How to convert CString in MFC to char[] (character array)
5 Answers
You use CString::GetBuffer() to get the TCHAR[] - the pointer to the buffer. If you compiled without UNICODE defined that's enough - TCHAR is same as char, otherwise you'll have to allocate a separate buffer and use WideCharToMultiByte() for conversion.

- 167,383
- 100
- 513
- 979
I struggled with this, but what I use now is this: (UNICODE friendly)
CString strCommand("My Text to send to DLL.");
**
char strPass[256];
strcpy_s( strPass, CStringA(strCommand).GetString() );
**
// CStringA is a non-wide/unicode character version of CString This will then put your null terminated char array in strPass for you.
Also, if you control the DLL on the other side, specifying your parameters as:
const char* strParameter
rather than
char strParameter*
will "likely" convert CStrings for you with the default casting generally being effective.

- 96
- 1
- 4
-
Thanks, this is the only solution that worked in my case. – Eliezer Miron Dec 19 '22 at 23:13
You can use GetBuffer function to get the character buffer from CString.
-
4The type is LPTSTR, strcpy will not work if UNICODE, _UNICODE is defined. – dirkgently Apr 24 '09 at 09:51
Calling only the GetBuffer method is not sufficient, you'll need too copy this buffer to the array.
For example:
CString sPath(_T("C:\temp\"));
TCHAR tcPath[MAX_PATH];
_tcscpy(szDisplayName, sPath.GetBuffer(MAX_PATH));

- 1,643
- 2
- 14
- 24
As noted elsewhere, if You need to port CString for warning C4840: non-portable f.
The quick, Unicode && Multibyte striong conversion is using:
static_cast
sample:
//was: Str1.Format( szBuffer, m_strName );
Str1.Format(szBuffer, static_cast<LPCTSTR>(m_strName) );

- 10,876
- 3
- 61
- 48