Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function pointer to an external program in Cython

Tags:

python

cython

I am trying to write a wrapper around a C program so that I can call it from Python. I am using Cython to do this. The C function takes a callback function as an argument, but this call back function will only be known at run-time of the python program. I have been searching how to do this and it seems there is not simple solution but the following seems to work:

#python.py

libc = cdll.LoadLibrary("myfunc.so") #Callback function is defined in myfunc.so 
....
c_wrapper(libc.fun, ...)

.

#c_wrapper.pyx

cdef extern void mainfunction(void *F, ...) #The intial C function we are wrapping
ctypedef void (*myfuncptr) () 

def c_wrapper(f, ...) # our function pointer is passed to the wrapper as a Python object
    cdef myfuncptr thisfunc
    thisfunc = (<myfuncptr*><size_t>addressof(f))[0]
    mainfunction(thisfunc, ...)

This method works for C and FORTRAN functions (i am assuming it will work for most compiled languges) and Python functions (using C types), but it seems a little awkward. Is there any more simple way of doing this in Cython?

Thanks

EDIT : I am unable to change the C library I am trying to wrap

like image 697
SimpleSimon Avatar asked Jan 10 '12 09:01

SimpleSimon


Video Answer


1 Answers

I guess you're aware of this?

Is it possible to call my Python code from C?

Answer: Yes, easily. Follow the example in Demos/callback/ in the Cython source distribution

So, knowing that you can dload your main function, let's take another approach. I wrote a couple of stupid functions to test this:

/* lib.c -> lib.so */
#include <stdio.h>

void fn1(void) {
        puts("Called function 1");
}

void fn2(void) {
        puts("Called function 2");
}

then, the function that takes the callback

/* main.c -> main.so */

typedef void (*callback)();

void mainfunction(void *F) {
        ((callback)F)();
}

Which can be passed directly from Python:

>>> from ctypes import cdll
>>> lib = cdll.LoadLibrary('./lib.so')
>>> main = cdll.LoadLibrary('./main.so')
>>> main.mainfunction(lib.fn1)
Called function 1
>>> main.mainfunction(lib.fn2)
Called function 2

And now, let's wrap a Python function:

>>> from ctypes import CFUNCTYPE
>>> def pyfn():
...     print "Called the Python function"
... 
>>> CWRAPPER = CFUNCTYPE(None)

>>> wrapped_py_func = CWRAPPER(pyfn)
>>> main.mainfunction(wrapped_py_func)
Called the Python function
like image 196
Ricardo Cárdenes Avatar answered Oct 20 '22 10:10

Ricardo Cárdenes