[Mono-dev] struct alignment

Jacob Gladish jacobgladish at yahoo.com
Wed Mar 26 23:49:36 EDT 2008


While working with pInvoke, I noticed that two structures seemed to be algined differently. One looks like it's aligning on 4 byte boundary, while the other is aligning on 8. If you run this sample code you'll see that the sizeof(foo) is 12 and the sizeof(bar) is 16. I'm not sure if this is a bug and wanted to see if anyone could explain why this is happening. If I add Pack=4 to bar it reports sizeof(bar) 12 as expected. The equivalent c++ code compiled with g++ reports 12 and 12. As another reference point MS Dev Studio 2008 has sizeof 16 for both structures using c# and c++ code. 

Thanks
-jake


using System;
using System.Runtime.InteropServices;

public class SizeTest
{
    [StructLayout(LayoutKind.Sequential)]
    struct foo {
        UInt64  a;
        UInt32  b;
    }

    [StructLayout(LayoutKind.Explicit)]
    struct bar {
        [FieldOffset(0)] UInt64 a;
        [FieldOffset(0)] UInt16 b;
        [FieldOffset(0)] foo    f;
    }

    public static void Main( String[] args ) {
        foo f = new foo();
        bar b = new bar();
        Console.WriteLine( "sizeof(foo)={0}", Marshal.SizeOf(f) );
        Console.WriteLine( "sizeof(bar)={0}", Marshal.SizeOf(b) );
    }
}

-- 

#include <stdio.h>
#include <stdint.h>

struct foo {
    uint64_t    a;
    uint32_t    b;
};

union bar {
    uint64_t    a;
    uint16_t    b;
    foo         f;
};

int
main( int argc, char* argv[] )
{
    printf( "sizeof(foo)=%lu\n", sizeof(foo) );
    printf( "sizeof(bar)=%lu\n", sizeof(bar) );
    return 0;
}

~







      ____________________________________________________________________________________
Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs


More information about the Mono-devel-list mailing list