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

How to assign in c++ an object created in python?

本文关键字:创建 对象 python 分配 c++      更新时间:2023-10-16

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

我有一个简单的Node类,它有一个getChild和一个getParent

可以通过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;
};

然后boost 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来设置父级。不幸的是,我不知道发生了什么。。我试过使用一个增强包装器:

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函数

知道吗?

你不能这样做:

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

没有CCD_ 1。请参阅"enable_shared_from_this"的作用是什么?