Ensuring the Alignment and Packing of Your C++ Structures

Because the Garbage Collector does so much of the assignment and layout of the code for you, it's sometimes difficult to know how a particular structure is laid out in memory. This can be of crucial importance if you are bringing in byte-ordered structures from previous C++ applications or DLLs and using them in the context of .NET. The Platform Invoke services has attributes that you can use to specify exactly how your structures are laid out so that you can read them into managed code and still be sure that the order and alignment of memory-based variables are well known.

The StructLayout attribute can be used to lay out a structure sequentially, to place member variables at an exact ...

Get C# and the .NET Framework: The C++ Perspective now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.