Marshal.SizeOf structure returns excessive number

后端 未结 2 1968
囚心锁ツ
囚心锁ツ 2021-01-18 21:02

I have the following structure

[StructLayout(LayoutKind.Sequential)]
public struct SFHeader
{

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
    pu         


        
2条回答
  •  轮回少年
    2021-01-18 21:44

    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;
    }
    

提交回复
热议问题