2

我想为第三方库中的 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 的“双”数组,将其传递给函数,然后返回第一个索引)?是否有使用 ctypes 或 cffi 辅助函数的更轻量级的方法?

4

1 回答 1

2
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]
于 2017-08-14T08:26:53.770 回答