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


Now create a shared library

$gcc -fPIC -shared -o division.c

Step — 2 : Create a python program

from ctypes import CFUNCTYPE

save the program as in the same directory

Now run it


You will get the following output

Quotient is 0 , remainder is 3

Providing simple solutions for complex problems.