这是我的代码:
struct abc
{
short a;
byte b;
int c;
}
当我使用时:
Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(typeof(abc)));
它显示:8
,但它应该显示:7
因为在我的机器中:byte:1
,short:2
,int:4
bytes分别
为什么会这样?
如果由于填充而发生,如何在读取结构大小时禁用填充?因为我需要以字节为单位的结构的确切大小。这很重要。
答案 0 :(得分:6)
由于structure member alignment rules,它显示8
。
如果您想将struct
设置为未对齐,则需要StructLayout
使用Pack = 1
属性,如下所示:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct abc
{
short a;
byte b;
int c;
}
这应输出7
。