簡體   English   中英

從C#傳遞2D字符串數組(不可拆分)到C ++

[英]Passing 2D string array (non-blittable) from C# to C++

問題是將2D字符串數組(不可綁定)從托管C#傳遞到非托管C ++。 我不確定DllImport和MarshalAs約定對於這種類型的字符串數組是否完全正確。 也許,指針/內存分配定義缺少屬性。 非常感謝您的評論。

public struct TestStruct
{
   public string[,] stringArray;
}

[DllImport("C:\\Users\\Win32Project2.dll",
    EntryPoint = "DDentry",
    CallingConvention = CallingConvention.StdCall)]

    public static extern void DDentry
    (
        [In][MarshalAs(UnmanagedType.LPArray,
        ArraySubType = UnmanagedType.LPStr)] string[,] arrayReadDat, int iDim1, int iDim2
    );

    private void button6_Click_1(object sender, EventArgs e)
    {
        TestStruct arrayReadDat = new TestStruct();
        arrayReadDat.stringArray = new string[lastRow+1, lastCol+1];

        for (int i = 2; i <= lastRow; i++)
        {
            for (int j = 1; j <= lastCol; j++)
            {
                arrayReadDat.stringArray[i, j] = i;
            }
        }

        int size = Marshal.SizeOf(typeof(TestStruct));
        IntPtr strPointer = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(arrayReadDat, strPointer, false);

        DDentry(arrayReadDat.stringArray, lastRow+1, lastCol+1);

        Marshal.FreeHGlobal(strPointer);
     }

這里是非托管的C ++代碼,它們不顯示來自C#代碼的數據:

  _declspec(dllexport) void DDentry(string *p2DIntArray, int iDim1, int iDim2)
  {
     int iIndex = 0;
     for (int i = 2; i <= iDim1; i++)
     {
        for (int j = 1; j <= iDim2; j++)
        {
           arrayREAD[i][j] = p2DIntArray[iIndex++];
        }
     }
  }

看起來,與其在C ++代碼中導入DLL並在C#代碼中導出它,不如說正好相反。

在此處可以找到如何從本地Visual C ++代碼調用托管DLL的示例: https : //support.microsoft.com/zh-cn/kb/828736

它是為VS2005編寫的,但是總體邏輯在更新的VS版本中也應該相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM