tags:

views:

83

answers:

1

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.

+3  A: 

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)
Adam Gent
Oh, yeah! That just did the trick. thanks.I pass that cpm_func to a ctypes.Structure that has a field'callback', ctypes.CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
manson54