Ctypes initializes the c_int array by reading a file

Using the Python array, I can initialize the 32 487 834 integer array (found in the HR.DAT file) using the following commands (not quite Pythonic, of course):

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 am not sure how to initialize each element of the array with HR.DAT. Any thoughts?

Thank,

Mike

+3
source share
2 answers

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

So something like this should work:

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

- , ctypes

>>> 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
+1

Source: https://habr.com/ru/post/1752559/


All Articles