简体   繁体   中英

How to read a structure containing an array using Python's ctypes and readinto?

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.

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

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

Check that documentation page for other examples.

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)
    ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM