嘿,我真的很纠结这个问题。我正在尝试将一小段别人的代码移植到 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/