I'm trying to create a (very) simple Win32 GUI program, but for some reason the compiler (I'm using VC++ 2008 Express) wants me to manually typecast every string or char* to LPCWSTR:
I get this compiler error every time I do this, for example I get this error for the "Hello" and "Note":
error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'const char [22]' to 'LPCWSTR'
Please tell me I don't have to cast every time I do this....
Here's the code:
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
MessageBox(NULL, "Hello", "Note", MB_OK);
return 0;
}
This LPCWSTR is Microsoft defined. So to use them we have to include Windows. h header file into our program. To convert std::wstring to wide character array type string, we can use the function called c_str() to make it C like string and point to wide character string.
An LPCWSTR is a 32-bit pointer to a constant string of 16-bit Unicode characters, which MAY be null-terminated.
If you specifically need Unicode, you can use CStringW, even in a non-Unicode program. LPSTR psz = (LPSTR)(LPCSTR)str; The (LPCSTR) cast actually calls a conversion operator on CString, which returns a pointer to the CString internal buffer. The (LPSTR) cast removes the const-ness of the pointer.
The LPSTR type and its alias PSTR specify a pointer to an array of 8-bit characters, which MAY be terminated by a null character. In some protocols, it is acceptable to not terminate with a null character, and this option will be indicated in the specification.
The default for new projects in VS2008 is to build UNICODE aware applications. You can either change that default and go back to using ANSI or MBCS apps (Properties->Configuration Properties->General->Character Set), or use Unicode Strings like this:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
MessageBox(NULL, L"Hello", L"Note", MB_OK);
return 0;
}
Do not cast your strings to LPCWSTR because that will lead to undefined behavior! A char is not the same as a wchar_t!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With