Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)]
    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++?

like image 921
Gary Willoughby Avatar asked Jun 02 '10 20:06

Gary Willoughby


2 Answers

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

like image 58
Cumbayah Avatar answered Nov 14 '22 22:11

Cumbayah


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)
like image 29
Hans Passant Avatar answered Nov 14 '22 21:11

Hans Passant