为什么结构对齐方式在iOS中有所不同 [英] Why struct alignment different in iOS
问题描述
我已经将Xcode中的结构对齐方式设置为8字节压缩.例如:
I have set the struct alignment in Xcode to 8-byte packing. For example :
struct Info
{
unsigned short kindID;
char kindName[32];
int64_t gameMonery;
}__attribute__ ((aligned(8)));
在iPhone5和iPhone 5S中,此结构大小均为48字节, kindName
地址偏移量为2字节,但在iPhone5中, gameMoney
偏移量为36字节,在iPhone 5S的 gameMoney
偏移量为40字节.
This struct size is 48 byte, both in iPhone5 and iPhone 5S, the kindName
address offset is 2 byte, but in iPhone5 the gameMoney
offset is 36 byte, in iPhone 5S the gameMoney
offset is 40 byte.
为什么有这个不同?
推荐答案
64位类型( int64_t
)的对齐方式在32位平台上为4,在64位平台上为8.
The alignment of 64 bit types (int64_t
) is 4 on 32 bit platforms and 8 on 64 bit platforms.
通过在声明中添加 __ attribute __((packed))
,可以使编译器禁止单个元素的对齐.未结盟成员的访问速度稍慢.
You can make the compiler suppress alignment of individual elements by adding __attribute__((packed))
to the declaration. Access of unaligned members is somewhat slower.
两个平台上结构的大小之所以没有不同的原因是,其大小取决于结构的对齐方式(如8所示):
The reason why the size of the struct does not differ on both platforms is that the size is subject to the struct's alignment (as specified to 8):
示例:
struct { char i; } __attribute__((aligned(8))) foo;
sizeof(foo) == 8;
这篇关于为什么结构对齐方式在iOS中有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!