c++ convert from LPCTSTR to const char *
I have this problem in MSVC2008 MFC. I´m using unicode. I have a function prototype:
MyFunction(const char *)
and I'm calling it:
MyfunFunction(LPCTSTR wChar).
error:Cannot Convert Parameter 1 From 'LPCTSTR' to 'const char *'
How to resolve it?
Since you're using MFC, you can easily let CString do an automatic conversion from
char
toTCHAR
:This works whether your original string is
char
orwchar_t
based.Edit: It seems my original answer was opposite of what you asked for. Easily fixed:
CStringA
is a version ofCString
that specifically containschar
characters, notTCHAR
. There's also aCStringW
which holdswchar_t
.LPCTSTR
is a pointer toconst TCHAR
andTCHAR
isWCHAR
andWCHAR
is most probablywchar_t
. Make your function takeconst wchar_t*
if you can, or manually create aconst char*
buffer, copy the contents, and pass that.When UNICODE is defined for an MSVC project
LPCTSTR
is defined asconst wchar_t *
; simply changing the function signature will not work because whatever code within the function is using the input parameter expects aconst char *
.I'd suggest you leave the function signature alone; instead call a conversion function such as
WideCharToMultiByte
to convert the string before calling your function. If your function is called several times and it is too tedious to add the conversion before every call, create an overloadMyFunction(const wchar_t *wChar)
. This one can then perform the conversion and call the original version with the result.This may not be totally on topic, but I wrote a couple of generic helper functions for my proposed wmain framework, so perhaps they're useful for someone.
Make sure to call
std::setlocale(LC_CTYPE, "");
in yourmain()
before doing any stringy stuff!You could provide "dummy" overloads:
Now, if you have an
LPCTSTR x
, you can always callget_locale_string(x).c_str()
to get achar
-string.If you're curious, here's the rest of the framework:
Now the
main()
-- your new entry point is alwaysint wmain(const std::vector<std::wstring> args)
: