0

The issues is about passing a 2D string array from C# to C++: The C# code is correctly reading all strings into the stringArray {string[30,30]}.

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

and here the unmanaged C++ DLL:

extern "C"
{
#pragma pack(1)
struct Struct2
{
    wchar_t *varArray[30][30];
};

..

_declspec(dllexport) void DDentry(Struct2 *pArray, int iDim1, int iDim2)
{
    for (int i = 0; i < iDim1; i++)
    {
        for (int j = 0; j < iDim2; j++)
        {
            wchar_t *str = pArray->varArray[i][j];
            wprintf(str);
            wprintf(L" ");
        }
        wprintf(L"\n");
    }

All strings are perfectly passed to C++.

Unfortunately, after returning to C# a PInvokeStackImbalance error appears. If I proceed with the Continue button the array shows stringArray{string[900]} instead of previously stringArray{string[30,30]}. Many thanks for your ideas to resolve ..

joe
  • 61
  • 2
  • 6
  • 1
    Tried a different calling convention? e.g. `CallingConvention.Cdecl`? Anyway, you'll probably need to pass a 1D array from C# and write code to access it as if it was a 2D array. – Matthew Watson Dec 18 '15 at 09:40
  • A 2D array in C++ seldom passes inside C++ quite the way you want. It getting munged on return to C# doesn't surprise me much. It looks a lot like the return unrolled your 2d array (30*30=900). – user4581301 Dec 18 '15 at 09:47
  • Hans, great answer and it perfectly worked now with the Cdecl convention! Many thanks. – joe Dec 18 '15 at 11:22

0 Answers0