I know 2 ways of creating a c array out of a python sequence data = (1, 2, 3, 4, 5, 6)
.
Creating an array class, initializing it and passing the values through the value
attribute:
array_type = ctypes.c_int * len(data) array1 = array_type() array1.value = data
Creating an array class and passing the value as arguments during initialization:
array_type = ctypes.c_int * len(data) array2 = array_type(*data) # Or 'array2 = (ctypes.c_int * len(data))(*data)'
Both generates the same type:
>>> array1 <c_int_Array_6 object at 0x1031d9510> >>> array2 <c_int_Array_6 object at 0x1031d9400>
But when trying to access the value attribute:
array1.value >>> (1, 2, 3, 4, 5, 6, 7, 8, 9) array2.value >>> AttributeError: 'c_int_Array_6' object has no attribute 'value'
Why doesn’t array2
has a value
attribute? My understanding is that these arrays are the same type but just initialized differently.
And even if I create two different arrays with two different values, the problem still occurs:
char_array = (c_char * 4)(*data) print(char_array.value) # Works! int_array = (c_int * 4)(*data) print(int_array.value) # Doesn't work!
Advertisement
Answer
You define array1.value
as data
. But you didn’t specifically define array2.value
. By default .value
is not define (even if the array contains the values).
>>> import ctypes >>> # Same commands that you provide >>> # ... >>> array1.value (1, 2, 3, 4, 5, 6) >>> array2.value Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'c_int_Array_6' object has no attribute 'value' >>> list(array2) [1, 2, 3, 4, 5, 6] >>> array2[0] 1 >>> data_bis = (1,4,5) >>> array2.value = data_bis >>> array2 <__main__.c_int_Array_6 object at 0x7f86dc981560> >>> array2.value (1, 4, 5)
As you can see, you can still have access to the values of array2
using standard python call for list.
You can have a look at Python’s documentation, especially on fundamental data types and on arrays and pointers.