views:

1696

answers:

4

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

+6  A: 

There's a whole MSDN article on how to do this.

Matthew Jones
+2  A: 
stdString = toss(systemString);

  static std::string toss( System::String ^ s )
  {
    // convert .NET System::String to std::string
    const char* cstr = (const char*) (Marshal::StringToHGlobalAnsi(s)).ToPointer();
    std::string sstr = cstr;
    Marshal::FreeHGlobal(System::IntPtr((void*)cstr));
    return sstr;
  }
Spencer Ruport
+6  A: 

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

Colin Gravill
A: 

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;
}

Mike Johnson
Look at the MSDN article Collin linked to to see when to use marshal_as and when to use the marshal_context. Generally speaking the marshal_context is needed when unmanaged resources need to cleaned up.
rotti2