Python Language ctypes arrays


Example

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'