How to convert char * to String ^? RRS feed

  • Question

  • How can i convert char * to Platform::String ^?

    I am geting char * from unmanaged dll and formatting with other values(chars, integers...) into another char *. After that, i want to convert that to String^.

    How can i convert it?

    Saturday, April 14, 2012 9:53 AM


All replies

  • You'll need to convert your string to Unicode with MultiByteToWideChar and then you can pass it in to the String constructor. You can read out the String^'s buffer from its Data member.

    String^ str = ref new String(L"Lorem ipsum dolor sit amet"); 
    std::wstring wstr(str->Data());

    See Strings (Visual C++ for Windows Runtime) and Platform::String, std::wstring, and Literals for more detail.


    Sunday, April 15, 2012 6:11 PM
  • I am using this: Is this a bad way?

    What is the better way?

    char statusHelper[512];
    for(int i=0;i<4;i++){
    sprintf(statusHelper,"[%d] %s\n",i,myLibVariable->myset[i]->myCharArrayValue); //default c string
    String ^statusString=
    ref new String( s2ws(statusHelper).c_str());
    std::wstring s2ws(const std::string& s)
        int len;
        int slength = (int)s.length() + 1;
        len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
        wchar_t* buf = new wchar_t[len];
        MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
        std::wstring r(buf);
        delete[] buf;
        return r;

    Monday, April 16, 2012 6:39 AM
  • Use the atops function (at the end)

    std::wstring stows(std::string s)
    	std::wstring ws;
    	ws.assign(s.begin(), s.end());
    	return ws;
    std::string wstos(std::wstring ws)
    	std::string s;
    	s.assign(ws.begin(), ws.end());
    	return s;
    Platform::String ^stops(std::string s)
    	return ref new Platform::String(stows(s).c_str());
    std::string pstos(Platform::String^ ps)
    	return wstos(std::wstring(ps->Data()));
    Platform::String ^atops(const char *text)
    	return stops(std::string(text));

    Monday, April 16, 2012 5:09 PM
  • Hi,

    I'm trying to use your function atops.
    However, the stops remains undefined in my source code.
    Do we need to include a specific file ?


    Tuesday, August 13, 2013 9:06 AM