【问题标题】:C#: passing array of strings to a C++ DLLC#:将字符串数组传递给 C++ DLL
【发布时间】:2010-12-15 08:36:17
【问题描述】:

我正在尝试将数组中的一些字符串传递给我的 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,但它打印出垃圾而不是“第一”、“第二”和“第三”。

有什么线索吗?

【问题讨论】:

    标签: c# dll pinvoke marshalling


    【解决方案1】:

    使用 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 在封送阵列上有more info。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      相关资源
      最近更新 更多