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

标签 python ctypes

我们有一些由 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/

相关文章:

python - 使用 ctypes 将字符串作为 char 指针数组传递

python - 如何将 ctypes C 指针转换为 Numpy 数组?

python - cx_freeze 通过 Python Wand (imagemagick)

python - 在 Python 3.7 中安装 TA-Lib 时遇到问题

python - 循环任务遍历所有输入文件 python

.net - 模拟多个IP地址进行测试

python - Django 在函数内重定向

python - 在 python 中使用 DLL - 无法找到函数或类

python - 如何从 ctypes 使用 IFileOperation

python - 使用 SWIG 使用 3rd-Party 驱动程序构建 Python 模块