views:

4924

answers:

5

How do I convert a CString to const char* in my Unicode MFC application?

+9  A: 

Note: This answer predates the Unicode requirement; see the comments.

Just cast it:

CString s;
const TCHAR* x = (LPCTSTR) s;

It works because CString has a cast operator to do exactly this.

Using TCHAR makes your code Unicode-independent; if you're not concerned about Unicode you can simply use char instead of TCHAR.

RichieHindle
when i try your method, i get this error :"Error 1 error C2664: 'CppSQLite3DB::execDML' : cannot convert parameter 1 from 'const TCHAR *' to 'const char *'".my projetc settings use Unicode but the function CppSQLite3DB::execDML requires a const char* parameter.
Attilah
As Mark says, you need to convert from a Unicode CString to an ANSI CStringA: CStringA charstr(unicodestr); You can then cast the CStringA to a const char*
RichieHindle
+2  A: 

There is an explicit cast on CString to LPCTSTR, so you can do (provided unicode is not specified):

CString str;
// ....
const char* cstr = (LPCTSTR)str;
Reed Copsey
+6  A: 

If your CString is Unicode, you'll need to do a conversion to multi-byte characters. Fortunately there is a version of CString which will do this automatically.

CString unicodestr = _T("Testing");
CStringA charstr(unicodestr);
DoMyStuff((const char *) charstr);
Mark Ransom
when i use this, i get this error : "Error 2 error C2440: 'initializing' : cannot convert from 'CString' to 'ATL::CStringT<BaseType,StringTraits>'""
Attilah
@Attilah: Thanks for catching that, I had the syntax wrong. Fixed.
Mark Ransom
+7  A: 

To convert a TCHAR CString to ASCII, use the CT2A macro - this will also allow you to convert the string to UTF8 (or any other Windows code page):

// Convert using the local code page
CString str(_T("Hello, world!"));
CT2A ascii(str);
TRACE(_T("ASCII: %S\n"), ascii.m_psz);

// Convert to UTF8
CString str(_T("Some Unicode goodness"));
CT2A ascii(str, CP_UTF8);
TRACE(_T("UTF8: %S\n"), ascii.m_psz);

// Convert to Thai code page
CString str(_T("Some Thai text"));
CT2A ascii(str, 874);
TRACE(_T("Thai: %S\n"), ascii.m_psz);

There is also a macro to convert from ASCII -> Unicode (CA2T) and you can use these in ATL/WTL apps as long as you have VS2003 or greater.

See the MSDN for more info.

Rob
i already got the answer to the question a little bit earlier and you're right, I used the CT2A macro.Thanks.
Attilah
A: 

I had a similar problem. I had a char* buffer with the .so name in it. I could not convert the char * variable to LPCTSTR. Here's how I got around it...

char *fNam;

...

LPCSTR nam = fNam;

dll = LoadLibraryA(nam);

Mr.What