How do you convert System::String to std::string in C++ .NET?
+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
2009-08-19 15:40:39
+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
2009-08-19 15:51:51
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
2010-04-23 18:07:45
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
2010-04-29 10:28:50