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

How to convert Platform::String to char*?

本文关键字:char 转换 String Platform      更新时间:2023-10-16

如何转换Platform::String的内容以供期望基于char*的字符串的函数使用?我假设WinRT为此提供了辅助函数,但我就是找不到它们。

谢谢!

这里有一个非常简单的方法可以在代码中做到这一点,不必担心缓冲区长度只有当您确定要处理ASCII时才使用此解决方案

Platform::String^ fooRT = "aoeu";
std::wstring fooW(fooRT->Begin());
std::string fooA(fooW.begin(), fooW.end());
const char* charStr = fooA.c_str();

请记住,在本例中,char*在堆栈上,一旦离开作用域

,就会消失

Platform::String::Data()将返回一个指向字符串内容的wchar_t const*(类似于std::wstring::c_str())。Platform::String表示一个不可变的字符串,因此没有访问器来获取wchar_t*。您需要将其内容复制到std::wstring中以进行更改。

没有直接的方法来获得char*char const*,因为Platform::String使用宽字符(所有Metro风格的应用程序都是Unicode应用程序)。您可以使用WideCharToMultiByte转换为多字节。

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

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

有一个String::Data方法返回const char16*,这是原始的unicode字符串。

从unicode到ascii或其他任何东西的转换,即char16*char*,则是另一回事。您可能不需要它,因为现在大多数方法都有wchar版本。

使用wcstombs:的解决方案

Platform::String^ platform_string = p_e->Uri->AbsoluteUri;
const wchar_t* wide_chars =  platform_string->Data();
char chars[512];
wcstombs(chars, wide_chars, 512);