[Mono-list] Marshal.SizeOf() vs. sizeof operator

Marcus mathpup@mylinuxisp.com
Wed, 13 Aug 2003 00:17:17 -0500


I think that you're using Marshal.SizeOf() in a way that is not intended. It 
appears that this method is mainly useful when invoked on classes or structs 
that will undergo marshalling conversions when passed to P/Invoke methods. I 
don't think that it was intended to be invoked on enums.

What are you attempting to do where the size of the unmanaged struct makes a 
difference?



On Tuesday 12 August 2003 10:59 pm, Giuseppe Greco wrote:
> Marcus,
>
> here's an example:
>
> public enum FieldType : byte
> {
>     Undefined = 0,
>     Int16,
>     Int32,
>     Int64
> }
>
> Then, try something like this:
>
> using System;
> using System.Runtime.InteropServices;
>
> public class MyClass
> {
>     private FieldType fieldType = FieldType.Undefined;
>
>     public void MyMethod()
>     {
>         Console.WriteLine("The size of fieldType is {0}",
>             Marshal.SizeOf(fieldType.GetType());
>     }
> }
>
> The code above executes sucessfully with Mono on Linux,
> but it doesn't with .NET on Windwos, where I always get
> the following exception:
>
> Unhandled Exception: System.ArgumentException:
> Type FieldType can not be marshaled as an unmanaged
> structure; no meaningful size or offset can be computed.
> at System.Runtime.InteropServices.Marshal.SizeOf(Type t)
>
> Rewriting MyMethod like this
>
>     public void MyMethod()
>     {
>         Console.WriteLine("The size of fieldType is {0}",
>             Marshal.SizeOf(Type.GetType("System.Byte"));
>     }
>