A reader asks,
Sender: Erik Brendengen
Is there an easy way to convert from String^ to std::string?
Does String ^s = std::string( “bla”).c_str(); work the other way?
This is a FAQ, one that I myself bumped into when I had to pass a System::String retrieved from System::Windows::Forms::TextBox to a native program that expected a std::string.
There are generally two conversion strategies, depending on which side of the managed/native fence you wish to do the conversion work. Here are two methods making use of the PtrToStringChars( String^ ) utility from the vcclr.h header file that is part of Visual C++. Note that these are written in the new C++/CLI syntax – and that these are adapted from an internal FAQ ...
#include <stdlib.h>
#include <vcclr.h>
#include <string>
using namespace System;
bool To_CharStar( String^ source, char*& target )
{
pin_ptr<const wchar_t> wch = PtrToStringChars( source );
int len = (( source->Length+1) * 2);
target = new char[ len ];
return wcstombs( target, wch, len ) != -1;
}
bool To_string( String^ source, string &target )
{
pin_ptr<const wchar_t> wch = PtrToStringChars( source );
int len = (( source->Length+1) * 2);
char *ch = new char[ len ];
bool result = wcstombs( ch, wch, len ) != -1;
target = ch;
delete ch;
return result;
}
As to the second question, does String^ s = ns.c_str() work? Yes.