如何在char *和Platform :: String ^之间进行转换?

时间:2015-12-04 13:44:34

标签: string visual-c++ uwp

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

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

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

Not the most elegant but the only solution that worked for me to get const char * from the Platform::String

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;
}

and its a lot easier to convert it back

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);
}