C++ .NET convert System::String to std::string

Amish Programmer picture Amish Programmer · Aug 19, 2009 · Viewed 64.8k times · Source

How do you convert System::String to std::string in C++ .NET?

Answer

Colin Gravill picture Colin Gravill · Aug 19, 2009

There is cleaner syntax if you're using a recent version of .net

#include "stdafx.h"
#include <string>

#include <msclr\marshal_cppstd.h>

using namespace System;

int main(array<System::String ^> ^args)
{
    System::String^ managedString = "test";

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

    return 0;
}

This also gives you better clean-up in the face of exceptions.

There is an msdn article for various other conversions