MessageBox
function takes two arguments correctly typed asLPCTSTR
. Assuming unicode that is equal toLPCWSTR
orwchar_t const *
.- Under unicode, you shouldn't1 work with
std::string
at all. It is based onchar
and you will needwchar_t
-based string everywhere. - The
std::wstring
is based onwchar_t
, so you want to use that. - Since the arguments are properly const,
MessageBox
will accept result ofstd::wstring::c_str()
without casting.
Note, that many of the casts in your code are unnecessary. Let's start with:
/* convert/cast LPTSTR to LPCWSTR */
LPCWSTR test = (LPCWSTR) lpCmdLine;
LPCWSTR
is wchar_t const *
and if you have unicode set (as you seem to), LCTSTR
is wchar_t *
. And adding const
is implicit conversion in C++. So
test = lpCmdLine;
will do the same. Without risking an error by not having unicode selected, in which case LCTSTR
expands to char *
and the statement would fail with "cannot convert to incompatible pointer type" error. With the cast it compiles, but since the C-style cast does a reinterpret cast, i.e. treats the memory content as the requested type, the result is garbage.
Now what I don't understand is this:
BOOL status = CreateProcess((LPWSTR) LgetGamePath("World of RPG.exe").c_str(), game_args, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInformation);
The function LgetGamePath
gets a narrow string (wide literals have L
prefix, which can also be generated with the TEXT()
macro), so I would expect it to return a narrow string (you don't seem to show that signature, so I don't know for certain). Now you blindly cast it to wide, which will yield garbage and it shouldn't be able to start the process. On the other hand the conversion of the arguments actually seems correct, as long as the string is ASCII only.
1For portable programs wchar_t
is still a mess, because it is 4 bytes on some platforms and 2 bytes on others (including windows that eagerly created wide versions of all interfaces when 2 bytes were enough and were stuck with 2 bytes when Unicode exceeded it). And at least for input and output you usually need a specific encoding, which is often Utf-8 (due to it's backward compatibility with ASCII, but Windows don't support it). So many people, including me, when writing portable programs just prepare conversion functions for calling system interfaces somewhere and work in Utf-8 (like e.g. Gtk) or Utf-16 (stored in uint16_t
, not wchar_t
, as do Qt or ICU) internally.