Sequential
C#
//Sequential,按最大成员长度进行对齐,占用内存将是 最大长度成员的整数倍长度
[StructLayout(LayoutKind.Sequential)]
struct Struct1
{
public short Short1;
public int Int1;
public short Short2;
}
//总共占用12字节,每行4字节,两个short各占一半,剩余填充,int占一行
1 Short1 | --------
2 Int1
3 Short2 | --------
//如果 int 改为 long,占用内存将变为 24字节=8*3
[StructLayout(LayoutKind.Sequential)]
struct Struct1
{
public int Int1;
public short Short1;
public short Short2;
}
//每行4字节,两个short占行,int占一行
1 Int1
2 Short1 | Short2
//如果 int 改为 long,占用内存将变为 16字节=8*2
Auto,由CLR自动调整,尽量少占用内存
Explicit 精确对齐,手动设置偏移进行对齐
C#
//总共8字节 Int1占0-3,Short1占4-5,Short2占6-7,
[StructLayout(LayoutKind.Explicit)]
struct Struct1
{
[FieldOffset(0)]
public int Int1;
[FieldOffset(4)]
public short Short1;
[FieldOffset(6)]
public short Short2;
}