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

2024-06-01 07:41:02 发布

您现在位置:Python中文网/ 问答频道 /正文

<>当为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*,因此{}必须在{}之后被销毁。在

我写的Cython包装是这样的:

^{pr2}$

在像这样构建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__销毁{}之后。但是,一旦涉及到Python垃圾收集,用于PySprockettp_clear函数Cython就会把事情搞砸:

$ 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 ^{}(尽管我花了一段时间才了解它所讨论的是什么条件,因为它没有涉及任何细节)。因此,也许这种方法是完全无效的。在

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__中仍然有效,并手动对其进行引用计数。在


Tags: selffoowidgetcythonclassdelcdefimportant
1条回答
网友
1楼 · 发布于 2024-06-01 07:41:02
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

我晚一点回来检查我写的东西,因为我很累, 但重要的是:关键是你 想要在销毁小工具时通知链轮,反之亦然。在

这是一个通用的解决方案,可以调高。在

你还必须包括错误处理,我完全跳过了。 垃圾回收器的设计没有任何问题。在

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

^{pr2}$

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,因此链轮将在小部件中继续存在

相关问题 更多 >