djc*_*uch 17 c++ character-encoding microsoft-metro windows-runtime c++-cx
如何转换Platform :: String的内容以供期望基于char*的字符串的函数使用?我假设WinRT为此提供了辅助函数,但我找不到它们.
谢谢!
Jam*_*lis 13
Platform::String::Data()将返回wchar_t const*指向字符串内容(类似于std::wstring::c_str()). Platform::String表示一个不可变的字符串,所以没有访问器来获取wchar_t*.您需要将其内容复制到a std::wstring中进行更改.
有没有直接的方式来获得一个char*或char const*因为Platform::String使用宽字符(所有Metro风格的应用程序都是Unicode应用程序).您可以使用转换为多字节WideCharToMultiByte.
rys*_*ama 13
这是在代码中执行此操作的一种非常简单的方法,无需担心缓冲区长度.如果您确定要处理ASCII,请仅使用此解决方案:
Platform::String^ fooRT = "aoeu";
std::wstring fooW(fooRT->Begin());
std::string fooA(fooW.begin(), fooW.end());
const char* charStr = fooA.c_str();
Run Code Online (Sandbox Code Playgroud)
请记住,在此示例中,char*它位于堆栈中,一旦离开作用域就会消失
您不应该将一个宽字符强制转换为字符,您将使用每个字符超过一个字节(例如中文)来破坏语言.这是正确的方法.
#include <cvt/wstring>
#include <codecvt>
Platform::String^ fooRT = "foo";
stdext::cvt::wstring_convert<std::codecvt_utf8<wchar_t>> convert;
std::string stringUtf8 = convert.to_bytes(fooRT->Data());
const char* rawCstring = stringUtf8.c_str();
Run Code Online (Sandbox Code Playgroud)