Layout of .NET value type in memory

前端 未结 3 1547
滥情空心
滥情空心 2021-01-01 23:03

I have the following .NET value types:

[StructLayout(LayoutKind.Sequential)]
public struct Date
{
    public UInt16 V;
}

[StructLayout(LayoutKind.Sequential         


        
相关标签:
3条回答
  • 2021-01-01 23:32

    The info you get from the Marshal class is only relevant if the type actually gets marshaled. The internal memory layout of a managed structure is not discoverable through any documented means, other than peeking at the assembly code perhaps.

    Which means the CLR is free to reorganize the layout of the structure and optimize the packing. Swapping the D and V fields makes your structure smaller due the alignment requirements of a double. It saves 6 bytes on your 64-bit machine.

    Not sure why this would be an issue for you, it shouldn't be. Consider Marshal.StructureToPtr() to get the structure laid-out the way you want it.

    0 讨论(0)
  • 2021-01-01 23:42

    Two things:

    • StructLayout(Sequential) does not guarantee packing. You might want to use Pack=1, otherwise 32 and 64bit platforms might be different.

    • and string is a reference, not a pointer. If the string length is always fixed, you might want to use fixed char arrays:

      public struct MyArray // This code must appear in an unsafe block
      {
          public fixed char pathName[128];
      }
      
    0 讨论(0)
  • 2021-01-01 23:51

    If you need explicit layout... use explicit layout...

    [StructLayout(LayoutKind.Explicit)]
    public struct StringPair
    {
        [FieldOffset(0)] public String A;
        [FieldOffset(8)] public String B;
        [FieldOffset(16)] public String C;
        [FieldOffset(24)] public Date D;
        [FieldOffset(32)] public double V;
    }
    
    0 讨论(0)
提交回复
热议问题