![](/img/trans.png)
[英]C# pass pointer to struct (containing non-blittable types) to unmanaged C++ DLL
[英]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.