Returning string from C# to C++ using Unmanaged Exports returns numbers

641 views Asked by At

I have a function in C# that I am calling from C++ using Unmanaged Exports. The passed string is received correctly in C# but the returned string in C++ is shown as numbers like 5073480. What could possibly be wrong here? I need to get the string back in C++. Following is the code

C++ code:

using Testing = wchar_t*(__stdcall *) (wchar_t* name);
int _tmain(int argc, _TCHAR* argv[])
{
    HMODULE mod = LoadLibraryA("CSharp.dll");
    Testing performTest = reinterpret_cast<Testing>(GetProcAddress(mod, "testing"));
    wchar_t* d_str = L"JS";
    wchar_t* result = performTest(d_str);
    std::printf("Result from c#: %d\n", result);
    getchar();
    return 0;
}

C# code:

[DllExport(ExportName = "testing", CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static string PassStringInOut([MarshalAs(UnmanagedType.LPWStr)]string name)
{
    Console.WriteLine("Received string is: "+name);
    return string.Format("Hello from .NET assembly, {0}!", name);
}
1

There are 1 answers

1
Soonts On BEST ANSWER

Couple of problems here.

The format string is wrong. To print a Unicode string using ASCII version of printf, the format specified is %S (note the capital S).

Second, you introduced a memory leak here. After you’re done using the string in C++, you must free the memory by calling CoTaskMemFree (assuming you’re writing code for Windows).