Daily Archives: 2012/07/01

convert between .net String^ to char *

String^ => char *
//#include
//using namespace msclr::interop;
String^ dotnetStr = "convert .net string to c++ string";
marshal_context ^ context = gcnew marshal_context();
const char* cppStr = context->marshal_as(dotnetStr);
puts(cppStr);
delete context; // the native pointer of cppStr only valid until this line, memory will released after delete

char * => String^
char *cppStr = "convert c++ string to .net string";
String^ dotnetStr = gcnew String(cppStr );

or

//#include
//using namespace msclr::interop;
char *cppStr = "convert c++ string to .net string";
String^ dotnetStr = marshal_as( cppStr );

Reference

http://support.microsoft.com/kb/311259

http://msdn.microsoft.com/en-us/library/bb384865.aspx