我基本上有一个非常简单的节点测试用例,我正在尝试修复。
我有一个带有 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;
};
然后是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 来设置父级。不幸的是,我不知道发生了什么.. 我尝试使用 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 函数
任何想法 ?