如何在Cython中正确管理C++对象的生命周期?
在为一个C++库写Cython封装时,我遇到一个问题,就是不太清楚什么时候该删除某些C++实例。
这个C++库大概是这样的:
#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(); }
};
这个库的一个重要特点是,Sprocket
的析构函数会使用它接收到的Widget*
,所以在Sprocket
被销毁之前,Widget
不能被销毁。
我写的Cython封装大致是这样的:
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
在这样构建Python版本后:
$ cython --cplus somelib.pyx
$ g++ -I/usr/include/python2.6 -L/usr/lib somelib.cpp -shared -o somelib.so
$
在简单的情况下,它似乎是有效的:
$ python -c 'from somelib import PyWidget, PySprocket
spr = PySprocket(PyWidget())
del spr
'
PySprocket dealloc with widget <somelib.PyWidget object at 0xb7537080>
Widget::foo a widget
PyWidget dealloc
Widget destruct
$
cdef Widget
字段会保持PyWidget
的存活,直到PySprocket.__dealloc__
销毁Sprocket
。但是,一旦Python的垃圾回收机制介入,Cython为PySprocket
构建的tp_clear
函数就会搞砸这一切:
$ python -c 'from somelib import PyWidget, PySprocket
class BadWidget(PyWidget):
pass
widget = BadWidget()
sprocket = PySprocket(widget)
widget.cycle = sprocket
del widget
del sprocket
'
PyWidget dealloc
Widget destruct
PySprocket dealloc with widget None
Widget::foo ��h�
由于存在引用循环,垃圾回收器会调用tp_clear
来尝试打破这个循环。Cython的tp_clear
会删除所有对Python对象的引用。只有在这个操作完成后,PySprocket.__dealloc__
才会被执行。
Cython的文档警告了关于__dealloc__
的使用(虽然我花了一段时间才弄明白它所说的条件,因为没有详细说明)。所以也许这种方法根本就不适用。
Cython能支持这种用法吗?
作为我希望是一个临时的解决办法,我转向了这样一种方法:
cdef class PySprocket:
cdef void *widget
cdef Sprocket *thisptr
def __init__(self, PyWidget widget):
Py_INCREF(widget)
self.widget = <void*>widget
self.thisptr = new Sprocket(self.widget.thisptr)
def __dealloc__(self):
del self.thisptr
Py_DECREF(<object>self.widget)
换句话说,就是把引用隐藏起来,这样在__dealloc__
中它仍然有效,并且手动进行引用计数。
1 个回答
cdef extern from "somelib.h":
cdef cppclass Widget:
pass
cdef cppclass Sprocket:
Sprocket(Widget*)
cdef class PyWidget:
cdef Widget *thisptr
cdef set sprockets
def __init__(self):
self.thisptr = new Widget()
self.sprockets = set()
def __dealloc__(self):
print 'PyWidget dealloc'
#PyWidget knows the sprockets and notifies them on destroy
sprockets_to_dealloc = self.sprockets.copy()
#with this solution spr items can call back to detach
for spr in sprockets_to_dealloc:
del spr
del self.thisptr
def attach(PySprocket spr):
print 'PySprocket attach'
self.sprockets.add(spr)
def detach(PySprocket spr):
print 'PySprocket detach'
self.sprockets.remove(spr)
cdef class PySprocket:
cdef PyWidget widget
cdef Sprocket *thisptr
def __init__(self, PyWidget widget):
self.thisptr = new Sprocket(widget.thisptr)
#You should be sure here that the widget exists
widget.attach(self)
self.widget = widget
def __dealloc__(self):
self.widget.detach(self)
del self.thisptr
我稍微晚了一点再来看我写的内容,因为我有点累,但这里有重点:你需要在销毁Widget的时候通知Sprockets,反之亦然。
这是一个通用的解决方案,可以根据需要进行调整。
你还得考虑错误处理,我完全跳过了这一部分。这和垃圾回收器没关系,实际上是你代码里的设计问题。
编辑:这些代码是等价的:
A
class BadWidget(PyWidget):
pass
widget = BadWidget()
sprocket = PySprocket(widget)
widget.cycle = sprocket ###1
del widget ###2
del sprocket
B
class BadWidget(PyWidget):
pass
widget = BadWidget()
sprocket = PySprocket(widget)
sprocket.widget.cycle = sprocket ###1
del sprocket.widget ###2
del sprocket
###2
会调用 sprocket.widget.__deallocate__()
,但它并不会释放 sprocket.widget.cycle
,所以sprocket会在widget被销毁后继续存在。