How to I get the contents from a wchar_t array into a LPWSTR?

106 Views Asked by At

I found a very old post, which gives the answer as:

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.

I think I understand the first part - create a new array of wchar_t and copy the contents of the LPCWSTR to it.

wstring wstrSrc(myString.begin(), myString.end());
const int lngth = sizeof(wstrSrc) / sizeof(int);
PCWSTR str2PCWSTR = wstrSrc.c_str();
const wchar_t* filepath[lngth]{ str2PCWSTR };

However, I am not sure how to do the second part - use it in the function taking a LPWSTR.

How do I use the contents of the wchar_t array in a PWSTR?

I tried searching for a clearer answer to the one I found, and tried, or made an effort to understand the suggestion.

I have not gotten any further than the code above.

1

There are 1 best solutions below

3
Some programmer dude On

LPWSTR is an alias for wchar_t*. So if you have an array of wchar_t elements, you already have a LPWSTR (remember that arrays decay to pointers to their first element).

As for getting a LPWSTR from a wstring object, just get a pointer to its first element: &wstrSrc[0]. That will be a wchar_t*, which as said above is the same as LPWSTR. With later standards of C++ you can also use wstrSrc.data() to get the pointer.

If you want a pointer to constant string (i.e. LPCWSTR) then use wstrSrc.c_str().


As for other problems sizeof returns the size of the object you pass to it, which in the case of wstrSrc will be the size of a std::wstring (assuming wstring is std::wstring). And the size of std::wstring is not the length of the string, as std::wstring only keeps a pointer to the actual string data.

To get the length in wchar_t elements from the string object use its length function: wstrSrc.length().

Also note that on Windows using the MSVC compiler, sizeof(wchar_t) != sizeof(int). On Windows using MSVC the size of wchar_t is currently 2 while the size of a 32-bit int is 4.