Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a CFuncType in Python

I need to pass a callback function that is CFuncType (ctypes.CFUNCTYPE or ctypes.PYFUNCTYPE...).

How can I cast a python function to CFuncType or how can I create a CFuncType function in python.

like image 496
manson54 Avatar asked Apr 28 '10 12:04

manson54


1 Answers

I forgot how awesome ctypes is:

Below is Copied from http://docs.python.org/library/ctypes.html

So our callback function receives pointers to integers, and must return an integer. First we create the type for the callback function:

CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))

For the first implementation of the callback function, we simply print the arguments we get, and return 0 (incremental development ;-):

 def py_cmp_func(a, b):
     print "py_cmp_func", a, b
     return 0

Create the C callable callback:

cmp_func = CMPFUNC(py_cmp_func)
like image 184
Adam Gent Avatar answered Oct 25 '22 08:10

Adam Gent