编组一系列短裤:“发生了不匹配”

时间:2010-05-19 12:30:55

标签: c# c++ dll marshalling

我有以下C ++结构:

    typedef struct FormulaSyntax{
        WORD StructSize;
        short formulaSyntax [2];
    } FormulaSyntax;

我有一个DLL方法,它接受这个结构的一个实例。这是我在C#方面尝试的内容:

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct FormulaSyntax {
        public short StructSize;
        public short[] formulaSyntax;
    }

    [DllImport(DLL_NAME, EntryPoint = "PEGetFormulaSyntax",
                    CharSet = CharSet.Unicode)]
    public static extern bool getFormulaSyntax(short reportID,
                     ref FormulaSyntax syntax);

    ...
    FormulaSyntax syntax = new FormulaSyntax();
    syntax.formulaSyntax = new short[2];
    syntax.StructSize = (short)Marshal.SizeOf(syntax);
    PrintEngine.getFormulaSyntax(context.oldApiID, ref syntax);

这会崩溃,给我留言

Mismatch has occurred between the runtime type of the array and the sub type recorded in the metadata.

我做错了什么?

1 个答案:

答案 0 :(得分:0)

找到答案here:这是我的C#struct需要的样子 - 它需要MarshalAs行。它现在有效。

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct FormulaSyntax {
        public short StructSize;
        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I4,
                                            SizeConst = 2)]
        public short[] formulaSyntax;
    }