For an interop scenario, you need to return a string object you'll be able to read from .NET code.
Don't return a std::string
(there is no such thing in C#) or a const char *
(readable from C# but you'd have to manage memory deallocation) or things like that. Return a System::String^
instead. This is the standard string type in .NET code.
This will work:
public: System::String^ getStringFromCpp()
{
return "Hello World";
}
But if you actually have a const char *
or std::string
object you'll have to use the marshal_as
template:
#include <msclr/marshal.h>
public: System::String^ getStringFromCpp()
{
const char *str = "Hello World";
return msclr::interop::marshal_as<System::String^>(str);
}
Read Overview of Marshaling in C++ for more details.
To convert a System::String^
to std::string
you can also use the marshal_as
template, as explained in the above link. You just need to include a different header:
#include <msclr/marshal_cppstd.h>
System::String^ cliStr = "Hello, World!";
std::string stdStr = msclr::interop::marshal_as<std::string>(cliStr);