I want to use an event based Python library in a C application. I use the offical C-API for embedding Python: http://docs.python.org/2/c-api/index.html#c-api-index
It is no problem to call methods from C and collect return values. However, I don’t know how to do the following:
Several of the python library functions take what I think is a python function pointer as an argument.
Is it possible, when calling these methods from C, to pass a C function pointer so the Python function uses a C function as callback?
If not, how to accomplish having Python use a C callback?
This is harder than one would expect, but it can be done.
If you have a single C function that you want to provide as a callback, you can use
PyCFunction_Newto convert it into a Python callable:This approach won’t work if you want to choose different callbacks at run-time, e.g. to provide a generic
c_to_pythonfunction that converts a C callback function to a Python callback. In that case, you’ll need to implement an extension type with its owntp_call.This code is trivially extended for the to also accept a
user_datapointer; just store the user data in theCallbackObjectstruct.