기본적으로 수정하려는 노드 테스트 케이스가 아주 간단합니다. 파이썬에서 생성 된 객체를 C++로 할당하는 방법은 무엇입니까?
나는아이가하는 AddChild 기능이 기능 자동 그래서 C에서 관련 클래스 (에 부모를 설정 한 다음
를 통해 할당 할 수있는 getChild과의 getParent 간단한 노드 클래스가 있습니다 ++ 측) 불행하게도
내가 파이썬 참조를 잃게 그렇게 ..
것 같아요 코드를 이해하는 것이 더해야한다 :
기본 메인 클래스의 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;
};
그런 다음 부스트 파이썬 바인딩 코드는 :
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)
;
내 파이썬 테스트 코드를 마치려면 :
>>> 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 기능
어떤 생각을 수정하는 방법을 모르겠어요?
정말 고마워요. 은이 같은 다른 I 외부 함수를 사용하고 용액 .. 것을 발견 '무효로 addChild (부스트 : shared_ptr의 pythis을 높일 :: shared_ptr의 노드) { \t pythis-> m_child = 노드; \t node-> m_parent = pythis; \t } –
user2111835
하지만 해결책이 좋습니다. 다른 사람이 동일한 문제가있는 경우 enable_shared_from_this에서 상속하면됩니다. addFunction에서 부모 포인터를 할당 할 수 있습니다. node-> m_parent = shared_from_this() ; 너무 쉽고 다시 감사드립니다! – user2111835