Marshal.SizeOf显示错误输出的结构

时间:2018-03-28 05:47:21

标签: c# struct types sizeof

这是我的代码:

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分别

为什么会这样?

如果由于填充而发生,如何在读取结构大小时禁用填充?因为我需要以字节为单位的结构的确切大小。这很重要。

1 个答案:

答案 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