0

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.

Botje
  • 26,269
  • 3
  • 31
  • 41
Usman
  • 43
  • 5

2 Answers2

1

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.

Botje
  • 26,269
  • 3
  • 31
  • 41
  • great, it worked. Also i tried without 'const' only char* works too. Thanks a lot. – Usman Jul 09 '19 at 07:59
  • I suggest explicitly specifying `UnmanagedType.LPUTF8Str` or `UnmanagedType.LPWStr` to support Unicode, or `UnmanagedType.BStr` – Ben Jul 09 '19 at 08:07
1

C++ with CLI, use System::String^ (this is a .Net string, i.e. same as C#'s)

using GetOutputString = System::String^ (__stdcall *) ();

Then you can do this

std::string standardString = context.marshal_as<std::string>(managedString);

(Credit [https://stackoverflow.com/a/1300903/1848953])

AlanK
  • 1,827
  • 13
  • 16