简体   繁体   English

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

[英]Best way to pass pointer to C function from Python using CFFI

I want to create a Python wrapper to a C function in a thirdparty library that has a signature such as 我想在具有以下签名的第三方库中为C函数创建Python包装器

int f(double* x);

where the function f modifies the input argument x (ie, call by reference using a pointer). 函数f修改输入参数x (即使用指针通过引用进行调用)。 What is the most efficient way to implement a Python wrapper function so that the Python user can treat it like a function that just returns a new number each time? 什么是实现Python包装函数的最有效方法,以便Python用户可以将其视为每次都返回一个新数字的函数? Example pseudocode: 伪代码示例:

# 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

Should I use the array module (eg, create a "double" array of size 1, pass that to the function, and return the first index)? 我是否应该使用数组模块(例如,创建大小为1的“双精度”数组,将其传递给函数,然后返回第一个索引)? Is there a more lightweight approach that uses ctypes or cffi helper functions? 是否有使用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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM