简体   繁体   中英

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

int f(double* x);

where the function f modifies the input argument x (ie, call by reference using a pointer). 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? 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)? Is there a more lightweight approach that uses ctypes or cffi helper functions?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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