Tutorial by Examples

Let's say we want to use libc's ntohl function. First, we must load libc.so: >>> from ctypes import * >>> libc = cdll.LoadLibrary('libc.so.6') >>> libc <CDLL 'libc.so.6', handle baadf00d at 0xdeadbeef> Then, we get the function object: >>> ntohl = l...
Failing to load a file The first possible error is failing to load the library. In that case an OSError is usually raised. This is either because the file doesn't exists (or can't be found by the OS): >>> cdll.LoadLibrary("foobar.so") Traceback (most recent call last): File &...
The most basic object is an int: >>> obj = ctypes.c_int(12) >>> obj c_long(12) Now, obj refers to a chunk of memory containing the value 12. That value can be accessed directly, and even modified: >>> obj.value 12 >>> obj.value = 13 >>> obj c_...
As any good C programmer knows, a single value won't get you that far. What will really get us going are arrays! >>> c_int * 16 <class '__main__.c_long_Array_16'> This is not an actual array, but it's pretty darn close! We created a class that denotes an array of 16 ints. Now al...
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 r...
Let's combine all of the examples above into one complex scenario: using libc's lfind function. For more details about the function, read the man page. I urge you to read it before going on. First, we'll define the proper prototypes: >>> compar_proto = CFUNCTYPE(c_int, POINTER(c_int), PO...

Page 1 of 1