Python ctypes:ctype数组中元素的类型
Python ctypes: the type of elements in a ctype array
我在 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 数组中 class。为方便起见,索引数组 returns Python 整数。如果您从 c_int
派生出 class,您可以抑制该行为:
>>> 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
我在 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 数组中 class。为方便起见,索引数组 returns Python 整数。如果您从 c_int
派生出 class,您可以抑制该行为:
>>> 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
:
>>> 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