C++/CLI Tips - Convert string between .NET and C++

  • Convert string between .NET/C# and C++
#include <string>
#include <msclr\marshal_cppstd.h>
 
std::string cstring(System::String^ str) {
    msclr::interop::marshal_context context;
    std::string result = context.marshal_as<std::string>(str);
    return result;
}
 
System::String^ nstring(const std::string& str) {
    return gcnew System::String(str.c_str());
}