问题是将二维字符串数组(不可插入)从托管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++];
}
}
}
答案 0 :(得分:0)
看起来,不是在C ++代码中导入DLL而是用C#代码导出它,而是反之亦然。
可以在此处找到如何从本机Visual C ++代码调用托管DLL的示例: https://support.microsoft.com/en-us/kb/828736
它是为VS2005编写的,但在较新的VS版本中整体逻辑应该相同。