Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I explicitly specify a StructLayout?

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?

like image 648
biozinc Avatar asked Dec 26 '08 16:12

biozinc


2 Answers

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.

like image 176
Hans Passant Avatar answered Oct 23 '22 03:10

Hans Passant


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.

like image 31
Mark Hurd Avatar answered Oct 23 '22 03:10

Mark Hurd