How do I convert from CString
to const char*
in my Unicode MFC application?
This question is related to
c++
visual-studio
visual-c++
unicode
mfc
I recommendo to you use TtoC from ConvUnicode.h
const CString word= "hello";
const char* myFile = TtoC(path.GetString());
It is a macro to do conversions per Unicode
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
.
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);
Generic Conversion Macros (TN059 Other Considerations section is important):
A2CW (LPCSTR) -> (LPCWSTR)
A2W (LPCSTR) -> (LPWSTR)
W2CA (LPCWSTR) -> (LPCSTR)
W2A (LPCWSTR) -> (LPSTR)
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;
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);
I used this conversion:
CString cs = "TEST";
char* c = cs.GetBuffer(m_ncs me.GetLength())
I hope this is useful.
Source: Stackoverflow.com