How to read a structure containing an array using Python and readinto types?

We have several binaries created by C.

One type of file is created by calling fwrite to write the following C structure to the file:

typedef struct {
   unsigned long int foo; 
   unsigned short int bar;  
   unsigned short int bow;

} easyStruc;

In Python, I read the structures of this file as follows:

class easyStruc(Structure):
  _fields_ = [
  ("foo", c_ulong),
  ("bar", c_ushort),
  ("bow", c_ushort)
]

f = open (filestring, 'rb')

record = censusRecord()

while (f.readinto(record) != 0):
     ##do stuff

f.close()

It works great. Our other file type is created using the following structure:

typedef struct {  // bin file (one file per year)
    unsigned long int foo; 
    float barFloat[4];  
    float bowFloat[17];
} strucWithArrays;

I am not sure how to create a structure in Python.

+5
source share
2 answers

According to this documentation page (section: 15.15.1.13. Arrays), it should look something like this:

class strucWithArrays(Structure):
  _fields_ = [
  ("foo", c_ulong),
  ("barFloat", c_float * 4),
  ("bowFloat", c_float * 17)]

Check the documentation page for other examples.

+9
source

ctypes. :

class structWithArray(Structure):
    _fields_ = [
      ("foo", c_ulong),
      ("barFloat", c_float * 4),
      ("bowFloat", c_float * 17)
    ]
+2

All Articles