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 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)

Feedback about page:

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


ctypes:
* Wrapping functions for ctypes

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve