4

如果我要包装一个 C 类:

from ._ffi import ffi, lib

class MyClass(object):
     def __init__(self):
         self._c_class = lib.MyClass_create()

确保lib.MyClass_destroy(…)调用的最佳实践是什么?

当 Python 对象被 GC 处理时,确实cffi有一些对象包装器会调用析构函数,例如:

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)

这里有哪些最佳实践?

4

1 回答 1

2

看起来ffi.gc()是要走的路。这是我编写的小包装器,它也进行了后 mallocNULL检查:

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)
于 2015-06-13T02:58:44.533 回答