如何将Platform::String转换为char*
How to convert Platform::String to char*?
如何转换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);
相关文章:
- 将无符号char*转换为std::istream*C++
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 将函数参数"const char*"转换为"std::string_view"是
- C ++如何在使用"tolower"时将char转换为int
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- JavaCPP 错误:无法将参数"1"的"char*"转换为"Abc*
- 为什么从 char 转换为 std::byte 可能是未定义的行为?
- 如何在虚幻引擎4中将char*转换为TCHAR?
- C++:将模板类型 char 转换为 std::string
- strcmp/char* 转换无法按预期工作
- C++中的SQLite char*转换
- 无法从 const char* 转换为 const char *&
- 在 C++ 中将 char 转换为 int,而无需符号位传播
- 如果必须包含西里尔字符,如何将 char* 转换为 std::string?
- 试图使用strCMP时的char转换错误
- 无法从'const char *'转换为'LPCTSTR'
- 将 std::vector<char> 转换为字符* 会导致字符缺陷
- 使用 static_cast 将 char 转换为 int c++
- 如何在 C++(MFC) 中将 char* 转换为 LPCTSTR
- 无法将const char转换为字符串构造字符串