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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

great, it worked. Also i tried without 'const' only char* works too. Thanks a lot.
I suggest explicitly specifying UnmanagedType.LPUTF8Str or UnmanagedType.LPWStr to support Unicode, or UnmanagedType.BStr
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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.