I have a C# app that calls a C++ DLL.
In C#, I have code as follows:
[DllImport(@"111.dll", CharSet = CharSet.Unicode)]
public extern static String Func1(String arg);
......
String arg = "test text";
String retstring = Func1(arg);
In CPP, I have the function defined as follows:
extern "C"
{
__declspec(dllexport) LPWSTR Func1(LPWSTR arg)
{
....
LPWSTR ret1 = L"1?2?3?4?5";
LPWSTR ret2 = SomeActualFunction(arg);
retturn ret1; // return ret2;
}
}
If I return ret1 in C++’s Func1(), all works fine. And in VS2008’s memory window, I can see correct Unicode binaries. In C++ the binaries of ret1 is
“31 00 3f 00 32 00 3f 00 33 00 3f 00 34 00 3f 00 35 00”
, and in C# the binaries of retstring is
“28 67 a3 f7 fe 07 00 00 0a 00 00 00 09 00 00 00 31 00 3f 00 32 00 3f 00 33 00 3f 00 34 00 3f 00 35 00”
. I think the C# binaries
“28 67 a3 f7 fe 07 00 00 0a 00 00 00 09 00 00 00”
are the header of System.String type.
What’s more, if I add the following line just before return in CPP code, I can get correct retstring in C# code too:
ret2 = L"1?2?3?4?5";
But when I return ret2 in the C++ DLL, the returned string ret in C# seems to be corrupted. The binaries in the C++ DLL are correct Unicode on my inspection. But the binaries of retstring in the C# code are
“28 67 a3 f7 fe 07 00 00 0a 00 00 00 09 00 00 00 dd dd dd dd dd dd dd dd dd dd dd dd ….”.
I can only notice ret2 is longer than ret1 – ret2 has some hundreds of WCHARs.
Any ideas? Thx in advance.
I would always use a
BSTRfor this because it makes the responsibility of memory allocation/deallocation transparent.C++
C#
You don’t say how your strings are being allocated, but as soon as you use a dynamically allocated string you need to tackle that issue. The great thing about
BSTRis that it uses the shared COM allocator which enables the C# marshaller to deallocate the string with the same allocator as the C++ code that allocated it.