6

我有以下结构

[StructLayout(LayoutKind.Sequential)]
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;


    public byte[] GetBytes()
    {
        int size = Marshal.SizeOf(this);
        var buffer = new byte[size];
        IntPtr ptr = Marshal.AllocHGlobal(size);

        Marshal.StructureToPtr(this, ptr, true);
        Marshal.Copy(ptr, buffer, 0, size);
        Marshal.FreeHGlobal(ptr);

        return buffer;
    }


    public static SFHeader FromBytes(byte[] buffer)
    {
        var str = new SFHeader();
        int size = Marshal.SizeOf(str);

        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.Copy(buffer, 0, ptr, size);
        str = (SFHeader)Marshal.PtrToStructure(ptr, str.GetType());
        Marshal.FreeHGlobal(ptr);

        return str;
    }

}

我需要将我的结构转换为字节数组(使用套接字作为数据包发送),所以我使用该GetBytes方法,但它返回一个字节数组24而不是21字节数组:

  • 文件名(字符串):5 个字节
  • 偏移量(int):4 字节
  • 大小(短):2 字节
  • 标志(字节):1 字节
  • 源(字节):1字节
  • LastWriteTime(长):8 字节

所以:5+4+2+1+1+8 = 21 个字节。
发生这种情况是因为Marshal.SizeOf返回 24,为什么?似乎多余的字节放在字符串的字节之后,实际上例如以下结构:

var header = new SFHeader()
{
   FileName = "aaaa",
   Offset = 1,
   Size = 1
};

转换为以下缓冲区:

[0] = 97
[1] = 97
[2] = 97
[3] = 97
[4] = 0
[5] = 0
[6] = 0
[7] = 0
[8] = 1
[9] = 0
[10] = 0
[11] = 0
[12] = 1
[13] = 0
... The following are all zero (0)

第五个、第六个和第七个是多余的字节。我怎么解决这个问题?

4

2 回答 2

10

您遇到了字节对齐问题。为了使字段保持在字边界上以提高访问速度,编译器会string用 3 个额外字节填充您。要解决此问题,请使用Pack.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;
}
于 2012-11-05T14:32:50.300 回答
0

您可以使用固定大小的缓冲区而不是字符串。

[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
    }
}
于 2012-11-05T14:35:05.313 回答