将C#字符串数组传递给C ++ DLL并在那里进行修改 [英] Passing C# string Array to C++ DLL and modify it there
本文介绍了将C#字符串数组传递给C ++ DLL并在那里进行修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所示,我想在C ++ DLL中的函数中描述字符串数组.
As the title suggests I would like to let a string array be described in a function which is in a C++ DLL.
在我的实际尝试中,它毫无例外地运行,但是我的 strArray
在C ++ Function调用之后不包含任何对象.
In my actual attempt it runs without exception, but my strArray
does not contain any objects after the C++ Function call.
我的C#代码:
var strArray = new StringBuilder[100];
for (int i = 0; i < strArray .Length; i++)
{
strArray[i] = new StringBuilder(50);
}
modifyStringInCpp(strArray);
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private extern static void modifyStringInCpp(StringBuilder[] strA);
我的C ++代码:
extern "C" {
__declspec(dllexport) void __cdecl modifyStringInCpp(char** strA)
{
for (size_t i = 0; i < 100; i++)
{
strcpy(strA[i], "testString");
}
}
}
我需要更改什么?
推荐答案
可悲的是,没有 StringBuilder []
的默认封送处理...然后变成了PAIN ...一个 PAIN !!!
Sadly there is no default marshaling for StringBuilder[]
... It then becomes a PAIN... A PAIN!!!
您必须手动做所有事情!:-(
You have to do everything manually! :-(
[DllImport("CPlusPlusSide.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private extern static void modifyStringInCpp(IntPtr[] strA);
然后:
var strArray = new byte[100][];
for (int i = 0; i < strArray.Length; i++)
{
// 49 characters + NUL
strArray[i] = new byte[50]; // or a size you choose
}
var handles = new GCHandle[strArray.Length];
string[] strings;
try
{
var ptrs = new IntPtr[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
{
handles[i] = GCHandle.Alloc(strArray[i], GCHandleType.Pinned);
ptrs[i] = handles[i].AddrOfPinnedObject();
}
modifyStringInCpp(ptrs);
strings = new string[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
{
strings[i] = Marshal.PtrToStringAnsi(ptrs[i]);
}
}
finally
{
for (int i = 0; i < strArray.Length; i++)
{
if (handles[i].IsAllocated)
{
handles[i].Free();
}
}
}
这篇关于将C#字符串数组传递给C ++ DLL并在那里进行修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文