3

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.

ScArcher2
  • 85,501
  • 44
  • 121
  • 160
  • 2
    Should work - `wstring` has a constructor for that. What do you get? Also, is the buffer null-terminated? – Seva Alekseyev Jan 18 '12 at 19:34
  • I updated the code with what's happening to initialize the pointer. I'm new to c++ so I'm still wrapping my head around pointers and such. I don't know if the the wchar_t is null terminated. I'm calling the WinHttpQueryHeaders Funtion - http://msdn.microsoft.com/en-us/library/windows/desktop/aa384102(v=vs.85).aspx I couldn't tell if it was null terminating the buffer. – ScArcher2 Jan 18 '12 at 19:40
  • 1
    @ScArcher2: What does "it's not quite working" mean? – Drew Dormann Jan 18 '12 at 19:42
  • 1
    @DrewDormann The responseHeaders wstring is empty when i attempt to print it out. If I print the wchar_t it prints out what I expect. – ScArcher2 Jan 18 '12 at 19:44

3 Answers3

4

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.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
4

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.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
0

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.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
MyVat9
  • 1