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>

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 CFUNCTYPE

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

Providing simple solutions for complex problems.