How to convert const wchar_t * to System :: String?

I need to convert SHA1 (wchar_t *) to regular String ^ in order to use it in a specific function. Any ideas? I tried Google, but all the results were completely opposite to my question.: \

NOTE. I am using C ++. NET framework and Windows Forms applications.

+4
source share
3 answers

Use the constructor; eg:

const wchar_t* const pStr1 = ...; System::String^ const str1 = gcnew System::String(pStr1); const char* const pStr2 = ...; System::String^ const str2 = gcnew System::String(pStr2); 

If you use standard C ++ string classes ( std::wstring or std::string ), you can get a pointer using the c_str() method. Then your code might be

 const std::wstring const std_str1 = ...; System::String^ const str1 = gcnew System::String(std_str1.c_str()); 

See System.String and a detailed discussion here .

+3
source

If you receive the error cannot convert parameter 1 from 'std::string' to 'const wchar_t *' when executing the Dan solution, then you will ask the wrong question. Instead of asking how to convert wchar_t* to String^ , you should ask how to convert std::string to String^ .

Use the built-in c_str function to get a simple char* from std::string and pass this to the constructor.

 std::string unmanaged = ...; String^ managed = gcnew String(unmanaged.c_str()); 
+1
source

You can also try:

 #include <msclr\marshal_cppstd.h> ... String^ managedString = msclr::interop::marshal_as<String^>(/* std::string or wchar_t * or const wchar_t * */); 

You can refer to C ++ Marshaling Overview for all supported types that you could use

+1
source

All Articles