In C# you have nice alignment attributes such as this:
[StructLayout(LayoutKind.Explicit)]
public struct Message
{
[FieldOffset(0)]
public int a;
[FieldOffset(4)]
public short b;
[FieldOffset(6)]
public int c;
[FieldOffset(22)] //Leave some empty space just for the heck of it.
public DateTime dt;
}
Which gives you fine control on how you need your structure to be layed out in memory. Is there such a thing in standard C++?
Compilers typically support that via a #pragma but it's not something that is included in the C++ standard and, thus, is not portable.
For an example with the Microsoft compiler, see: http://msdn.microsoft.com/en-us/library/2e70t5y1(VS.80).aspx
Hmya, it's rather backwards: you need the attribute in C# so that you can match the structure alignment chosen by a native code compiler. And [FieldOffset] is only really needed to deal with unions.
But you can achieve that kind of layout pretty easily by inserting the padding yourself:
#pragma pack(push, 1)
public struct Message
{
int a;
short b;
int c;
char padding1[12];
long long dt;
}
#pragma pack(pop)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With