如何用对象数组封送对象?

时间:2012-12-22 14:38:53

标签: c# marshalling sizeof

我在编组方面遇到了问题。

    [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 ++ struct。

如果我这样做:

    [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定义为struct,它必须是class。

0 个答案:

没有答案