如果我正在包装C类:
from ._ffi import ffi, lib
class MyClass(object):
def __init__(self):
self._c_class = lib.MyClass_create()
确保调用lib.MyClass_destroy(…)
的最佳做法是什么?
cffi
是否有某种类型的包装器,当Python对象是GC时会调用析构函数,例如:
my_obj = managed(lib.MyClass_create(), destructor=lib.MyClass_destroy)
或者该析构函数逻辑应该在类__del__
中吗?类似的东西:
class MyClass(object):
def __del__(self):
if self._c_class is not None:
lib.MyClass_destroy(self._c_class)
这里的最佳做法是什么?
答案 0 :(得分:2)
看起来ffi.gc()
是要走的路。这是我写过的小包装器,它也会进行后malloc NULL
检查:
def managed(create, args, free):
o = create(*args)
if o == ffi.NULL:
raise MemoryError("%s could not allocate memory" %(create.__name__, ))
return ffi.gc(o, free)
例如:
c_class = managed(lib.MyClass_create, ("some_arg", 42),
lib.MyClass_destroy)