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

6 投票
2 回答
4544 浏览
提问于 2025-04-15 14:24

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

其中一种文件是通过调用fwrite将以下C结构写入文件生成的:

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

} easyStruc;

在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()

这样做没问题。我们的另一种文件是使用以下结构创建的:

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

我不太确定如何在Python中创建这个结构。

2 个回答

2

文档中有一部分讲的是 ctypes中的数组。简单来说,这意味着:

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

根据这个文档页面(第15.15.1.13节:数组),应该是类似这样的:

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

可以查看那个文档页面,里面还有其他的例子。

撰写回答