6

I'm fiddling with calling DLLs from C#, and came across the need to define my own structs. Lots of articles force a sequential layout for the struct with

[StructLayout(LayoutKind.Sequential)]
struct Foo ...

So, I followed suite, and my programme worked. Now, when I took the line out, it still works. Why do I need it?

biozinc
  • 4,629
  • 2
  • 25
  • 28

3 Answers3

5

The internal layout of a managed struct is undocumented and undiscoverable. Implementation details like member order and packing are intentionally hidden. With the [StructLayout] attribute, you force the P/Invoke marshaller to impose a specific layout and packing.

That the default just happens to match what you need to get your code to work is merely an accident. Although not an uncommon one. Note the Type.StructLayoutAttribute property.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    Thanks for the answer. I just had a look at StructLayoutAttribute of my struct with and without that line. Seems both give me sequential. Is that the default? – biozinc Dec 26 '08 at 16:57
  • 3
    This is an old answer, but perhaps it's worth noting that it is not entirely correct. The fact that the code worked as expected without the attribute was due to the fact that LayoutKind.Sequential is applied to all structs by default: [MSDN](https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute(v=vs.110).aspx#Anchor_7): "C#, Visual Basic, and C++ compilers apply the Sequential layout value to structures by default. For classes, you must apply the LayoutKind.Sequential value explicitly. (...)" – Sly May 15 '18 at 11:49
1

Interesting point. I'm sure I had code that failed until I put in an explicit LayoutKind.Sequential, however I have confirmed Sequential is the default for structures even in 1.1.

Note the VB Reference for Structure implies at Remarks > Behaviour > Memory Consumption that you do need to specify StructLayout to confirm the memory layout, but the documentation for StructLayoutAttribute states Sequential is the default for structures in Microsoft compilers.

Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
0

I am not entirely sure, but it may affect binary serialization - it might spit out the fields in order with not naming or ordering information (resulting in a smaller file), but that is a complete whim.

Jonathan C Dickinson
  • 7,181
  • 4
  • 35
  • 46