Marshal.SizeOf structure returns excessive number

浪子不回头ぞ 提交于 2019-12-01 17:54:36

You're running into a byte-alignment issue. In an attempt to keep fields on word boundaries for speed of access, the compiler is padding your string with 3 extra bytes. To fix this, use the Pack field of the StructLayoutAttribute.

[StructLayout(LayoutKind.Sequential, Pack=1)]  // notice the packing here
public struct SFHeader
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
    public string FileName;

    public int Offset;

    public short Size;

    public byte Flags;

    public byte Source;

    public long LastWriteTime;
}

You could use a fixed size buffer instead of a string.

[StructLayout(LayoutKind.Sequential)]
public unsafe struct SFHeader
{
    public fixed char FileName[5];
    public int Offset;
    public short Size;
    public byte Flags;
    public byte Source;
    public long LastWriteTime;

    public byte[] GetBytes()
    {
        //omitted
    }

    public static SFHeader FromBytes(byte[] buffer)
    {
        //omitted
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!