This question may already be having an answer but I felt I needed to ask it because I cant seem to get the answer I need for the code to work as intended on VS Community 2017 since it worked well on VS Express Edition.
I am trying to implement a code i picked up from a c project but I can't see how to get around the error:
Value of type "const char *" cannot be assigned to an entity of type "LPSTR"
and
cannot convert from 'const char [7]' to 'LPSTR'
MENUITEMINFO mii = { 0 };
mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_TYPE;
mii.fType = MFT_STRING;
mii.dwTypeData = _T("item 1"); // error is on this line
mii.dwTypeData = _T("item 2"); // error is on this line also
NOTE:
A string literal is of type const char[N]
, its contents must not be modified. The ability to implicitly convert string literals to char*
was only ever there in C++ for backwards compatibility with C. It's a very dangerous thing, has been deprecated basically forever, and was finally removed in C++11. Visual Studio 2017 switched the default language standard to C++14, which is most likely the reason why your code stopped working there. If you absolutely, positively, definitely know for sure that the string pointed to won't be modified, then you can use a const_cast
MENUITEMINFO mii = { 0 };
mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_TYPE;
mii.fType = MFT_STRING;
mii.dwTypeData = const_cast<char*>("item 1");
Ideally, you would just use const char*
, but interop with some old C APIs, unfortunately, sometimes requires the use of const_cast
. Before you do this sort of thing, always check the API documentation to make sure that there is no way the API will attempt to modify the contents of the string.
In the case of your MENUITEMINFO
here, the reason why the dwTypeData
is a char*
rather than a const char*
is most likely that the struct is intended to be used with both GetMenuItemInfo
and SetMenuItemInfo
where the former expects a pointer to a buffer in which it will write a string while the latter expects a pointer to a buffer from which it will read a string…
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