4

I created a C-library with a number of functions that I can call from python using ctypes. I've got my head around some of the simpler ones but I'm stumped by how I pass the right arguments to the following function:

foo(double *, double *, void(*f1)(double *, double *, double, struct sys *),
    void(*f2)(double *, double *, double, struct sys *), struct sys *, double *,
    double, double, int, int, gsl_rng *)

My starting point is setting the .argtypes for the function. I've got the double arrays sorted with POINTER(100*c_double) etc.

However, I am stuck on how to pass the function pointers. I have a number of functions (of the form of f1 and f2), which reside in the same library as foo that I would like to pass as arguments to foo.

I think I've managed pass the struct sys* pointer ok by using the following code:

class sys(Structure):
    _fields_ = [("alpha", c_double),
                ("sigma", c_double)]

and then using POINTER(sys) as the argtype there. Finally, the gsl_rng is a typical random number generator from the GNU Scientific Library; I don't know where to start here.

Can anybody shine some light on the complicated ctypes?

1 Answer 1

1

Function pointer types like this in ctypes seem to be somewhere between non-existent and undocumented, but you can still use them. The key is not to define argtypes at all.

From the ctypes documentation:

The function objects ... by default accept any number of arguments, accept any ctypes data instances as arguments, ...

Ergo, we should be able just to jam the pointers in there and hope for the best as long as we don't specify argtypes, and this approach actually turns out to work. Here's a simple working example:

f.c:

int f(int n, int (*h)(int)){ return (*h)(n); }
int g(int n){ return n+1; }

f.py:

import ctypes
so = ctypes.CDLL('/path/to/f.so')
f = so.f
g = so.g
print(f(3, g))

output:

$ gcc -o f.so -shared -fPIC f.c
$ python f.py
4

Of course, if you really want the type checking that ctypes does for you when you specify argtypes, then this doesn't help you. I don't know of any way to have that particular cake and eat it, too.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.