【问题标题】:Conventions for memory management and destructors / free() with Python's CFFI?Python CFFI 的内存管理和析构函数/free() 的约定?
【发布时间】:2015-08-28 22:30:38
【问题描述】:

如果我要包装一个 C 类:

from ._ffi import ffi, lib

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

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

cffi 是否有某种对象包装器,当 Python 对象被 GC'd 时会调用析构函数,例如:

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)

这里有哪些最佳做法?

【问题讨论】:

  • 两者都可以。 (“托管”()是“ffi.gc()”。)

标签: python python-cffi


【解决方案1】:

看起来ffi.gc() 是要走的路。这是我写的小包装器,它也做 post-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)

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 2019-07-03
    • 2023-02-09
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 2016-01-20
    • 2011-02-19
    相关资源
    最近更新 更多