python - 将 C 的 fread(&struct,....) 移植到 Python

标签 python c struct porting

嘿,我真的很纠结这个问题。我正在尝试将一小段别人的代码移植到 Python,这就是我所拥有的:

typedef struct
{
  uint8_t Y[LUMA_HEIGHT][LUMA_WIDTH];
  uint8_t Cb[CHROMA_HEIGHT][CHROMA_WIDTH];
  uint8_t Cr[CHROMA_HEIGHT][CHROMA_WIDTH];
} __attribute__((__packed__)) frame_t;

frame_t frame;

 while (! feof(stdin))
  {
    fread(&frame, 1, sizeof(frame), stdin);

    // DO SOME STUFF
  }

稍后我需要像这样访问数据:frame.Y[x][y]

所以我在 Python 中创建了一个“框架”类,并插入了相应的变量(frame.Y、frame.Cb、frame.Cr)。 我曾尝试按顺序将数据从 Y[0][0] 映射到 Cr[MAX][MAX],甚至打印出 C 结构的作用,但没能完全理解用于放置数据的方法在那里。我整晚都在为此苦苦挣扎,今晚必须回到军队,所以非常欢迎和感谢任何直接的帮助。

谢谢

最佳答案

你必须使用 struct python标准模块。
从其文档(添加了重点):

This module performs conversions between Python values and C structs represented as Python strings. It uses format strings (explained below) as compact descriptions of the lay-out of the C structs and the intended conversion to/from Python values. This can be used in handling binary data stored in files or from network connections, among other sources.

注意:由于你最后读取的数据是统一格式的,你也可以使用array模块,然后在 Python 中“重构”数据,但我认为最好的方法是使用结构。

关于python - 将 C 的 fread(&struct,....) 移植到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2616680/

相关文章:

python - 如何使用子字符串格式化 JSON 项目 OrderedDic 转储 - PYTHON 3

PYTHON-2.x 第 1 行出现语法错误,但我没有看到任何错误?

python - 如何撤消 Django 中未完成迁移的更改

c - 尝试将数字存储在数组中并通过从文件中读取来显示它们

c - RL_ARM的TCP模式下close和abort的区别

c - 我这样做对吗?将结构中的指针映射到结构外部以供 IPC 共享内存使用

c - C中的结构类型转换

python - Beautiful Soup 和字符编码

c - getutent 和 Linux 计时器问题

C结构语法问题