Reputation: 21194
If I'm developing for Windows and some WinAPI functions require me to use LPWSTR as string data type. Is it okay to use C++11's u16string in my library? Are those two data types the same thing?
It looks more like LPWSTR is wchar_t, but nobody likes wchar_t anymore...
Upvotes: 4
Views: 2551
Reputation: 157324
wchar_t
and char16_t
are distinct types, so it is not possible to use u16string.c_str()
as a LPWSTR
(without a reinterpret_cast
that would cause undefined behavior).
If you are confident that on your platform wchar_t
is encoded as UTF-16, you can copy the data across:
std::wstring my_wstring(my_u16string.begin(), my_u16string.end());
and then use my_wstring.c_str()
as LPWSTR. In a function call, you can use a temporary:
SomeWindowsAPI(std::wstring(my_u16string.begin(), my_u16string.end()).c_str());
Upvotes: 2
Reputation: 595762
wchar_t
on Windows is 16-bit, and LPWSTR
values are UTF-16 encoded, so yes, you can use char16_t
and u16string
values when interacting with the API, though you will have to typecast to keep the compiler happy.
Upvotes: 1
Reputation: 145239
The C++11 char16_t
type is distinct from wchar_t
. In theory you could reinterpret_cast
your way between char16_t*
and Windows’ wchar_t*
(Windows’ wchar_t
is 16 bits). In practice, however, Visual C++ 10.0 – and I think also Visual C++ 11.0 – lacks support for Unicode literals like u'A'
or u"A"
.
Summing up (I’ve found that on SO one should better make all conclusions explicit):
“Is it okay to use C++11's u16string in my library?”
Certainly, but not as direct plug-in replacements for wchar_t
strings, and as of 2012 currently problematic (due to lack of support for literals) if you plan on supporting Visual C++.
“Are those two data types the same thing?”
No.
“nobody likes wchar_t anymore...”
That’s certainly not the case.
Upvotes: 2