Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char* to LPTSTR

Tags:

c++

I am trying to call a function that accepts an LPTSTR as a parameter. I am calling it with a string literal, as in foo("bar");

I get an error that 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.

like image 576
captncraig Avatar asked Sep 11 '09 20:09

captncraig


2 Answers

You probably has UNICODE defined, and LPTSTR expands into wchar_t*. Use TEXT macro for string literals to avoid problems with that, e.g. foo(TEXT("bar")).

like image 64
Cat Plus Plus Avatar answered Sep 26 '22 03:09

Cat Plus Plus


An LPTSTR is a non-const pointer to a TCHAR. A TCHAR, in turn, is defined as char in ANSI builds and wchar_t in Unicode builds (with the UNICODE and/or _UNICODE symbols defined).

So, an LPTSTR is equivalent to:

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

As it's not const, you can't safely call it with a literal -- literals can be allocated in read-only memory segments, and LPTSTR is a signal that the callee may alter the contents of the string, e.g.

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

That would crash if you passed in a literal, when compiled with Visual C++ 2008.

like image 23
Kim Gräsman Avatar answered Sep 26 '22 03:09

Kim Gräsman