none
How to convert String^ to std::string in C++/CX RRS feed

  • Question

  • Hi all, I don't have much experience with C++/CX. I have requirement where I need to convert the C# string data to C++ std::string data.

    I have tried following code which is giving build error: unresolved external symbol.

    C++ Code:

    String^ req;
    std::wstring ws(req->Data());
    	std::string request((const char*)&ws[0], sizeof(wchar_t) / sizeof(char)*ws.size());
    	_networkApi->Post(request);
    
     

    The definition of the PostRequest method as below:

    void	Post (std::string &s);

    When I removed _networkApi->Post(request). then the project build successfully. Please suggest me a solution.

    Thanks in advance... :)


    Pallam Madhukar Windows Phone Developer

    Thursday, August 28, 2014 11:13 AM

All replies

  • I guess the section String conversions of this article: http://msdn.microsoft.com/en-us/library/windows/apps/hh699879.aspx contains all the information you need.

    • Proposed as answer by Oliver Ulm Thursday, August 28, 2014 11:32 AM
    Thursday, August 28, 2014 11:32 AM
  • Hi Oliver Ulm

    From that link, I didn't get the information which I need. please suggest me.

    Thanks you


    Pallam Madhukar Windows Phone Developer


    Thursday, August 28, 2014 12:32 PM
  • the String^ type is actually Platform::String has data that is only compatible with std::wstring when it comes to it's data (16 bit characters = std::wchar_t instead of 8 bit characters). So you can do something like this:

    String^ str1 = "Hello World!";
    std::wstring wstr1 ( str1->Data() );//initialize the std::wstring using the data from the String^

    So now you need to convert that std::wstring to a std:string which you can do for example using functions as shown here: http://codereview.stackexchange.com/questions/419/converting-between-stdwstring-and-stdstring

    std::string ws2s(const std::wstring& s)
    {
        int len;
        int slength = (int)s.length() + 1;
        len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0); 
        std::string r(len, '\0');
        WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, &r[0], len, 0, 0); 
        return r;
    }

    There seem to be some caveats attached to this as lined out on the page it was taken from. But Basically using that function you should be able to convert it.


    Thursday, August 28, 2014 2:21 PM
  • Hi Oliver Ulm,your code seems to right but when I build project I got following error

    Please tell me the what could be the problem. 


    Pallam Madhukar Windows Phone Developer


    Thursday, August 28, 2014 4:10 PM
  • Looks to me as if the Linker is not able to find the method that you are trying to call (the one using std::String). I can't tell you how to fix that though - are you able to call any other functions or methods from your Network API?
    Friday, August 29, 2014 12:52 PM