【问题标题】:Using Boost Python with Weak Ptrs?使用带有弱 Ptrs 的 Boost Python?
【发布时间】:2009-10-26 13:49:27
【问题描述】:

尝试在 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 中使用弱指针?

【问题讨论】:

    标签: c++ python boost weak-references boost-python


    【解决方案1】:

    我在没有 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);
    

    【讨论】:

      【解决方案2】:

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

      class_<Parent, boost::shared_ptr<Parent> >("Parent");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-10
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 2014-05-05
        • 1970-01-01
        • 1970-01-01
        • 2013-06-21
        相关资源
        最近更新 更多