for循环崩溃python

时间:2017-07-12 17:48:52

标签: python arrays pointers for-loop ctypes

我有一个用ctypes包装在Python中的C库,我在下面有这个DLL 当我要求时打印出时间值。但不是经历 每个项目并手动要求它打印出50000个值的时间。我想我创建了一个for循环,但它无法正常工作。

以下是我的代码的一个小例子:

import ctypes
from ctypes import *

MultiF = (b'path_to_file')   
dll = CDLL('path_to_dll') 

PN = ctypes.c_char_p(b'Paramter_name')
startTime = ctypes.c_double(-value)
stopTime = ctypes.c_double(value)
DT_RETURN = 0x0100
DT_FLOAT = 0x0001
convertType = (DT_RETURN|DT_FLOAT)
Null = 0


dll.readSParm.argtypes = (POINTER(SFile), c_char_p, c_double, c_double, c_double, POINTER(TTag), c_ushort,)   
dll.readSParm.restype = POINTER(SParm)

g = dll.readSParm(f, PN, startTime, stopTime, Null, None, convertType)

print(g[0].time[0])
print(g[0].time[1])
print(g[0].time[50000])

这些是代码给我的返回值:

-1031.0762939453125
-1031.0362548828125
0.0

我希望最终将所有这些数字都放到一个数组中,以便绘制图形。 所以我创建了一个失败的for循环:

time = (g[0].time)
for i in time:
    print(time[1])

这只会反复打印第一个值,直到Python崩溃。 我的问题是: 如何让它在循环中运行并打印出所有50000个值?

修改

这有效:

 time = (g[0].time)
 for i in time:
    print(i)

然后它崩溃了Python

2 个答案:

答案 0 :(得分:1)

你打印时间[1]而不是时间[i]。此外,现在我是每个元素的价值本身。

如果你想迭代列表的所有索引并打印每个索引的值(这是我想你想要的),你需要做

for i in range(len(time))

将您的代码更改为

time = (g[0].time)
for i in range(len(time)):
    print(time[i])

答案 1 :(得分:0)

如果time实际上是您要打印的值列表,那么这应该可以解决问题:

for v in time:
    print v