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

北城余情 提交于 2019-11-29 07:50:34

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.

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());

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!