3

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?

1 Answer 1

4
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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.