1

尝试在 C++ 中建立具有父子关系的依赖项。父级包含子级,子级有一个指向父级的弱指针。

我还希望能够从 Python 中的父级派生。但是,当我这样做时,连接此父子关系时出现弱指针错误。

C++ 代码:

#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

using namespace boost;
using namespace boost::python;

struct Child;

struct Parent : public enable_shared_from_this<Parent>
{
    void initialize();
    shared_ptr<Child> m_child;
};

struct Child: public enable_shared_from_this<Child>
{
    void setParent(shared_ptr<Parent> ptr);
    weak_ptr<Parent> m_parent;
};

void Parent::initialize()
{
    shared_ptr<Child> ptr(new Child);
    m_child = ptr;

    m_child->setParent(shared_from_this());
}

void Child::setParent(shared_ptr<Parent> ptr)
{
    m_parent = ptr;
}

static PyObject* create(PyObject* object)
{
    PyObject* instance = PyObject_CallObject(object, NULL);

    Parent* parent = extract<Parent*>(instance);
    parent->initialize();

    return instance;
}

Python绑定:

BOOST_PYTHON_MODULE(test_module)
{
    class_<Parent>("Parent");

    def("create", &create);
} 

Python代码:

from test_module import *

class Test(Parent):
    def __init__(self):
        Parent.__init__(self)

n = create(Test)

错误:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    n = create(Test)
RuntimeError: tr1::bad_weak_ptr

如果我尝试将提取的指向 Parent 的指针转换为 shared_ptr,我会在 Python 中得到一个 free() 无效指针错误。

有没有办法解决这个问题,或者我应该放弃在 Boost Python 中使用弱指针?

4

2 回答 2

2

我玩了没有python东西的代码。

这重现了问题:

Parent* p(new Parent);
p->initialize();

问题是没有任何东西保留 shared_ptr 对象。这修复了它:

boost::shared_ptr<Parent> p(new Parent);
p->initialize();

Boost.Python 常见问题解答:“当从 Python 转换 shared_ptr 时,shared_ptr 实际上管理对包含 Python 对象的引用。当 shared_ptr 转换回 Python 时,库会检查它是否是那些“Python 对象管理器”之一如果是这样,则返回原始 Python 对象”

Parent* 需要以某种方式存储在 shared_ptr 中。我还没弄清楚怎么做。

Parent* parent = boost::python::extract<Parent*>(instance);
于 2009-11-01T11:51:02.943 回答
1

class_ 的接口允许您控制对象的持有方式。它是一个名为 HeldType 的模板参数。Boost.Python 文档中有更多关于 class_ 的信息,但您的 Python 绑定可能看起来更像这样:

class_<Parent, boost::shared_ptr<Parent> >("Parent");
于 2011-08-09T01:57:15.180 回答