gpt4 book ai didi

python - 使用 CFFI 从 Python 传递指针到 C 函数的最佳方法

转载 作者:行者123 更新时间:2023-12-01 02:41:35 24 4
gpt4 key购买 nike

我想为第三方库中的 C 函数创建一个 Python 包装器,其签名如下

int f(double* x);

其中函数f修改输入参数x(即使用指针通过引用调用)。实现 Python 包装函数以便 Python 用户可以将其视为每次仅返回新数字的函数的最有效方法是什么?伪代码示例:

# lib and ffi are imported from a compiled cffi.FFI() object
def python_f():
??? double x; ???
rc = lib.f(&x)
assert rc == 0
return x

我应该使用数组模块(例如,创建一个大小为 1 的“ double ”数组,将其传递给函数,并返回第一个索引)?是否有更轻量级的方法使用 ctypes 或 cffi 辅助函数?

最佳答案

def python_f():
x_ptr = ffi.new("double[1]")
x_ptr[0] = old_value
rc = lib.f(x_ptr)
assert rc == 0
return x_ptr[0]

关于python - 使用 CFFI 从 Python 传递指针到 C 函数的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45656902/

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