8

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

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Thanks, this is the only solution that worked in my case.
3

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

1 Comment

The type is LPTSTR, strcpy will not work if UNICODE, _UNICODE is defined.
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));

Comments

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) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.