Python 和 C 结构之间的大小不匹配,默认结构对齐/填充

Posted

技术标签:

【中文标题】Python 和 C 结构之间的大小不匹配,默认结构对齐/填充【英文标题】:Size mismatch between Python and C struct with default struct alignment/padding 【发布时间】:2021-05-28 16:00:52 【问题描述】:

我有一个从 C 服务器发送到 Python 客户端的结构。 C结构如下:

// Data structure to be sent to python interface
typedef struct                                         //
    uint32_t componentType;                             // 4
    bool componentId_present;                           // 1 + 3 padding = 4
    uint32_t componentIdType;                           // 4 + 4 padding = 8
    long componentId;                                   // 8
    uint32_t componentConfigUpdate_type;                // 4 + 4 padding = 8
    bool componentConfigUpdate_s1AP_present;            // 1 + 3 padding = 4
    uint32_t componentConfigUpdate_s1AP_size;           // 4
    byte componentConfigUpdate_s1AP[128];               // 128
    bool componentConfigUpdate_x2AP_present;            // 1 + 3 padding = 4
    uint32_t componentConfigUpdate_x2AP_size;           // 4
    byte componentConfigUpdate_x2AP[128];               // 128
 data_E2setupRequest_NodeComponentConfigUpdate_t;      // 256 + 3*8 + 6*4 = 256 + 24 + 24 = 304

在 Python 中,我使用以下代码计算要接收的大小:

import struct
size = struct.calcsize("i?ili?i128s?i128s")             # returns 300

如您所见,大小不同:304 字节与 300 字节。我已阅读 this on *** 和 The Lost Ark of Structure Packing,但我无法解释为什么与 默认填充/打包规则存在这种差异。

无论如何,我通过以这种方式设置结构来解决(之前的 long var 一个地方):

typedef struct 
    uint32_t componentType;                             // 4
    bool componentId_present;                           // 1 + 3 padding = 4
    long componentId;                                   // 8
    uint32_t componentIdType;                           // 4 + 0 padding = 4
    uint32_t componentConfigUpdate_type;                // 4 + 0 padding = 4
    bool componentConfigUpdate_s1AP_present;            // 1 + 3 padding = 4
    ....
 data_E2setupRequest_NodeComponentConfigUpdate_t;      // 256 + 8 + 8*4 = 256 + 8 + 32 = 296

import struct
size = struct.calcsize("i?lii?i128s?i128s")             # returns 296

【问题讨论】:

在哪些架构上? (32/64 位,字节序...) 我正在从一个 little endian x86_64 GNU/Linux 编译 【参考方案1】:

来自struct module docs:

填充只会在连续的结构成员之间自动添加。编码结构的开头或结尾不添加任何填充。

您错误计算了 C 结构的填充 - 假设典型的结构布局和 8 字节长,sizeof(data_E2setupRequest_NodeComponentConfigUpdate_t) 将是 304 而不是 300,但 componentConfigUpdate_s1AP_present 实际上进入了您认为在 @ 之后填充的空间987654325@。额外的 4 个字节的填充实际上位于结构的末尾,struct 没有添加该填充。

同样来自struct 模块文档:

要将结构的结尾与特定类型的对齐要求对齐,请以该类型的代码结束格式,并且重复计数为零。

因此,如果您希望struct 将结构的末尾填充到long 对齐,您可以将0l 添加到格式字符串的末尾。

(另外,bool 是 1 个字节,而不是 4 个 - 在结构中的所有布尔值之后有 3 个字节的填充。您可以通过将所有布尔值彼此相邻来消除其中的一些填充。)

【讨论】:

以上是关于Python 和 C 结构之间的大小不匹配,默认结构对齐/填充的主要内容,如果未能解决你的问题,请参考以下文章

python第五天

指定的 DSN 中,驱动程序和应用程序之间的体系结构不匹配

C语言自定义类型重难点总结(结构体位段枚举联合)

结构体内存对齐

在 WPF 字体大小和“标准”字体大小之间转换

指定的 DSN 包含驱动程序和应用程序之间的体系结构不匹配错误