6

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

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

ildjarn
  • 62,044
  • 9
  • 127
  • 211
FreelanceCoder
  • 596
  • 2
  • 8
  • 12
  • @Dan Errors occur. Error 2 error C2664: 'System::String::String(const wchar_t *)' : cannot convert parameter 1 from 'std::string' to 'const wchar_t *' c:\users\jeremy\documents\visual studio 2010\projects\launcher\launcher\Form1.h 289 – FreelanceCoder Mar 29 '13 at 02:50
  • It's probably a bit late, but a raw SHA1 hash stored in 10 `wchar_t` objects a) is quite likely not to be valid Unicode (invalid characters, invalid surrogate s); b) has a 1 in 1000 chance of containing an embedded NULL (which means just using gcnew will truncate). If the OP is converting from a hex representation, that's not a problem. – Martin Bonner supports Monica Jan 08 '18 at 14:43

3 Answers3

7

Use the constructor; like this:

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're using the standard C++ string classes (std::wstring or std::string), you can get a pointer with the c_str() method. Your code then might be

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

See System.String and extensive discussion here.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
1

If on doing Dan's solution you get an error cannot convert parameter 1 from 'std::string' to 'const wchar_t *', then you're asking the wrong question. Instead of asking how to convert wchar_t* to String^, you should be asking how to convert std::string to String^.

Use the built-in c_str function to get a plain char* out of the std::string, and pass that to the constructor.

std::string unmanaged = ...;
String^ managed = gcnew String(unmanaged.c_str());
David Yaw
  • 27,383
  • 4
  • 60
  • 93
1

You could 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 Overview of Marshaling in C++ for all the supported types you could use

Viv
  • 17,170
  • 4
  • 51
  • 71