C#: 将字符串数组传递给C++ DLL

5
我正在尝试将数组中的一些字符串传递给我的C++ DLL。
C++ DLL的函数是:
extern "C" _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>

然后我像这样设置/调用函数:
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);

使用DbgView,我可以看到一些数据被传递给了DLL,但是它打印出来的是垃圾而不是“first”,“second”和“third”。有什么线索吗?
1个回答

5

使用String[]代替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有关于数组封送的更多信息


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接