如何在c ++中分配一个在python中创建的对象?

时间:2013-02-26 15:39:15

标签: c++ python boost boost-python make-shared

我基本上有一个非常简单的节点测试用例,我正在尝试修复。

我有一个带有getChild和getParent

的简单Node类

可以通过addChild函数

分配子项

然后这个函数自动在相关类上设置父类(所以从c ++方面)

不幸的是,当我这样做时,我失去了python引用..

我想代码应该更好理解:

基本主要类MyNode

class MyNode
{
public:
    MyNode(): m_name("unknown") {}
    MyNode(std::string name): m_name(name) {}
    MyNode(MyNode * const o) : m_name(o->m_name) {}
    virtual ~MyNode() {}

    std::string getName() const { return m_name; }
    void setName(std::string name) { m_name = name; }
    boost::shared_ptr<MyNode> getChild() const { return m_child; }
    const boost::shared_ptr<MyNode> & getParent() const { return m_parent; }

    void addChild(boost::shared_ptr<MyNode> node) {
        m_child = node;
        node->m_parent = boost::make_shared<MyNode>(this);
    }

private:
    std::string m_name;
    boost::shared_ptr<MyNode> m_parent;
    boost::shared_ptr<MyNode> m_child;
};

然后提升python绑定代码

class_< MyNode, boost::shared_ptr<MyNode>/*, MyNodeWrapper*/ >("MyNode", init<std::string>())
    .add_property( "Name", &MyNode::getName, &MyNode::setName )
    .add_property( "Child", &MyNode::getChild )
    .add_property( "Parent", make_function(&MyNode::getParent, return_internal_reference<>()))
    .def( "addChild", &MyNode::addChild )
    ;

完成我的python测试代码

>>> p=MyNode("p")
>>> o=MyNode("o")
>>> p.addChild(o)
>>> o.Parent
<hello_ext.MyNode object at 0x01C055A8>   << this is not equal to p
>>> p
<hello_ext.MyNode object at 0x01C06510>   << as you can see p here
>>> o.Parent
<hello_ext.MyNode object at 0x01C055A8>   << but at least the pointer doesn't change each time the Parent is called !
>>> p.Child == o                          << so for the child it works
True
>>> o.Parent == p                         << but it doeesn't work for Parent
False

问题肯定在addFunction以及我如何使用boost :: make_shared设置父级。 遗憾的是我不知道发生了什么...... 我试过使用一个boost包装器:

struct MyNodeWrapper : public MyNode, public boost::python::wrapper<MyNode>
{
    MyNodeWrapper( PyObject * a_PyObj ) : m_Self( a_PyObj ) {}
    MyNodeWrapper( PyObject * a_PyObj, const MyNode & a_Vec ) : MyNode( a_Vec ), m_Self( a_PyObj ) {}
    MyNodeWrapper( PyObject * a_PyObj, std::string name ) : MyNode( name ) , m_Self( a_PyObj ) {}

    PyObject * m_Self;
};

但我仍然不确定如何修改addChild函数

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你不能这样做:

    node->m_parent = boost::make_shared<MyNode>(this);

没有boost::enable_shared_from_this。见What is the usefulness of `enable_shared_from_this`?