gpt4 book ai didi

python - 属性错误: free when taking ownership or freeing cdata

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:54 29 4
gpt4 key购买 nike

如果我想获得在 C 中进行 malloc 的指针的所有权,则 docs for the Python cffi packagethis answer假设使用 ffi.gclib.free 作为析构函数。但是,当我这样做时,我在调用 lib.free 时收到 AttributeError: 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

最佳答案

文档并没有强调这一点,但您需要将 free 作为库的 cdef 的一部分公开,就像任何其他函数一样,以便在Python 端。将 void free(void *ptr); 放入对 ffi.cdef 的调用中,并且 free 函数将通过 lib 可用。编译后免费:

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)

关于python - 属性错误: free when taking ownership or freeing cdata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55198286/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com