【问题标题】:How to convert between char* and Platform::String^?如何在 char* 和 Platform::String^ 之间进行转换?
【发布时间】:2016-03-09 11:17:25
【问题描述】:

如何将字符串从 char* 转换为 Platform::String^,反之亦然?

我正在为通用 Windows 平台开发一个 DLL,使用版本 10.0.10586.0 的 SDK 和 Visual Studio 2015 Update 1。

【问题讨论】:

    标签: string visual-c++ uwp


    【解决方案1】:
    //Char to String
    char *text = "new string";
    Platform::String str = new Platform::String(text, strlen(text));
    
    //String to char
    char16 *newText =  str.Data();
    

    更详细的回答:https://stackoverflow.com/a/11746252/5477130

    【讨论】:

    • 从 char* 转换为 String 的代码不起作用:它说“不可能在 C++/CX 类中使用 new(必须使用 ref new)。所以我将其更改为 @ 987654323@ 但随后它说该构造函数不存在。
    【解决方案2】:

    不是最优雅但对我有用的从 Platform::String 获取 const char * 的唯一解决方案

    const char * StringToChar(String^ s) {
        const wchar_t *W = s->Data();
        int Size = wcslen(W);
        char *CString = new char[Size + 1];
        CString[Size] = 0;
        for (int y = 0;y<Size; y++)
        {
            CString[y] = (char)W[y];
        }
        return (const char *)CString;
    }
    

    而且它更容易转换回来

    String^ CharToString(const char * char_array) {
        std::string s_str = std::string(char_array);
        std::wstring wid_str = std::wstring(s_str.begin(), s_str.end());
        const wchar_t* w_char = wid_str.c_str();
        return ref new String(w_char);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 2020-06-06
      • 2015-12-23
      • 2011-08-22
      相关资源
      最近更新 更多