【发布时间】:2013-07-26 15:08:42
【问题描述】:
考虑这段代码:
public enum MyEnum { V1, V2, V3 }
int size = Marshal.SizeOf(typeof(MyEnum));
它抛出异常:
“System.ArgumentException”类型的未处理异常发生在 测试控制台.exe
附加信息:不能输入“TestConsole.Program+MyEnum” 编组为非托管结构;没有有意义的大小或偏移量可以 被计算出来。
虽然这段代码没有抛出异常并且size包含4:
public enum MyEnum { V1, V2, V3 }
public struct MyStruct
{
public MyEnum en;
}
int size = Marshal.SizeOf(typeof(MyStruct));
谁能解释为什么 .NET 框架无法确定第一个示例代码中的 enum 是 4 个字节?
更新
Marshal.Sizeof() 在这个通用方法中失败了:
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);
}
}
而且编译器并没有抱怨enum 不是struct。
解决方案
我可以重构我的通用方法,使其适用于 struct 和 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);
【问题讨论】:
-
this 没有解释原因,但给出了解决方法。
-
相比之下,可以使用不安全代码创建指向
MyEnum的指针类型,即使用类型MyEnum*。
标签: c# .net enums marshalling