如何创建c_int列表并一次添加一个元素(python)
以下是一些代码(来自文档): 我怎样才能做到:如何创建c_int列表并一次添加一个元素(python),python,ctypes,Python,Ctypes,以下是一些代码(来自文档): 我怎样才能做到: N = 5 IntArrayN = c_int * N ian = IntArrayN ian.append(5) ian.append(1) ian.append(7) ian.append(33) ian.append(99) 所以这会引发一个属性错误这是我能够做到的 arr=[] arr.append(5) arr.append(1) arr.append(7) arr.append(33) arr.append(99) ian=(c_i
N = 5
IntArrayN = c_int * N
ian = IntArrayN
ian.append(5)
ian.append(1)
ian.append(7)
ian.append(33)
ian.append(99)
所以这会引发一个属性错误这是我能够做到的
arr=[]
arr.append(5)
arr.append(1)
arr.append(7)
arr.append(33)
arr.append(99)
ian=(c_int*len(arr)(*arr)
print type(arr) # list
print type(ian) #__main.c_int_Array_N
输出
<type 'list'>
<class '__main__.c_int_Array_4'>
使用一个具有可变长度的列表,而不是定义为固定长度的c_int
数组。c_int*N
使用执行时的N
值,即5
,它不会使类型具有可变长度。从某种意义上讲,N在运行时之前是未知的,我明白这就是目的,我只是不明白当你显然需要一个可变长度的容器时,你为什么要首先尝试使用c_int
array。在这里列出清单绝对是正确的方法。不惜一切代价避免使用ctypes
。至少喜欢cffi
。
<type 'list'>
<class '__main__.c_int_Array_4'>