尝试使用父子关系在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的弱指针?

有帮助吗?

解决方案

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

这再现了问题:

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

问题是什么都没有抓住shared_ptr对象。 这解决了它:

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

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

Parent *需要以某种方式存储在shared_ptr中。我还没想出来。

Parent* parent = boost::python::extract<Parent*>(instance);

其他提示

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

class_<Parent, boost::shared_ptr<Parent> >("Parent");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top