Passing a callback function from Python to C

To communicate between python and C, we have a library `ctypes`
Step — 1 : create a c program, in which one function receives another function pointer as parameter.
In the below example, the function divide
receives another function pointer as first parameter, which receives 2 parameters, quotient and remainder.
save the program as `division.c`
#include <stdio.h>void divide(void (*ptr)(int *, int *), int a, int b){ int s = a / b; int r = a % b; (*ptr) (&s, &r);}void print_sum(int * s, int * r){ printf("Quotient is %d, remainder is %d\n", *s, *r);
}int main(){ void (*ptr)() = &print_sum; divide(ptr, 7, 4);}
To run the above program
$gcc division.c
$./a.out
Now create a shared library
$gcc -fPIC -shared -o libdiv.so division.c
Step — 2 : Create a python program
from ctypes import CFUNCTYPEfrom ctypes import c_void_pfrom ctypes import POINTERfrom ctypes import c_intfrom ctypes import cdlllib = cdll.LoadLibrary('./libdiv.so')
CMPFUNC = CFUNCTYPE(c_void_p, POINTER(c_int), POINTER(c_int))def py_cmp_func(s, r): print (f'Quotient is {s[0]} , remainder is {r[0]}')cmp_func = CMPFUNC(py_cmp_func)lib.divide(cmp_func, 3, 5)
save the program as test.py in the same directory
Now run it
$python3 test.py
You will get the following output
Quotient is 0 , remainder is 3