【发布时间】: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 stackoverflow 和 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 编译
标签: python c python-3.x data-structures struct