简体   繁体   English

序列化二进制结构gcc vs cl

[英]Serializing binary struct gcc vs cl

Full disclosure - this is homework, although completed and fully working, I'm searching for a nicer solution. 全面披露-这是家庭作业,尽管已完成且可以正常运行,但我正在寻找更好的解决方案。

I have a binary file, which was created by a program compiled within Visual Studio (I believe). 我有一个二进制文件,它是由Visual Studio(我相信)中编译的程序创建的。 The structure looks something like this. 结构看起来像这样。

struct Record {
    char c;
    double d;
    time_t t;
};

The size of this structure on Windows with Visual Studio 2008 gives 24 bytes. 在带有Visual Studio 2008的Windows上,此结构的大小为24个字节。 1 + 8 + 8 = 24 . 1 + 8 + 8 = 24 So there's some padding going on. 因此,正在进行一些填充。 The same structure on Linux and gcc gives 16 bytes. 在Linux和gcc上,相同的结构提供16个字节。 1 + 8 + 4 = 16 . 1 + 8 + 4 = 16 To line this up I added some padding and changed time_t to another type. 为此,我添加了一些填充并将time_t更改为另一种类型。 So then my struct looks like this. 所以我的结构看起来像这样。

struct Record {
    char c;
    char __padding[7];
    double d;
    long long t;
};

This now works and gcc gives its size as 24 bytes, but it seems a little dirty. 现在可以正常工作了,gcc的大小为24字节,但似乎有点脏。 So two questions.. 所以有两个问题。

Why is this implemented differently between the two compilers? 为什么在两个编译器之间实现不同?

Are there any __attribute__ ((aligned)) -type options or any other cleaner solutions for this? 是否有__attribute__ ((aligned)) -type选项或任何其他更清洁的解决方案?

The difference stems from whether we 32bit align doubles by default or 64bit align doubles by default. 差异源自我们默认情况下是32位对齐双精度还是默认情况下64位对齐双精度。 On a 32 bit machine, having a double on a 64 bit boundary may have some benefits but is probably not huge. 在32位计算机上,在64位边界上加倍可能会有一些好处,但可能并不大。 VC is then probably more careful about this than gcc. 这样,VC可能比gcc更谨慎。

The botton line is that if you are using structs for serialization you should ALWAYS make them packed (ie 8 bit aligned) and then do the alignment by hand. botton行是,如果您使用结构进行序列化,则应始终将其打包(即8位对齐),然后手动进行对齐。 This way your code is sure to be compatible across platforms. 这样,您的代码就可以确保跨平台兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM