我在编组方面遇到问题。
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Book
{
[MarshalAs(UnmanagedType.LPArray, SizeConst = 1000)]
public Page[] astInject2;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Page
{
public int n;
}
为什么调用Marshal.SizeOf(typeof(Book))会引发 ArgumentException:
Type 'Book' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
?
有什么解决办法吗?
我正在将 Book 对象编组为 C++ 结构。
如果我这样做:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Book
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1000)]
public Page[] astInject2;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Page
{
public int n;
}
然后Marshal.SizeOf(typeof(Book))
按应有的方式返回 4000。请注意,我不能将 Book 定义为结构,它必须是类。