Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 569
Warpin Avatar asked Nov 11 '09 05:11

Warpin


1 Answers

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.

like image 150
Chris R. Timmons Avatar answered Oct 04 '22 18:10

Chris R. Timmons