2015-11-05 188 views
0

問題是將託管C#中的二維字符串數組(非可循)傳遞給非託管C++。 我不確定DllImport和MarshalAs約定對於這種類型的字符串數組是否完全正確。也許,指針/內存分配定義有一個缺失的屬性。非常感謝您的評論。將C#中的二維字符串數組(非blittable)傳遞給C++

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++]; 
     } 
    } 
    } 
+0

對不起,複製時出現litlle錯誤:應該是:string strK =「testify」; arrayReadDat.stringArray [i,j] = strK; – joe

回答

0

看起來,這不是在C++代碼導入DLL和C#代碼將其導出,你正在做,反之亦然。

一個例子如何調用來自本機的Visual C託管DLL ++代碼可以在這裏找到: https://support.microsoft.com/en-us/kb/828736

它是爲VS2005寫的,但整體的邏輯應該是在新版本VS也一樣。

+0

實際上,方向在C#端使用「DllImport」,在C++端使用「_declspec(dllexport)」,可以完美地處理2D​​整數和雙數組。 – joe

+0

在這種情況下,在C++端嘗試char *而不是字符串 – user2667069

+0

不,它不工作..僅在C++端有空數組。 – joe

相關問題