Gabe Hackebeil
Gabe Hackebeil

Reputation: 1436

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 (i.e., 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 (e.g., 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?

Upvotes: 3

Views: 1794

Answers (1)

Armin Rigo
Armin Rigo

Reputation: 13000

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]

Upvotes: 4

Related Questions