Dear all,
currently, I am writing bindings of an amplitude analysis package (rootpwa, http://sourceforge.net/projects/rootpwa/) for python with boost::python. The analysis package uses a number of root classes which makes an interaction between pyroot and boost::python necessary.
For the most part, this works quite well. Unfortunately, I have run into a problem where I need some help: I am doing bindings for functions which return root objects. In python, the objects which are returned should behave like regular pyroot objects. I solved this with the following converter:
#include<TPython.h>
template<typename T>
PyObject* convertToPy(const T& cxxObj) {
T* newCxxObj = new T(cxxObj);
return TPython::ObjectProxy_FromVoidPtr(&newCxxObj, newCxxObj.ClassName());
};
Initially, I was assuming that the python garbage collection would take over the deletion of “newCxxObj”, but as it turns out, this is not the case, so the converter is a gaping memory leak. However, if I directly return a pointer to cxxObj, it might happen that cxxObj goes out of scope and I am returning a dangling pointer.
I also tried around with the boost::python return value policies, in particular return_value_policy<manage_new_object>(), but this results in a segmentation violation. I also stumbled upon the AsCObject() and SetOwnership(), but as far as I can tell, I cannot call these from C++ code, which would be necessary to check if they could solve my problem.
I would be very grateful if anybody had some input as to how to do this correctly. How can I create a pyroot object in C++ code which will be garbage collected?
Thank you very much in advance!
e_dude