pass C# string to C++ DLL

Trips

Well-known member
Joined
Aug 7, 2010
Messages
2,788
Having issues with passing a C# string to a C++ DLL (for an XNA game on Valves Steam platform). I generated the C# with Microsoft P/Invoke Interop Assistant, so I am fairly sure the C# side is correct. Anyway, here is the C++ side:

<div style="color:Black; background-color:White
<pre><span style="color:Green // C++ function receives a string from C# and writes it to file
<span style="color:Blue bool __stdcall TestString(<span style="color:Blue char* c, <span style="color:Blue int length)
{
stringstream s;
<span style="color:Blue for(<span style="color:Blue int i=0; i<length; i++) s << c;

ofstream file(<span style="color:#A31515 "log.txt", ios::app);
file << s.str() << endl;
file.close();

<span style="color:Blue return <span style="color:Blue true;
}
[/code]


Here is the C# call:

<div style="color:Black; background-color:White
<pre>[DllImportAttribute(dllPath, EntryPoint = <span style="color:#A31515 "TestString", CallingConvention = CallingConvention.StdCall)]
[<span style="color:Blue return: MarshalAsAttribute(UnmanagedType.I1)]
<span style="color:Blue public <span style="color:Blue static <span style="color:Blue extern <span style="color:Blue bool SendString(IntPtr c, <span style="color:Blue int length);
[/code]


I call it this way:

<div style="color:Black; background-color:White
<pre> <span style="color:Blue string s1 = <span style="color:#A31515 "bleh";
IntPtr p1 = Marshal.StringToHGlobalUni(s1);
<span style="color:Blue bool received = NativeMethods.SendString(p1, s1.Length);
[/code]


Result: When I run the code by sending "blah" the C++ DLL writes "b l " to file. So it only gets every other character?
BTW, is there a way to look at a DLL and determine the char set?

View the full article
 
Back
Top