如何在Cython中正确管理C++对象的生命周期?

Jea*_*one 19 c++ python memory cython

在为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(); }
};
Run Code Online (Sandbox Code Playgroud)

这个库的一个重要方面是Sprocket析构函数使用了Widget*它,因此Widget必须在它之后才能销毁Sprocket它.

我写的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
Run Code Online (Sandbox Code Playgroud)

在构建Python构建之后:

$ cython --cplus somelib.pyx 
$ g++ -I/usr/include/python2.6 -L/usr/lib somelib.cpp -shared -o somelib.so
$
Run Code Online (Sandbox Code Playgroud)

在琐碎的情况下,它似乎工作:

$ 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
$
Run Code Online (Sandbox Code Playgroud)

cdef Widget领域保持PyWidget活着直到PySprocket.__dealloc__摧毁之后Sprocket.但是,一旦收集到Python垃圾,tp_clearCython构造的函数就会混淆PySprocket:

$ 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?
Run Code Online (Sandbox Code Playgroud)

由于存在引用循环,因此垃圾收集器调用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)
Run Code Online (Sandbox Code Playgroud)

换句话说,隐藏Cython中的引用以使其仍然有效__dealloc__,并手动对其进行引用计数.

ch0*_*kee 5

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
Run Code Online (Sandbox Code Playgroud)

我稍后回来查看我写的内容,因为我很累,但重要的是:重点是你要在销毁Widget时通知Sprockets,反之亦然.

这是一个通用的解决方案,可以调整.

你还必须包括错误处理,我绝对跳过了.与垃圾收集器无关,代码中存在设计问题.

编辑: 这些代码是等价的:
A

class BadWidget(PyWidget):
    pass
widget = BadWidget()
sprocket = PySprocket(widget)
widget.cycle = sprocket ###1
del widget ###2
del sprocket
Run Code Online (Sandbox Code Playgroud)

class BadWidget(PyWidget):
    pass
widget = BadWidget()
sprocket = PySprocket(widget)
sprocket.widget.cycle = sprocket ###1
del sprocket.widget ###2
del sprocket
Run Code Online (Sandbox Code Playgroud)

###2将调用sprocket.widget.__deallocate__()并且它不会释放sprocket.widget.cycle,因此链轮将在小部件中存活