C++/CLI String Conversions

2019-01-27 05:13发布

问题:

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

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

I'm passing rtn back to a C# program. Anyways, inside the function where this code exists, I'm passing in a System::String^. I also found some code to convert a System:String^ to a 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 be alot more work than converting the other way using the gcnew. So, at last my question is, is there something out there that will convert a System::String^ to string using a similar fashion as with the gcnew way?

回答1:

Use VC++'s marshaling library: Overview of Marshaling in C++

#include <msclr/marshal_cppstd.h>

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


回答2:

this could be useful:

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 

don't forget using namespace System::Runtime::InteropServices;