开发者

C#: passing array of strings to a C++ DLL

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,开发者_JS百科 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜