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

Best way to pass pointer to C function from Python using CFFI

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

int f(double* x);

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

# 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

我应该使用数组模块吗(例如,创建一个 "double" 大小为 1 的数组,将其传递给函数,然后 return 第一个索引)?是否有使用 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]