C ++ / CLI String Conversions

I found this really nice piece of code that converts a string to System:String^, as in:

System::String^ rtn = gcnew String(move.c_str());  // 'move' here is the string

I pass rtn back to a C # program. In any case, inside the function where this code exists, I pass System::String^. I also found code to convert System:String^to string using the following code:

pin_ptr<const wchar_t> wch = PtrToStringChars(cmd);  // 'cmd' here is the System:String          
size_t convertedChars = 0;
size_t  sizeInBytes = ((cmd->Length + 1) * 2);
errno_t err = 0;
char *ch = (char *)malloc(sizeInBytes);

err = wcstombs_s(&convertedChars,ch, sizeInBytes,wch, sizeInBytes);

Now I can use 'ch' as ​​a string.

This, however, seems to do a lot more work than converting another method using gcnew. So finally, my question is: is there something there that converts a string System::String^to a string using a similar method as with gcnew?

+1
source share
2 answers

V++: ++

#include <msclr/marshal_cppstd.h>

// given System::String^ mstr
std::string nstr = msclr::interop::marshal_as<std::string>(mstr);
+10

:

wchar_t *str = "Hi StackOverflow"; //native
String^ mstr= Marshal::PtrToStringAnsi((IntPtr)str); // native to safe managed
wchar_t* A=( wchar_t* )Marshal::StringToHGlobalAnsi(mstr).ToPointer(); // return back to native 

using namespace System::Runtime::InteropServices;

0

All Articles