C++ 如何将 Platform::String 转换为 char*?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11746146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Platform::String to char*?
提问by djcouchycouch
How do I convert the contents of a Platform::String to be used by functions that expect a char* based string? I'm assuming WinRT provides helper functions for this but I just can't find them.
如何转换 Platform::String 的内容以供期望基于 char* 的字符串的函数使用?我假设 WinRT 为此提供了帮助函数,但我找不到它们。
Thanks!
谢谢!
采纳答案by James McNellis
Platform::String::Data()
will return a wchar_t const*
pointing to the contents of the string (similar to std::wstring::c_str()
). Platform::String
represents an immutable string, so there's no accessor to get a wchar_t*
. You'll need to copy its contents, e.g. into a std::wstring
, to make changes.
Platform::String::Data()
将返回一个wchar_t const*
指向字符串内容的指针(类似于std::wstring::c_str()
)。 Platform::String
代表一个不可变的字符串,所以没有访问器来获取wchar_t*
. 您需要复制其内容,例如复制到 astd::wstring
中以进行更改。
There's no directway to get a char*
or a char const*
because Platform::String
uses wide characters (all Metro style apps are Unicode apps). You can convert to multibyte using WideCharToMultiByte
.
没有直接获取 achar*
或 a 的方法,char const*
因为Platform::String
使用宽字符(所有 Metro 风格应用程序都是 Unicode 应用程序)。您可以使用WideCharToMultiByte
.
回答by rysama
Here is a very simple way to do this in code w/o having to worry about buffer lengths. Only use this solution if you are certain you are dealing with ASCII:
这是在代码中执行此操作的一种非常简单的方法,无需担心缓冲区长度。仅当您确定要处理 ASCII 时才使用此解决方案:
Platform::String^ fooRT = "aoeu";
std::wstring fooW(fooRT->Begin());
std::string fooA(fooW.begin(), fooW.end());
const char* charStr = fooA.c_str();
Keep in mind that in this example, the char*
is on the stack and will go away once it leaves scope
请记住,在此示例中,char*
is 在堆栈中,一旦离开作用域就会消失
回答by Jeff McClintock
You shouldn't cast a wide character to a char, you will mangle languages using more than one byte per character, e.g. Chinese. Here is the correct method.
您不应该将宽字符转换为字符,您将使用每个字符多于一个字节来破坏语言,例如中文。这是正确的方法。
#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();
回答by Sistr
回答by Qnan
There's the String::Data
method returning const char16*
, which is the raw unicode string.
有String::Data
方法返回const char16*
,它是原始 unicode 字符串。
Conversion from unicode to ascii or whatever, i.e. char16*
to char*
, is a different matter. You probably don't need it since most methods have their wchar
versions these days.
从 unicode 到 ascii 或其他任何东西的转换,即char16*
到char*
,是另一回事。您可能不需要它,因为现在大多数方法都有它们的wchar
版本。