Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert wstring to wchar_t*? C++

I would like to convert wstring to wchar_t*. I have tried everything what i know, please help. I would like to convert wstring to wchar_t*.

like image 882
Jones Jones Avatar asked Jul 08 '17 11:07

Jones Jones


2 Answers

Did you try reading the reference

const wchar_t* wcs = s.c_str();
like image 82
K. Kirsz Avatar answered Oct 24 '22 01:10

K. Kirsz


There is no way to convert wstring to wchar_t* but you can convert it to const wchar_t* which is what answer by K.Kirsz says.

This is by design because you can access a const pointer but you shouldn't manipulate the pointer. See a related question and its answers.

The best bet is to create a new string using _wcsdup and access the non const buffer, an ascii example is given there.

For unicode:

    wstring str = L"I am a unicode string";
    wchar_t* ptr = _wcsdup(str.c_str());
    // use ptr here....
    free(ptr); // free memory when done
like image 3
zar Avatar answered Oct 23 '22 23:10

zar