C#:将数组的字符串传递给C ++ DLL [英] C#: passing array of strings to a C++ DLL
本文介绍了C#:将数组的字符串传递给C ++ DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C ++ DLL的功能是:
externC_declspec(dllexport)void printnames(char ** ppNames,int iNbOfNames)
{
for(int iName = 0; iName< iNbOfNames; iName ++)
{
OutputDebugStringA(ppNames [iName]);
}
}
在C#中,我加载了这样的功能:
[DllImport(MyDLL.dll,CallingConvention = CallingConvention.StdCall)]
static extern void printnames(StringBuilder [] astr,int size);< br>
然后我设置/调用这样的功能:
列表< string> names = new List< string>();
names.Add(first);
names.Add(second);
names.Add(third);
StringBuilder [] astr = new StringBuilder [20];
astr [0] = new StringBuilder();
astr [1] = new StringBuilder();
astr [2] = new StringBuilder();
astr [0] .Append(names [0]);
astr [1] .Append(names [1]);
astr [2] .Append(names [2]);
printnames(astr,3);
使用DbgView,我可以看到一些数据被传递给DLL,但它正在打印出垃圾第一,第二和第三。
任何线索?
解决方案
使用String []代替StringBuilder []:
[DllImport(MyDLL.dll ,CallingConvention = CallingConvention.StdCall)]
static extern void printnames(String [] astr,int size);
列表< string> names = new List< string>();
names.Add(first);
names.Add(second);
names.Add(third);
printnames(names.ToArray(),names.Count);
MSDN有更多信息在封送阵列上。
I'm trying to pass some strings in an array to my C++ DLL.
The C++ DLL's function is:
extern "C" _declspec(dllexport) void printnames(char** ppNames, int iNbOfNames)
{
for(int iName=0; iName < iNbOfNames; iName++)
{
OutputDebugStringA(ppNames[iName]);
}
}
And in C#, I load the function like this:
[DllImport("MyDLL.dll", CallingConvention = CallingConvention.StdCall)]
static extern void printnames(StringBuilder[] astr, int size);<br>
Then I setup/call the function like so:
List<string> names = new List<string>();
names.Add("first");
names.Add("second");
names.Add("third");
StringBuilder[] astr = new StringBuilder[20];
astr[0] = new StringBuilder();
astr[1] = new StringBuilder();
astr[2] = new StringBuilder();
astr[0].Append(names[0]);
astr[1].Append(names[1]);
astr[2].Append(names[2]);
printnames(astr, 3);
Using DbgView, I can see that some data is passed to the DLL, but it's printing out garbage instead of "first", "second" and "third".
Any clues?
解决方案
Use String[] instead of StringBuilder[]:
[DllImport("MyDLL.dll", CallingConvention = CallingConvention.StdCall)]
static extern void printnames(String[] astr, int size);
List<string> names = new List<string>();
names.Add("first");
names.Add("second");
names.Add("third");
printnames(names.ToArray(), names.Count);
MSDN has more info on marshaling arrays.
这篇关于C#:将数组的字符串传递给C ++ DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文