tags:

views:

642

answers:

3

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.

+4  A: 

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")).

PiotrLegnica
personally i always use the "_T" macro but it does exactly the same thing :)
Goz
TEXT("bar") is a const string, LPCTSTR. LPTSTR is non-const, so this may not work.
Kim Gräsman
Thanks. TEXT("bar") worked fine.
CaptnCraig
I'm pretty sure you can actually just do foo(L"bar") - try it.
Ricket
+1  A: 

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.

Kim Gräsman
your line of code will not compile on unicode builds - you need to use one of the smart T macros. These days I just don't even use the T types, they are kind of an anacronism these days since everything is unicode
1800 INFORMATION
Thanks, I edited before I saw that.
Kim Gräsman
A: 
foo(const_cast<LPTSTR>("bar"));

Will crash as explained above when foo tries to change the data that's been passed to it.

karx11erx