簡體   English   中英

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

[英]How can C++ object lifetimes be correctly managed in 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(); }
};

這個庫的一個重要方面是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垃圾, tp_clear函數Cython為PySprocket構造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�

由於存在引用循環,垃圾收集器會調用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)

換句話說,隱藏Cython中的引用,使其在__dealloc__仍然有效,並手動對其進行引用計數。

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,反之亦然。

這是一個通用的解決方案,可以調整。

你還必須包括錯誤處理,我絕對跳過了。 與垃圾收集器無關,代碼中存在設計問題。

編輯:這些代碼是等於:
一個

class BadWidget(PyWidget):
    pass
widget = BadWidget()
sprocket = PySprocket(widget)
widget.cycle = sprocket ###1
del widget ###2
del sprocket

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將在窗口小部件中存活

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM