如何将Platform :: String转换为char*?

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.

  • 这不回答这个问题.他问如何将Platform :: String转换为char*,并且有办法实现这一点.WideCharToMultiByte可以工作但是新功能的人不知道如何使用它. (3认同)

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*它位于堆栈中,一旦离开作用域就会消失

  • 对于每个问题,都有一个简单,优雅的解决方案.而且错了.像这个.除了执行线程当前状态之外,ASCII字符范围之外的任何字符都将被随机表示.**不要使用这个解决方案.**(这很容易,因为它甚至没有编译.) (3认同)

Jef*_*ock 5

您不应该将一个宽字符强制转换为字符,您将使用每个字符超过一个字节(例如中文)来破坏语言.这是正确的方法.

#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)

  • 但是使用@ Quest的方法,`raw`变量将指向释放的内存(临时对象在表达式被计算后消失),如果按字面意思使用的话.更好地使用`std :: string utf8 = std :: wstring_convert <std :: codecvt_utf8 <wchar_t >>().to_bytes(fooRT-> Data())`除非你确定自己在做什么. (2认同)