[C++-sig] How to deep-copy and delete a mixed python/C++ object from C++
achim-bpl at mol-net.com
Fri Mar 31 10:48:01 CEST 2006
I have a base class in C++ (MyClass), a wrapper class for boost::python
(Wrapper) and a class derived from that in Python (MyPythonClass) that
implements a pure virtual function of MyClass. So far so good.
However, when I copy an object of Wrapper in C++, the new instance still
points to the old python object and calls to the virtual function implemented
in python will access the old data. I had hoped that the wrapper<MyClass>
base class would copy the python object and everything would work.
Furthermore, I want to be able to delete the object (in C++) through the
pointer to its base class (it is stored in a std::vector<MyClass*>, together
with MyClass objects completely implemented in C++). If I do now, the Python
object stays around, still holds a pointer to a now dead object and at some
point tries to kill it with not-so-nice consequences.
How can I achieve both correct copying and deletion semantics ?
I built a work-around: Wrapper is copied by a clone() function, that looks up
the definition of the Python class (MyPythonClass) and, creates a new object
from this class and then fills in the missing data (no data on the Python
side, inheritance is only for overwriting virtual functions). However, then I
get a lifetime problem with the object. Currently, I directly use
Py_INCREF(copy) to keep it alive to the end of program runtime and then get
an error message, beacuse the C++ object was already deleted when the
std::vector<MyClass*> was cleaned up.
More information about the Cplusplus-sig