Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Chapter 189: ctypes

ctypes is a python built-in library that invokes exported functions from native compiled libraries.

Note: Since this library handles compiled code, it is relatively OS dependent.

Section 189.1: ctypes arrays


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 all we need to do is to initialize it:

>>> arr = (c_int * 16)(*range(16))


>>> arr
<__main__.c_long_Array_16 object at 0xbaddcafe>

Now arr is an actual array that contains the numbers from 0 to 15.

They can be accessed just like any list:

>>> arr[5]
5
>>> arr[5] = 20
>>> arr[5]
20

And just like any other ctypes object, it also has a size and a location:

>>> sizeof(arr)
64 # sizeof(c_int) * 16
>>> hex(addressof(arr))
'0xc000l0ff'

Section 189.2: Wrapping functions for ctypes


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)

GoalKicker.com – Python® Notes for Professionals 718

You might also like