Click to See Complete Forum and Search --> : MFC String: How to convert a 'CString' to a 'char*'?


Gabriel Fleseriu
February 14th, 2003, 03:45 AM
Q: How to convert a 'CString' to a 'char*'?

A: You will need this mostly to pass a 'CString' to a function that expects a 'char*'.


// Prototype of a function expecting a char*
void func(char* c);

CString csMyString = "Hello World";

// now call func()
char* str = csMyString.GetBuffer(csMyString.GetLength());
func(str);

// or directly
func(csMyString.GetBuffer(csMyString.GetLength()));

// if 'func()' modifies the passed char*, you must call
csMyString.ReleaseBuffer(-1);


Note:

'CString::GetBuffer()' will return a 'char*' only in non-UNICODE builds.
<br>
'CString' has an implicit operator to 'LPCTSTR'. In non-UNICODE builds, that is a 'const char*'. Do not use a cast hack like this:


func((char*)((LPCSTR) csMyString)); // BAD!!!!

<br>
Do not call any other 'CString' member function on 'csMyString' between 'GetBuffer()' and 'ReleaseBuffer()'.

<br><br>

Siddhartha
June 23rd, 2006, 04:12 AM
Starting VC++ 7.x, CString can be easily converted to a char* (or equivalent) for all possible build scenarios using conversion class CT2CA.

Like this -
CString csMyString = "Hello World";
CT2CA pszCharacterString (csMyString);

// Use pszCharacterString as a const char* or use it to copy into one...Alternatively, using class CStringA -

CStringA pszCharacterString (csMyString);

// Use pszCharacterString as a char* or use it to copy into one