使用Python的CFFI进行内存管理和析构函数的约定/free()? [英] Conventions for memory management and destructors / free() with Python's CFFI?
本文介绍了使用Python的CFFI进行内存管理和析构函数的约定/free()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我要包装C类:
from ._ffi import ffi, lib
class MyClass(object):
def __init__(self):
self._c_class = lib.MyClass_create()
确保调用lib.MyClass_destroy(…)
的最佳做法是什么?
What are best practices for making sure that lib.MyClass_destroy(…)
is called?
cffi
是否在对象周围有某种包装器,当对Python对象进行GC处理时,这些包装器将调用析构函数,例如:
Does cffi
have some sort of wrapper around objects that will call a destructor when the Python object is GC'd, for example something like:
my_obj = managed(lib.MyClass_create(), destructor=lib.MyClass_destroy)
还是应该在类的__del__
中使用析构函数逻辑?像这样:
Or should that destructor logic be in the class's __del__
? Something like:
class MyClass(object):
def __del__(self):
if self._c_class is not None:
lib.MyClass_destroy(self._c_class)
这里的最佳做法是什么?
What are the best practices here?
推荐答案
看起来ffi.gc()
是可行的方式.这是我写的小型包装程序,它也执行后malloc NULL
检查:
It looks like ffi.gc()
is the way to go. This is the small wrapper I've written which also does the post-malloc NULL
check:
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)
这篇关于使用Python的CFFI进行内存管理和析构函数的约定/free()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文