我尝试调用代码int size = Marshal.SizeOf(typeof(MyStruct))
,但它抛出以下异常:为什么我不能为此C#结构执行Marshal.SizeOf()?
类型“MYSTRUCT”不能被封送一个非托管的结构;无法计算出有意义的大小或偏移量。
我的结构如下:
[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
[MarshalAs(UnmanagedType.U4)]
public UInt32 version;
[MarshalAs(UnmanagedType.FunctionPtr)]
public IntPtr Start;
[MarshalAs(UnmanagedType.FunctionPtr)]
public IntPtr Stop;
// And a bunch more IntPtr, all declared the same way.
}
的结构应该被传递到C-土地,那里的C代码将使用其内容作为函数指针。我看不到如何计算大小会失败,任何人都可以帮忙?
感谢您的反馈。我目前通过执行'Marshal.GetFunctionPointerForDelegate(无论)'来填充结构体。由于各种原因,我想保留结构成员为'IntPtr' - 如果我只是删除'[MarshalAs(UnmanagedType.FunctionPtr)]'将兼容? – FusterCluck
使用GetFunctionPointerForDelegate()不会改变答案中的任何内容,但同样的问题也适用。是的,就像将该字段声明为委托类型一样,您也不需要IntPtr上的[MarshalAs]。 –