AttributeError:获取所有权或释放cdata时释放

时间:2019-03-16 15:13:44

标签: python python-cffi

如果我想拥有在C中malloc的指针的所有权,则docs for the Python cffi packagethis answer表示将ffi.gclib.free一起使用破坏者。但是,在执行此操作时,我接到AttributeError: free的呼叫时得到lib.freelib.free在哪里定义?

from tempfile import TemporaryDirectory
from weakref import WeakKeyDictionary

from cffi import FFI

common_header = """
typedef struct {
  int32_t length;
  double* values;
} my_struct;
"""

# FFI
ffi = FFI()

ffi.cdef(common_header + """
int func(my_struct*);
""")
ffi.set_source('_temp', common_header + """
int func(my_struct *input) {
  double* values = malloc(sizeof(double) * 3);
  input->length = 3;
  input->values = values;
  return 0;
}
""")

with TemporaryDirectory() as temp_dir:
    lib_path = ffi.compile(tmpdir=temp_dir)

    lib = ffi.dlopen(lib_path)

    func = lib.func

# Using the library
my_struct = ffi.new('my_struct*')
func(my_struct)

# Taking ownership of the malloced member
global_weakkey = WeakKeyDictionary()
global_weakkey[my_struct] = ffi.gc(my_struct.values, lib.free)
# AttributeError: free

1 个答案:

答案 0 :(得分:0)

文档并没有说明这一点,但是您需要像其他任何函数一样,将free作为lib cdef的一部分公开,以便在Python端进行访问。将void free(void *ptr);放入对ffi.cdef的调用中,编译后即可通过free使用lib.free函数:

from tempfile import TemporaryDirectory
from weakref import WeakKeyDictionary

from cffi import FFI

common_header = """
typedef struct {
  int32_t length;
  double* values;
} my_struct;
"""

# FFI
ffi = FFI()

ffi.cdef(common_header + """
int func(my_struct*);
void free(void *ptr); // <-- Key to lib.free working later
""")
ffi.set_source('_temp', common_header + """
int func(my_struct *input) {
  double* values = malloc(sizeof(double) * 3);
  input->length = 3;
  input->values = values;
  return 0;
}
""")

with TemporaryDirectory() as temp_dir:
    lib_path = ffi.compile(tmpdir=temp_dir)

    lib = ffi.dlopen(lib_path)

    func = lib.func

# Using the library
my_struct = ffi.new('my_struct*')
func(my_struct)

# Taking ownership of the malloced member
global_weakkey = WeakKeyDictionary()
global_weakkey[my_struct] = ffi.gc(my_struct.values, lib.free)
相关问题