6

How can I convert LPCWSTR to LPWSTR.

In one method I am getting an argument type as LPCWSTR. This parameter(LPCWSTR) has to be passed to another method of argument type LPWSTR.

kanden
  • 177
  • 1
  • 4
  • 11

3 Answers3

9

Create a new string, copy the contents into it, and then call the function that expects a modifiable string:

LPCWSTR str = L"bar";
std::wstring tempStr(str); 
foo(&tempStr[0]);
Mike Vonn
  • 182
  • 3
  • 8
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
7

LPCWSTR is a pointer to a const string buffer. LPWSTR is a pointer to a non-const string buffer. Just create a new array of wchar_t and copy the contents of the LPCWSTR to it and use it in the function taking a LPWSTR.

0

You probably need to create a copy of the string, and pass a pointer to the copy. An LPCWSTR i a pointer to a const, which means the content can't be modified. An LPWSTR is a pointer to non-const, meaning it may modify the content, so you need to make a copy it can modify before you can use that function.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • @ Jerry, in my requirement, no need to change the paratmeter content – kanden Mar 22 '12 at 16:08
  • 1
    @kanden: if the function doesn't modify the string, then change its parameter to LPCWSTR. Having done this, you'll be able to pass the existing LPCWSTR directly, with no conversion needed. – Jerry Coffin Mar 22 '12 at 16:40