如何在c++中分配在python中创建的对象
How to assign in c++ an object created in python?
我基本上有一个非常简单的节点测试用例要修复。
我有一个简单的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"的作用是什么?
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- 创建对象并防止被破坏
- 在C++中,友元类可以从友元类创建对象吗
- 只在堆中创建C++对象
- 创建用户定义的复制构造函数时无法创建对象