In some cases, a C function accepts a function pointer. As avid
ctypes users, we would like to use those functions, and even pass python function as arguments.
Let's define a function:
>>> def max(x, y): return x if x >= y else y
Now, that function takes two arguments and returns a result of the same type. For the sake of the example, let's assume that type is an int.
Like we did on the array example, we can define an object that denotes that prototype:
>>> CFUNCTYPE(c_int, c_int, c_int) <CFunctionType object at 0xdeadbeef>
That prototype denotes a function that returns an
c_int (the first argument), and accepts two
c_int arguments (the other arguments).
Now let's wrap the function:
>>> CFUNCTYPE(c_int, c_int, c_int)(max) <CFunctionType object at 0xdeadbeef>
Function prototypes have on more usage: They can wrap
ctypes function (like
libc.ntohl) and verify that the correct arguments are used when invoking the function.
>>> libc.ntohl() # garbage in - garbage out >>> CFUNCTYPE(c_int, c_int)(libc.ntohl)() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: this function takes at least 1 argument (0 given)