How do I convert from a wchar_t* to a wstring?

ScArcher2 picture ScArcher2 · Jan 18, 2012 · Viewed 16.2k times · Source

Or how to I initialize a wstring using a wchar_t*?

I tried something like this, but it's not quite working. I'm given an LPVOID and it points to a wchar_t pointer. I just want to get it into a wstring so I can use some normal string functions on it.

LPVOID lpOutBuffer = NULL;
//later in code this is initialized this way
lpOutBuffer = new WCHAR[dwSize/sizeof(WCHAR)];
//fills up the buffer
doStuff(lpOutBuffer, &dwSize);
//try to convert it to a wstring
wchar_t* t =  (wchar_t*)lpOutBuffer;
wstring responseHeaders = wstring(t);

printf("This prints response headers: \n%S", t);
printf("This prints nothing: \n%S", responseHeaders);

doStuff is really a call to WinHttpQueryHeaders I just changed it to make it easier to understand my example.

Answer

Drew Dormann picture Drew Dormann · Jan 18, 2012

If the LPVOID points to a wchar_t pointer as you say, your level of indirection is wrong.

LPVOID lpOutBuffer;
wchar_t** t =  (wchar_t**)lpOutBuffer;
wstring responseHeaders = wstring(*t);

Edit: Question has changed. This answer no longer applies.