8

How to convert CString in MFC to char[] (character array)

sharptooth
  • 167,383
  • 100
  • 513
  • 979
yesraaj
  • 46,370
  • 69
  • 194
  • 251

5 Answers5

9

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.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
5

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.

Mark Eckdahl
  • 96
  • 1
  • 4
3

You can use GetBuffer function to get the character buffer from CString.

Community
  • 1
  • 1
Naveen
  • 74,600
  • 47
  • 176
  • 233
1

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));
masche
  • 1,643
  • 2
  • 14
  • 24
0

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) );
ingconti
  • 10,876
  • 3
  • 61
  • 48