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

如果我想拥有在C中malloc的指针的所有权,则docs for the Python cffi package和this 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

python参考方案

文档并没有坚持这一点,但是您需要像其他任何函数一样,将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)

AttributeError:模块“ tensorflow”没有属性“ keras” - python

最初使用下面的代码加载CIFAR-10数据集。(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() 但是,将Keras安装到环境后,运行上述行会导致错误:>>> AttributeError: module 'tensorflow&…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

如何在python中将从PDF提取的文本格式化为json - python

我已经使用pyPDF2提取了一些文本格式的发票PDF。我想将此文本文件转换为仅包含重要关键字和令牌的json文件。输出应该是这样的:#PurchaseOrder {"doctype":"PO", "orderingcompany":"Demo Company", "su…

查找字符串中的行数 - python

我正在创建一个python电影播放器​​/制作器,我想在多行字符串中找到行数。我想知道是否有任何内置函数或可以编写代码的函数来做到这一点:x = """ line1 line2 """ getLines(x) python大神给出的解决方案 如果换行符是'\n',则nlines …