Vasi Marin
Vasi Marin

Reputation: 483

Python ctypes: the type of elements in a ctype array

I have created in Python a ctype array in the following way:

list_1 = [10, 12, 13]
list_1_c = (ctypes.c_int * len(list_1))(*list_1)

When I do a print of the first element of list_1_c I get:

print list_1_c[0]
10

My question is why I don't get the result?

c_long(10)

If I do:

a = ctypes.c_int(10)
print a

I get

c_long(10)

I would have expected that the elements of the array list_1_c to be ctypes elements.

Upvotes: 0

Views: 1537

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177406

The values are stored internally as a C integer array of 3 elements, wrapped in a ctypes array class. Indexing the array returns Python integers as a convenience. If you derive a class from c_int you can suppress that behavior:

>>> import ctypes
>>> list_1 = [10, 12, 13]
>>> list_1_c = (ctypes.c_int * len(list_1))(*list_1)
>>> list_1_c  # stored a C array
<__main__.c_long_Array_3 object at 0x00000246766387C8>
>>> list_1_c[0]  # Reads the C int at index 0 and converts to Python int
10
>>> class x(ctypes.c_int):
...  pass
...
>>> L = (x*3)(*list_1)
>>> L
<__main__.x_Array_3 object at 0x00000246766387C8>
>>> L[0]  # No translation to a Python integer occurs
<x object at 0x00000246783416C8>
>>> L[0].value  # But you can still get the Python value
10

The reason for the convenience is you can't do much with a wrapped C-types value unless you you access its .value:

>>> ctypes.c_int(5) * 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'c_long' and 'int'
>>> ctypes.c_int(5).value * 5
25

Upvotes: 1

Related Questions