I have a C# DLL, having below function:
[DllExport(ExportName = "getOutputString", CallingConvention = CallingConvention.StdCall)]
public static String getOutputString()
{
String managedString = "123456789012345678901234567890";
return managedString;
}
and a C++ application to use the above function as:
HMODULE mod = LoadLibraryA("MyCustomDLL.dll");
using GetOutputString = std::string (__stdcall *) ();
GetOutputString getOutputString = reinterpret_cast<GetOutputString>(GetProcAddress(mod, "getOutputString"));
and want to store the string from DLL in C++ variable as:
std::string myVariable = getOutputString();
When I run the C++ application, it crashes.
But when i just use the function in std::printf code works perfectly:
std::printf("String from DLL: %s\n", getOutputString());
My actual task is to get an Array of String from DLL, but if you can help me getting a simple String from C# to std::string in C++, that would be great.
Or just give me a hint to save printed string via std::printf( ) in a variable of type std::string.
As per the documentation, C# marshals string
objects as simple "pointer to a null-terminated array of ANSI characters", or const char *
in C++ terms.
If you change the typedef of GetOutputString
to return a const char *
, everything will work.