tags:

views:

233

answers:

2

We have some binary files created by a C program.

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

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

} easyStruc;

In Python, I read the structs 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()

That works fine. Our other type of file 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'm not sure how to create the structure in Python.

+4  A: 

Accordingly to this documentation page (section: 15.15.1.13. Arrays) it should became something like:

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

Check that documentation page, there are some example there.

Andrea Ambu
Thanks! Not sure how I missed that one.
+1  A: 

There's a section about arrays in ctypes in the documentation. Basically this means:

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