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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With