Wrapping functions for ctypes
suggest changeIn 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)
Found a mistake? Have a question or improvement idea?
Let me know.
Wrapping functions for ctypes
Table Of Contents
3 Filter
4 List
8 Loops
10 Comparisons
17 JSON Module
19 Metaclasses
21 Generators
23 Reduce
24 Map Function
26 Searching
27 Dictionary
28 Classes
29 Counting
32 Set
37 Unit Testing
42 Copying data
43 Tuple
46 Enum
48 Conditionals
49 Complex math
53 Networking
59 HTML Parsing
61 setup.py
62 List slicing
63 Sockets
65 Recursion
67 dis module
68 Type Hints
71 Exceptions
72 Web scraping
73 deque module
76 Overloading
77 Debugging
87 Indentation
90 urllib
91 Binary Data
93 Idioms
99 PostgreSQL
100 Descriptor
101 Common Pitfalls
102 Multiprocessing
105 Stack
106 Profiling
110 Logging
112 os module
114 Database Access
119 Mixins
120 Attribute Access
121 ArcPy
124 Websockets
127 Arrays
129 Polymorphism
133 2to3 tool
136 Unicode
137 ssh in Python
139 Neo4j
141 Curses
142 Templates
143 pass statement
145 Date Formatting
146 heapq
147 tkinter
148 CLI subcommands
150 SQLite3 module
153 Design Patterns
155 Audio
156 pyglet
157 queue module
158 ijson
160 base64 module
161 Flask
162 Groupby
164 pygame
166 hashlib
167 Gzip
168 ctypes
171 configparser
177 Unzipping Files
180 sys module
185 Python Lex-Yacc
186 pyaudio
187 shelve
192 Contributors