Convert CString to character array?
Asked Answered
D

5

8

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

Demonstrative answered 24/4, 2009 at 9:38 Comment(0)
F
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.

Francisco answered 24/4, 2009 at 10:0 Comment(0)
W
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.

Workhorse answered 9/3, 2016 at 20:47 Comment(1)
Thanks, this is the only solution that worked in my case.Rapping
D
3

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

Dastardly answered 24/4, 2009 at 9:42 Comment(1)
The type is LPTSTR, strcpy will not work if UNICODE, _UNICODE is defined.Spencer
S
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));
Sproul answered 7/5, 2015 at 8:36 Comment(0)
B
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) );
Barbados answered 18/6, 2018 at 12:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.