如何使用Python的ctypes和readinto读取包含数组的结构?

6 python ctypes

我们有一些由C程序创建的二进制文件.

通过调用fwrite将以下C结构写入文件来创建一种类型的文件:

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

} easyStruc;
Run Code Online (Sandbox Code Playgroud)

在Python中,我读取此文件的结构如下:

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()
Run Code Online (Sandbox Code Playgroud)

这很好.我们的其他类型的文件使用以下结构创建:

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

我不确定如何在Python中创建结构.

And*_*mbu 10

根据此文档页面(部分:15.15.1.13.数组),它应该是这样的:

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

查看该文档页面以获取其他示例.