2013-02-26 41 views
2

我基本上有一個非常簡單的節點測試用例,我試圖修復。如何在C++中分配一個在python中創建的對象?

我有一個getChild和的getParent簡單Node類

子可以通過的addChild函數

然後該功能自動設置父上的相關類(因此從c被分配++側)

不幸的是,當我這樣做,我失去了蟒蛇參考..

我猜代碼應該是更好的理解:

基本主類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來設置父級。 我遺憾的是不知道發生了什麼事.. 我試着使用升壓包裝:

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

你不能做到這一點:

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

沒有boost::enable_shared_from_this。見What is the usefulness of `enable_shared_from_this`?

+0

非常感謝! 我發現了另一個解決方案,其中我被利用外部函數..是這樣的: '空隙的addChild(升壓:: shared_ptr的 pythis,升壓:: shared_ptr的節點) { \t pythis-> m_child =節點; \t node-> m_parent = pythis; \t }' – user2111835 2013-02-28 15:32:29

+0

但你的解決方案更好..所以如果別人有同樣的問題,你所要做的就是繼承自enable_shared_from_this然後addFunction可以像這樣分配父指針:node-> m_parent = shared_from_this() ; 太容易了,再次感謝! – user2111835 2013-02-28 15:36:10