我们有一些由 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 中创建结构。
最佳答案
根据这个documentation page (部分:15.15.1.13。阵列),它应该是这样的:
class strucWithArrays(Structure):
_fields_ = [
("foo", c_ulong),
("barFloat", c_float * 4),
("bowFloat", c_float * 17)]
查看该文档页面以获取其他示例。
关于python - 如何使用 Python 的 ctypes 和 readinto 读取包含数组的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1444159/