编程语言
首页 > 编程语言> > 端口C对Python的fread(&struct,…)

端口C对Python的fread(&struct,…)

作者:互联网

嘿,我真的很挣这个.我试图将一小部分别人的代码移植到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中创建了一个Class’frame’并插入了相应的变量(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中“重组”数据,但我认为最好的方法是使用struct.

标签:c-3,python,struct,porting
来源: https://codeday.me/bug/20190827/1741046.html