如何转换的平台:: String的内容要由期望一个char *基于字符串函数中使用? 我假设的WinRT这提供了辅助功能,但我无法找到他们。
谢谢!
如何转换的平台:: String的内容要由期望一个char *基于字符串函数中使用? 我假设的WinRT这提供了辅助功能,但我无法找到他们。
谢谢!
Platform::String::Data()
将返回一个wchar_t const*
指向字符串的内容(类似std::wstring::c_str()
Platform::String
表示不可改变的字符串,所以没有访问得到一个wchar_t*
。 你需要复制的内容,例如进入std::wstring
,做出改变。
有没有直接的方法获得char*
或char const*
因为Platform::String
使用宽字符(所有Metro风格的应用程序都是Unicode应用程序)。 您可以使用转换为多字节WideCharToMultiByte
。
这里是一个非常简单的方法来做到这一点的代码W / O不必担心缓冲区长度。 只有当你确定你正在处理的ASCII使用此解决方案 :
Platform::String^ fooRT = "aoeu";
std::wstring fooW(fooRT->Begin());
std::string fooA(fooW.begin(), fooW.end());
const char* charStr = fooA.c_str();
请记住,在这个例子中, 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();
还有的String::Data
方法返回const char16*
,这是原始unicode字符串。
从Unicode转换为ASCII或什么的,即char16*
至char*
,则另当别论。 你也许并不需要它,因为大多数方法都有各自的wchar
版本的这些日子。
使用A溶液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);