我用Python在以下方式创建了一个ctype数组:
list_1 = [10, 12, 13]
list_1_c = (ctypes.c_int * len(list_1))(*list_1)
当我打印list_1_c的第一个元素时,我得到:
print list_1_c[0]
10
我的问题是为什么我没有得到结果?
c_long(10)
如果我做:
a = ctypes.c_int(10)
print a
我明白了
c_long(10)
我原以为数组list_1_c的元素是ctypes元素。
这些值在内部存储为3个元素的C整数数组,包含在ctypes数组类中。索引数组返回Python整数是为了方便。如果你从c_int
派生一个类,你可以抑制这种行为:
>>> 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
为方便起见的原因是,除非您访问其.value
,否则对包装的C类型值不能做太多:
>>> 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