为什么分组的struct.pack会写入错误的数据?

2024-06-02 17:20:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我只花了约30分钟调试和反复检查Python&;C代码,以发现我的struct.pack写入了错误的数据。当我把它分成不同的调用时,它工作得很好

这是我以前吃过的

file.write(struct.pack("fffHf", kf_time / frame_divisor, kf_in_tangent, kf_out_tangent, kf_interpolation_type, kf_value))

这就是我现在拥有的

file.write(struct.pack("f", kf_time / frame_divisor))
file.write(struct.pack("f", kf_in_tangent))
file.write(struct.pack("f", kf_out_tangent))
file.write(struct.pack("H", kf_interpolation_type))
file.write(struct.pack("f", kf_value))

为什么第一个变体没有写入我期望的数据?和单独写这些东西有什么不同

(文件以二进制模式打开,平台为64位Windows,Python 3.5)


Tags: 数据intimevaluetypetangentoutframe
1条回答
网友
1楼 · 发布于 2024-06-02 17:20:46

大概是因为,正如struct文档明确指出的那样:

Note By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.

相关问题 更多 >