我刚刚花了大约 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)
最佳答案
大概是因为,正如 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.
关于python - 为什么分组的struct.pack会写入错误的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44239031/