PInvoke Stack Imbalance将2D数组从C#传递到C ++

时间:2015-12-18 09:21:19

标签: c# c++ arrays marshalling

问题是将2D字符串数组从C#传递给C ++:C#代码正确地将所有字符串读入stringArray {string [30,30]}。

cv::Size(320,240)

这里是非托管C ++ DLL:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct Struct1
    {
        public const int RowCount = 30;
        public const int ColCount = 30;

        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.LPWStr,
        SizeConst = RowCount * ColCount)]
        public string[,] stringArray;
    }

    [DllImport("C:\\Win32Project2.dll",
    EntryPoint = "DDentry", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
    public static extern void DDentry(ref Struct1 stdPointer, int iDim1, int iDim2);

    public void button6_Click_1(object sender, EventArgs e)
    {
        try
        {
            TestStruct1 test_array = new Struct1();
            test_array.stringArray = new string[Struct1.RowCount, Struct1.ColCount];

            for (int i = 0; i < Struct1.RowCount; i++)
            {
                for (int j = 0; j < Struct1.ColCount; j++)
                {
                    test_array.stringArray[i, j] = String.Format("Cell[{0};{1}]", i, j);
                }
            }

            DDentry(ref test_array, Struct1.ColCount, Struct1.RowCount);
        }

        catch (Exception ex)
        {
            Console.Error.WriteLine(ex.ToString());
        }
    }

所有字符串都完美地传递给C ++。

不幸的是,在返回C#后出现PInvokeStackImbalance错误。如果我继续使用“继续”按钮,则数组将显示stringArray {string [900]},而不是之前的stringArray {string [30,30]}。非常感谢你的想法,以解决..

0 个答案:

没有答案