How to convert Platform::String to char*?

后端 未结 5 1277
长情又很酷
长情又很酷 2020-12-01 23:53

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 ju

相关标签:
5条回答
  • 2020-12-02 00:01

    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();
    
    0 讨论(0)
  • 2020-12-02 00:05

    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.

    There's no direct way 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.

    0 讨论(0)
  • 2020-12-02 00:07

    There's the String::Data method returning const char16*, which is the raw unicode string.

    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.

    0 讨论(0)
  • 2020-12-02 00:14

    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:

    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

    0 讨论(0)
  • 2020-12-02 00:26

    A solution using 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);
    
    0 讨论(0)
提交回复
热议问题