Search code examples
c#layoutstructurepinvoke

What is the difference between these 2 structures


There are 2 ways I can define this structure which I wish to pass as an argument to a pinvoke function. I wanted to know what was the difference between the 2

[StructLayout(LayoutKind.Sequential)]
public struct Rect {
   public int left;
   public int top;
   public int right;
   public int bottom;
}   

[StructLayout(LayoutKind.Explicit)]
public struct Rect {
   [FieldOffset(0)] public int left;
   [FieldOffset(4)] public int top;
   [FieldOffset(8)] public int right;
   [FieldOffset(12)] public int bottom;
}

From the definitions of layouts I found here, shouldnt both look the same in memory? Any advantages of one over the other?


Solution

  • From the definitions of layouts I found here, shouldn't both look the same in memory?

    Yes, they will look the same in memory.

    Any advantages of one over the other?

    One's faster to type out, and is easier to read.


    The use of FieldOffset is of course a useful tool; it's not like it's always useless, but if you just so happen to use it to explicitly lay out the fields in the manor in which they would be laid out by default, then it's useless. If you use it to lay out fields in a manor other than their default value (for example, having the overlap, adding padding space, having the underlying representation be in a different order than the declaration order, etc.), then it's not useless.