Consider this code:
public enum MyEnum { V1, V2, V3 } int size = Marshal.SizeOf(typeof(MyEnum));
it throws an exception:
An unhandled exception of type "System.ArgumentException" occurred in TestConsole.exe
Additional information: Type 'TestConsole.Program + MyEnum' cannot be marshaled as an unmanaged structure; no significant size or offset calculated.
So far, this code does not throw an exception, and size contains 4:
public enum MyEnum { V1, V2, V3 } public struct MyStruct { public MyEnum en; } int size = Marshal.SizeOf(typeof(MyStruct));
Can someone explain why the .NET Framework cannot figure out that enum is 4 bytes in the first code sample?
UPDATE
Marshal.Sizeof() failed for me in this general method:
public bool IoControlReadExact<T>(uint ioControlCode, out T output) where T : struct { output = new T(); int outBufferSize = Marshal.SizeOf(typeof(T)); IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize); if (outBuffer == IntPtr.Zero) return false; try { uint bytesReturned; return IoControlRead(ioControlCode, outBuffer, (uint)outBufferSize, out bytesReturned) && ((uint)outBufferSize == bytesReturned); } finally { output = (T)Marshal.PtrToStructure(outBuffer, typeof(T)); Marshal.FreeHGlobal(outBuffer); } }
And the compiler did not complain about enum not struct .
Decision
I could reorganize my general method so that it works for both struct and enum :
// determine the correct output type: Type outputType = typeof(T).IsEnum ? Enum.GetUnderlyingType(typeof(T)) : typeof(T); //... int outBufferSize = Marshal.SizeOf(outputType); //... output = (T)Marshal.PtrToStructure(outBuffer, outputType);
Wouter Huysentruit Jul 26 '13 at 11:09 on 2013-07-26 11:09
source share