相等的 ctypes 数组对象缺少属性“值”
Missing attribute `value` for equal ctypes array objects
我知道从 python 序列 data = (1, 2, 3, 4, 5, 6)
.
创建 c 数组的两种方法
正在创建一个数组 class,对其进行初始化并通过 value
属性传递值:
array_type = ctypes.c_int * len(data)
array1 = array_type()
array1.value = data
创建数组 class 并在初始化期间将值作为参数传递:
array_type = ctypes.c_int * len(data)
array2 = array_type(*data)
# Or 'array2 = (ctypes.c_int * len(data))(*data)'
两者生成相同的类型:
>>> array1
<c_int_Array_6 object at 0x1031d9510>
>>> array2
<c_int_Array_6 object at 0x1031d9400>
但是在尝试访问值属性时:
array1.value
>>> (1, 2, 3, 4, 5, 6, 7, 8, 9)
array2.value
>>> AttributeError: 'c_int_Array_6' object has no attribute 'value'
为什么 array2
没有 value
属性?我的理解是这些数组是同一类型,只是初始化方式不同。
即使我用两个不同的值创建两个不同的数组,问题仍然存在:
char_array = (c_char * 4)(*data)
print(char_array.value) # Works!
int_array = (c_int * 4)(*data)
print(int_array.value) # Doesn't work!
您将 array1.value
定义为 data
。但是你没有具体定义array2.value
。默认情况下 .value
未定义(即使数组包含值)。
>>> 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)
如您所见,您仍然可以使用标准 python 调用列表来访问 array2
的值。
您可以查看 Python 的文档,尤其是 fundamental data types and on arrays and pointers。
我知道从 python 序列 data = (1, 2, 3, 4, 5, 6)
.
正在创建一个数组 class,对其进行初始化并通过 value
属性传递值:
array_type = ctypes.c_int * len(data)
array1 = array_type()
array1.value = data
创建数组 class 并在初始化期间将值作为参数传递:
array_type = ctypes.c_int * len(data)
array2 = array_type(*data)
# Or 'array2 = (ctypes.c_int * len(data))(*data)'
两者生成相同的类型:
>>> array1
<c_int_Array_6 object at 0x1031d9510>
>>> array2
<c_int_Array_6 object at 0x1031d9400>
但是在尝试访问值属性时:
array1.value
>>> (1, 2, 3, 4, 5, 6, 7, 8, 9)
array2.value
>>> AttributeError: 'c_int_Array_6' object has no attribute 'value'
为什么 array2
没有 value
属性?我的理解是这些数组是同一类型,只是初始化方式不同。
即使我用两个不同的值创建两个不同的数组,问题仍然存在:
char_array = (c_char * 4)(*data)
print(char_array.value) # Works!
int_array = (c_int * 4)(*data)
print(int_array.value) # Doesn't work!
您将 array1.value
定义为 data
。但是你没有具体定义array2.value
。默认情况下 .value
未定义(即使数组包含值)。
>>> 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)
如您所见,您仍然可以使用标准 python 调用列表来访问 array2
的值。
您可以查看 Python 的文档,尤其是 fundamental data types and on arrays and pointers。