如果我想拥有在C中malloc
的指针的所有权,则docs for the Python cffi
package和this answer表示将ffi.gc
与lib.free
一起使用破坏者。但是,在执行此操作时,我接到AttributeError: free
的呼叫时得到lib.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*);
""")
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
答案 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)