views:

26

answers:

1

I have the following C++ struct:

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

I have a DLL method which takes an instance of this struct. Here's what I've tried on the C# side:

    [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);

This crashes, giving me the message

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

What am I doing wrong?

A: 

Found the answer here: Here is what my C# struct needed to look like - it needed the MarshalAs line. It works now.

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