C# – When should I explicitly specify a StructLayout

cinteropmarshallingstruct

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?

Best Answer

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.