Can you explicitly set a structure layout/alignment in C++ as you can in C#?
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)]
p开发者_高级运维ublic 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)
You can use "#pragma pack" compiler directive. For Microsoft Compilers look here http://msdn.microsoft.com/en-us/library/2e70t5y1%28VS.80%29.aspx for GCC google is your firend.
Also take a look at the align directive at the bottom of the page
I'm not familiar with C# alignment attributes, so can't be sure about this, but this looks a lot like C++ (and C) "bit fields".
精彩评论