question

flaviu avatar image
0 Votes"
flaviu asked flaviu commented

LPCTSTR to const char*

In a MFC project, I have encoutnered an issue using CDatabase::ExecuteSQL method, whend I have tried to deliver a std::string as a parameter:


 void ExecuteSQL(LPCTSTR lpszSQL);
    
 std::string sql;
 ExecuteSQL(sql.c_str());

in Use Unicode Character Set configuration only.

The error is:

 'void CDatabase::ExecuteSQL(LPCTSTR)': cannot convert argument 1 from 'const _Elem *' to 'LPCTSTR'
    
 note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

So, which one of conversion is better ? reinterpret_cast or C-style cast ? Or doesn't matter ?





c++
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RLWA32-6355 avatar image
2 Votes"
RLWA32-6355 answered flaviu commented

A cast won't solve the problem. The std::string is encapsulating a narrow string. So the member function c_str() is returning a const char * pointer. You need to convert the result to UNICODE or otherwise change the code to use std::wstring when building for UNICODE.

· 7
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

But how can do in order to be OK with Use Unicode Character Set and Use Multi-Byte Character Set without using stringstream ?

0 Votes 0 ·

One way is old-fashioned conditional compilation -

         //  Example 1
         #ifdef UNICODE
             std::wstring sql;
         #else
             std::string sql;
         #endif

Another way is to use a typedef -

         //  Example 2
         typedef std::basic_string<TCHAR> tstring;
    
         tstring sql;


2 Votes 2 ·

Unfortunately, I don't think I can use any of them, the code should be compatible with old compilers. If not, I could use std::stringstream or std::basic_stringstream or something.

0 Votes 0 ·
Show more comments