2

I'm exposing a C++ tree class using Boost.Python to python. The node class holds a list of child nodes and provides a method

void add_child(Node *node)

The Node class takes ownership of the provided Node pointer and deletes it's child nodes when the destuctor gets called.

I'm exposing the add_child method as:

.def("addChild", &Node::add_child)

My actual question is: How do i tell Boost.Python that the Node class takes ownership of the child nodes?

Because if i execute the following code in python:

parentNode = Node()
node = Node()
parentNode.addChild(node)

the object referenced by the node variable gets deleted twice at the end of the script. Once when the node variable gets deleted and a second time when the parentNode gets deleted.

1 Answer 1

3

Answering my own question:

I've missed an FAQ entry in the Boost.Python documentation that gave me the right hint:

//The node class should be held by std::auto_ptr
class_<Node, std::auto_ptr<Node> >("Node")

Create a thin wrapper function for the add_child method:

void node_add_child(Node& n, std::auto_ptr<Node> child) {
   n.add_child(child.get());
   child.release();
}

Complete code to expose the node class:

//The node class should be held by std::auto_ptr
class_<Node, std::auto_ptr<Node> >("Node")
//expose the thin wrapper function as node.add_child()
.def("addChild", &node_add_child)
;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.