How do I convert a CString to a char*

<P>First, be sure you actually need a <CODE>char*</CODE> (non-constant pointer, or
<CODE>LPTSTR</CODE>). If you need a <CODE>const
char*</CODE> (or <CODE>LPCTSTR</CODE>), then
<CODE>CString</CODE> has a conversion function that will be called automatically
if you pass a <CODE>CString</CODE> to a function expecting an
<CODE>LPCTSTR</CODE>. For example:</P><PRE>void f ( LPCTSTR somestring )
  cout << somestring << endl;

CString str = "bonjour";

  f ( str );  // OK - calls CString::operator LPCTSTR() to convert
<P>The remainder of this FAQ deals with obtaining a non-constant pointer to the
<P>Because a <CODE>CString</CODE> object manages the character array, you must
explicitly tell the <CODE>CString</CODE> that you want to get a non-constant
pointer to the string. Call <CODE>GetBuffer()</CODE> to get a <CODE>char*</CODE> to the string, and then call
<CODE>ReleaseBuffer()</CODE> when you no longer need that pointer. Calling
<CODE>ReleaseBuffer()</CODE> tells the <CODE>CString</CODE> that it can resume
managing the character array.</P><PRE>CString str = "some string";
LPTSTR  pch;

  pch = str.GetBuffer(0);

  // use pch here...

  // When you're done using pch, give the CString control
  // of the buffer again.
<P>After calling <CODE>GetBuffer()</CODE>, you may modify the contents of the
string through <CODE>pch</CODE>, although you can't make the string longer since
that would overrun the array. If you do modify the string, you must not call any
<CODE>CString</CODE> methods before the call to <CODE>ReleaseBuffer()</CODE>,
since <CODE>CString</CODE> methods may reallocate and move the array, which
would render <CODE>pch</CODE> invalid. After you call
<CODE>ReleaseBuffer()</CODE>, you must not use <CODE>pch</CODE> any more, again
because the <CODE>CString</CODE> may reallocate and move the character
<P>If you want to create a larger buffer for the string, for example if you are
going to pass it to an API that returns a filename, you can do so by passing the
desired length to <CODE>GetBuffer()</CODE>:</P><PRE>CString sFilename;
LPTSTR  pch;

  // Get a non-const pointer and set the buffer size.
  pch = sFilename.GetBuffer ( MAX_PATH );

  // Pass the buffer to an API that writes to it.
  GetModuleFileName ( NULL, pch, MAX_PATH );

  // Return control of the array to the CString object.

posted on 2006-10-18 22:41  cy163  阅读(...)  评论(...编辑  收藏