When writing a Cython wrapper for a C++ library, I've encountered a case where it's not clear how to correctly decide when to delete certain C++ instances.
The C++ library looks something like this:
#include <stdio.h>
#include <string.h>
class Widget {
char *name;
public:
Widget() : name(strdup("a widget")) {}
~Widget() { printf("Widget destruct\n"); }
void foo() { printf("Widget::foo %s\n", this->name); }
};
class Sprocket {
private:
Widget *important;
public:
Sprocket(Widget* important) : important(important) {}
~Sprocket() { important->foo(); }
};
An important aspect of this library is that the Sprocket destructor uses the Widget* it was given, so the Widget must not be destroyed until after the Sprocket has been.
The Cython wrapper I've written looks like this:
cdef extern from "somelib.h":
cdef cppclass Widget:
pass
cdef cppclass Sprocket:
Sprocket(Widget*)
cdef class PyWidget:
cdef Widget *thisptr
def __init__(self):
self.thisptr = new Widget()
def __dealloc__(self):
print 'PyWidget dealloc'
del self.thisptr
cdef class PySprocket:
cdef PyWidget widget
cdef Sprocket *thisptr
def __init__(self, PyWidget widget):
self.widget = widget
self.thisptr = new Sprocket(self.widget.thisptr)
def __dealloc__(self):
print 'PySprocket dealloc with widget', self.widget
del self.thisptr
After building the Python build like this:
$ cython --cplus somelib.pyx
$ g++ -I/usr/include/python2.6 -L/usr/lib somelib.cpp -shared -o somelib.so
$
In the trivial case, it appears to work:
$ python -c 'from somelib import PyWidget, PySprocket
spr = PySprocket(PyWidget())
del spr
'
PySprocket dealloc with wid