ScArcher2
ScArcher2

Reputation: 87167

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

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.

Upvotes: 3

Views: 18317

Answers (3)

MyVat9
MyVat9

Reputation: 1

Again, too complicated. Just do this:

std::wstring TheNewWideString = std::wstring(TheOldWideCharacterTPointer);

It works directly for me on Microsoft Windows with C++11 and CodeBlocks.

Upvotes: 0

Seva Alekseyev
Seva Alekseyev

Reputation: 61331

Passing the wstring object to printf is not going to work. Rephrase the second prinf line as

printf("This prints nothing: \n%S", responseHeaders.c_str()); 

c_str() gives you a const pointer to the underlying string data.

Upvotes: 4

Drew Dormann
Drew Dormann

Reputation: 63694

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.

Upvotes: 4

Related Questions