I worked with Cython trying to interact with a library written in C ++. So far, everything is going well, and I can effectively use the MOST functions in the library. My only problem is implementing callbacks. The library has 4 function definitions that look something like this:
typedef void (*Function1)(const uint16_t *data, unsigned width, unsigned height); void SetCallBack(Function1);
So, to implement them, I decided that with cython I would do something like this:
ctypedef void (*Function1)(unsigned short *data, unsigned width, unsigned height); cdef extern from "lib.hpp": void SetCallBack(Function1)
What really compiles correctly, however, for my life I cannot think of how to really implement this in such a way that the callback works. At first, I tried to create a function that would just call it, just like you would for any other function, by inventing the following:
def PySetCallBack(Func): SetCallBack(Func)
but this gives me a (predictable) error:
"Cannot convert Python object to" Function1 "
so yes I'm here. If anyone has experience setting up callbacks in Cython, I would really appreciate any help. Thanks.
Edit : Following your advice, I created an intermediate cdef function that looks like this:
cdef void cSetCallBack(Function1 function): SetCallBack(function)
It seems to bother me ... Closer? At least get another error:
error: invalid conversion from 'void (*)(short unsigned int*, unsigned int, unsigned int)' to 'void (*)(const uint16_t*, unsigned int, unsigned int)'
Now, as far as I can tell, these types are identical, so I can not understand what is happening.
Edit2 : Fixed this problem by declaring a new typedef:
ctypedef unsigned short uint16_t
and using this as an argument to call, but apparently it didnβt quite come nearer, it just took me to the side track, because when I try to call this function I get the same "Cannot convert Python object to Error" Function1 " again.
So, I almost returned to where I started. The only thing I can do now is to explicitly indicate that the python object comes in as a c function like this, but to be honest, I have no idea how I would do it.
Edit third : Okay, after analyzing your answer, I finally get it, and it works, so cheers and much more. What I ended up creating a function like this:
cdef void cSetCallback(Function1 function): SetCallback(function) cdef void callcallback(const_ushort *data, unsigned width, unsigned height): global callbackfunc callbackfunc(data,width,height) cSetCallback(callcallback) def PySetCallback(callbackFunc): global callbackfunc callbackfunc = callbackFunc
So, the only problem is that it cannot convert const_ushort * data to a python object, but this is another problem completely, so I think this problem is solved. Many thanks.