Python / Cython / C and callbacks by calling a Python function from C using Cython

I have the following question. We need to pass the callback functions to C. If the function is a Keaton function in the same module, the situation is quite simple.

In Cython:

def callme(int x):
    c_callme(x, <int (*)(int)>&callbackme) 

cdef int callbackme(int x):
    print <int> x
    return <int>x

In C:

int c_callme(int x, int (*f)(int))
{
    printf("---%d\n",x);
    printf("--%d\n",f(x));
    return x;
}

The question is this: we want to generalize this code on the Pythonic path itself, so that it can also accept python functions as callback arguments (of course, an additional level is needed), as well as C / Cython functions from another module. I believe that for C / Cython functions from a separate module you need to get the address of these functions (convert to long int?), And for a Python function you need a certain shell

+5
source share
2 answers

Python Cubature integration C, Python C, , cfunction. , cfunction_cb ( ), , int ):

cdef object f
ctypedef int (*cfunction) (double a, double b, double c, void *args)

cdef int cfunction_cb(double a, double b, double c, void *args):
    global f
    result_from_function = (<object>f)(a, b, c, *<tuple>args)
    for k in range(fdim):
        fval[k] = fval_buffer[k]
    return 0

C C:

def main(pythonf, double a, double b, double c, args): 
    global f
    f = pythonf
    c_function( <cfunction> cfunction_cb,
                double a,
                double b,
                double c,
                <void *> args )

, Python C.

+9

, - C

cdef class Callback(object):
    cdef int (*f)(int)        # I hope I got the syntax right...

    def __call__(int x):
        return self.f(x)

, , .

, C, , Python, , `void *.

(, long, undefined. , -, void*.)

0

All Articles