Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# have an equivalent to #pragma pack in C++?

C# provides StructLayoutAttribute.Pack, but its behaviour is "every member gets at least the specified alignment whether it wants it or not", whereas the behaviour of #pragma pack in C++ is "every member gets the alignment it wants, unless it wants more than the specified alignment, in which case it's not guaranteed to get more than that".

Is there a way to cause the layout of a struct in C# to be the same as the layout of a similar struct in C++ with a specific #pragma pack, other than using StructLayout( LayoutKind.Explicit ) and FieldOffset on each member, or inserting unused padding members?

like image 412
TheBeardyMan Avatar asked Oct 08 '09 08:10

TheBeardyMan


1 Answers

After experimenting with StructLayout.Pack, it appears that it does indeed do exactly the same thing as #pragma pack in C++. Believing the MSDN documentation for StructLayout.Pack (which claimed the behaviour described in my original post) was a mistake.

like image 135
TheBeardyMan Avatar answered Sep 29 '22 01:09

TheBeardyMan