4

Using a Python array, 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

2 Answers 2

11

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this worked, and is very efficient. Please edit so I can vote up (locked it yesterday by accident).
1

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

1 Comment

The problem with that is *a returns a tuple of array elements, which needs to load the whole thing into memory (if a was an iterator) and then convert to Python types (only to convert back into ctypes).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.