I am trying to write a binding to a C-Library that uses callback functions.
A function interface may look like:
int do_something(int a, void (*callback));
And i want to map it the same way in python so someone can write:
def callback(val):
print val
do_something(1, callback)
So the Python call do_something
should call the C-Function do_something
. And the Python function callback
should be connected to the C-Functions callback
.
How should I approach this?
Very thanks in advance!
The simplest approach should be defining, for each C function, a Python Wrapper, and using them. As a C function cannot be directly a Python Callable, this is a nice way of packing it.
Another approach should be defining your own class in the C extension which includes the method call . Through this C Python function, you can manage whatever you want and perform the connection to C function callbacks. The object becomes the generic callback, or subclass, or...
If you want to keep everything on the C level, then use Python Capsules to pass around the C function pointers. But then the callback is at a C level and not at a Python level.
To be more precise, you need to give further information of type of callbacks, quantity, variety, domain, etc. I cannot think of a universal way of achieving your goal, but I can imagine a variety of scenarios and implementations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.