Skip to main content
 首页 » 编程设计

python之如何使用 ctypes 读取压缩结构

2024年11月01日11rubylouvre

在 python 中有没有一种方法可以使用结构解压使用 #pragma pack(x) 或 __attribute__((packed)) 创建的 C 结构?

或者,如何确定 python 结构处理填充的方式?

请您参考如下方法:

使用 struct类。

它在字节顺序(大端与小端)和对齐(打包)方面非常灵活。参见 Byte Order, Size, and Alignment .它默认为 native 字节顺序(意思是 python 是编译过的)。

原生示例

C:

struct foo { 
    int  bar; 
    char t; 
    char x; 
} 

python :

struct.pack('IBB', bar, t, x)