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

后端 未结 2 1718
日久生厌
日久生厌 2020-12-30 15:49

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

2条回答
  •  轮回少年
    2020-12-30 16:16

    I think the easiest way would be to wrap C callbacks in

    cdef class Callback(object):
        cdef int (*f)(int)        # I hope I got the syntax right...
    
        def __call__(int x):
            return self.f(x)
    

    so you can pass objects of this type, as well as any other callable, to the function that must call the callback.

    However, if you must call the callback from C, then you should may pass it an extra argument, namely the optional address of a Python object, perhaps cast to `void*.

    (Please do not cast function pointers to long, or you may get undefined behavior. I'm not sure if you can safely cast a function pointer to anything, even void*.)

提交回复
热议问题