Wrapping functions for ctypes

suggest change

In some cases, a C function accepts a function pointer. As avid ctypes users, we would like to use those functions, and even pass a Python function as an argument.

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)
<class 'ctypes.CFUNCTYPE.<locals>.CFunctionType'>

CFUNCTYPE returns that class, not an instance. The class denotes a function that returns a c_int (the first argument), and accepts two c_int arguments (the other arguments). Calling the class, as in the next snippet, creates the instance. On Python 3.14 the class prints as shown above.

Now let’s wrap the function:

>>> CFUNCTYPE(c_int, c_int, c_int)(max)
<CFunctionType object at 0xdeadbeef>

Function prototypes have one more usage: they can wrap a 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)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents