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


Question

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

1
53
8/19/2009 3:37:19 PM

Accepted Answer

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

65
8/21/2009 8:47:05 AM

And in response to the "easier way" in later versions of C++/CLI, you can do it without the marshal_context. I know this works in Visual Studio 2010; not sure about prior to that.


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

#include <msclr\marshal_cppstd.h>

using namespace msclr::interop;

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

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

    return 0;
}


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon