【发布时间】:2010-12-21 17:10:13
【问题描述】:
在为 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 文档warns about __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)
换句话说,对 Cython 隐藏引用,使其在 __dealloc__ 中仍然有效,并手动对其进行引用计数。
【问题讨论】:
-
string.h和stdio.h不是有效的 C++ 头文件; C++ 等价物是<cstring>和<cstdio>,你真的真的不应该使用它们。为什么你会考虑否认自己std::string的力量,尤其是当性能显然不是问题时(考虑到你已经在 Python 中完成了一半的工作)? -
@Karl:它们在 C++ 中有效:标准的 D.5。
-
@Steve 合法但恕我直言不道德 ;)
-
名称字段是一种证明存在问题的方法。我实际上是要进行段错误,但只能设法获取一些垃圾数据(至少在我的系统上)。我认为 char* 可以替换为 std::string 而不会对问题产生实质性影响。不过,感谢您对标题名称的提醒。