MFC String: How to convert a 'CString' to a 'char*'?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 2 of 2

Thread: MFC String: How to convert a 'CString' to a 'char*'?

Threaded View

  1. #1
    Join Date
    Jun 2001

    Strings: How to convert a CString to a char*?

    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());
    // or directly
    // if 'func()' modifies the passed char*, you must call
    • 'CString::GetBuffer()' will return a 'char*' only in non-UNICODE builds.

    • '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!!!!
    • Do not call any other 'CString' member function on 'csMyString' between 'GetBuffer()' and 'ReleaseBuffer()'.

    Last edited by Andreas Masur; July 24th, 2005 at 12:54 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

This a survey!

On-Demand Webinars (sponsored)