[Mono-dev] Marshal.SizeOf differences on .NET and Mono

Joe Dluzen jdluzen at gmail.com
Thu Feb 3 17:08:24 EST 2011


Hi all,

I'm not entirely sure who has the bug here, Mono seems like it is more
logically correct, but perhaps I'm missing an attribute somewhere.

Marshal.SizeOf(typeof(ImClasses)) is not what you'd expect, and is
different depending on if it runs under Mono 2.8 (on Windows) or .NET
3.5.

.NET: Class size: 8
Mono: Class size: 1

Struct sizes are both 1.

Thanks,
Joe

using System;
using System.Runtime.InteropServices;
class Program
{
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public class ImaClass
    {
        public byte A;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public class ImClasses
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
        public ImaClass[] Classes;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct ImaStruct
    {
        public byte A;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct ImStructs
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
        public ImaStruct[] Structs;
    }

    static void Main(string[] args)
    {
        int sizeofClasses = Marshal.SizeOf(typeof(ImClasses));
        int sizeofStructs = Marshal.SizeOf(typeof(ImStructs));
        Console.WriteLine("Class size: " + sizeofClasses);
        Console.WriteLine("Struct size: " + sizeofStructs);
    }
}


More information about the Mono-devel-list mailing list