Options For Callback From Python To C++
Solution 1:
A function pointer does not have any space to store extra information. Therefore it is not possible to convert a Python callable to a function pointer in pure C. Similarly a cdef
function of a cdef class
must store the address of the instance to be usable and that is impossible too.
You have three options:
Use
ctypes
as in https://stackoverflow.com/a/34900829/4657412 (the bottom half of the answer shows how to do it).ctypes
accomplishes this with runtime code generation (and thus only works on processors that it explicitly supports).Use a
std::function
in C++ instead of a function pointer. These can store arbitrary information. You need to write an object wrapper (or re-use one from elsewhere) so it isn't completely pure Cython. See Pass a closure from Cython to C++. What you're trying to do is probably better covered by How to use a Cython cdef class member method in a native callback.Use the class C scheme where the callback is of type
void (CallbackT)(/* any args */, void* user_data)
and is registered with:
void register_callback(CallbackT func, void* user_data)
In this case
user_data
would be the address of yourB
instances (and you'd need to make sure it wasPy_INCREF
ed before setting the address andPy_DECREF
ed before unsetting the address). Cython callback with class method provides an example.
Post a Comment for "Options For Callback From Python To C++"