2015-11-05 185 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

相关问题