Passing a callback function from Python to 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);}
from ctypes import CFUNCTYPEfrom ctypes import c_void_pfrom ctypes import POINTERfrom ctypes import c_intfrom ctypes import cdlllib = cdll.LoadLibrary('./')
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)



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Prince Francis

Prince Francis

Providing simple solutions for complex problems.