0

How do I convert a string from char* to Platform::String^ and vice versa?

I'm developing a DLL for the Universal Windows Platform, using version 10.0.10586.0 of the SDK and Visual Studio 2015 Update 1.

user1945293
  • 127
  • 3
  • 9

2 Answers2

1

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);
}
Alex Krafts
  • 505
  • 2
  • 11
0
//Char to String
char *text = "new string";
Platform::String str = new Platform::String(text, strlen(text));

//String to char
char16 *newText =  str.Data();

More detailed answer: https://stackoverflow.com/a/11746252/5477130

Community
  • 1
  • 1
Nazar Sakharenko
  • 1,007
  • 6
  • 11
  • The code for converting from char* to String doesn't work: it says "Impossible to use new in a C++/CX class (it's necessary to use ref new). So I changed that to `char *text = "new string"; Platform::String^ str = ref new Platform::String(text, strlen(text));` but then it says that that constructor doesn't exist. – user1945293 Dec 04 '15 at 14:16