Const char * to LPTSTR

I am trying to call a function that takes LPTSTR as a parameter. I call this a string literal, as in foo ("bar");

I am getting the error "I cannot convert parameter 1 from" const char [3] "to" LPTSTR ", but I have no idea why or how to fix it. Any help would be great.

+2


source to share


3 answers


You probably defined UNICODE and LPTSTR expanded to wchar_t *. Use the TEXT macro for string literals to avoid problems with this eg. foo(TEXT("bar"))

...



+6


source


LPTSTR is a non-const pointer to TCHAR. TCHAR, in turn, is defined as char in ANSI assemblies, and wchar_t in Unicode strings (with UNICODE and / or _UNICODE characters defined).

So LPTSTR is equivalent to:

  TCHAR foo[] = _T("bar");

      



Just like non-const, you cannot safely call it a literal - literals can be allocated to read-only memory segments, and LPTSTR is a signal that the caller can change the contents of the string, for example

  void truncate(LPTSTR s)
  {
     if (_tcslen(s) > 4)
        s[3] = _T('\0');
  }

      

It would work if you passed in a literal when compiled with Visual C ++ 2008.

+1


source


foo(const_cast<LPTSTR>("bar"));

      

It crashes as described above when foo tries to modify the data passed to it.

0


source







All Articles