开发者

ctypes initializing c_int array by reading file

Using a Python a开发者_运维百科rray, I can initialize a 32,487,834 integer array (found in a file HR.DAT) using the following (not perfectly Pythonic, of course) commands:

F = open('HR.DAT','rb')
HR = array('I',F.read())
F.close()

I need to do the same in ctypes. So far the best I have is:

HR = c_int * 32487834

I'm not sure how to initilize each element of the array using HR.DAT. Any thoughts?

Thanks,

Mike


File objects have a 'readinto(..)' method that can be used to fill objects that support the buffer interface.

So, something like this should work:

f = open('hr.dat', 'rb')
array = (c_int * 32487834)()
f.readinto(array)


Try something like this to convert array to ctypes array

>>> from array import array
>>> a = array("I")
>>> a.extend([1,2,3])
>>> from ctypes import c_int
>>> ca = (c_int*len(a))(*a)
>>> print ca[0], ca[1], ca[2]
1 2 3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜