使用CString成员函数GetBuffer():
CString::GetBuffer LPTSTR GetBuffer( int nMinBufLength ); throw( CMemoryException ); 返回值:一个指向对象的(以空字符结尾的)字符缓冲区的LPTSTR指针。 参数: nMinBufLength 字符缓冲区的以字符数表示的最小容量。这个值不包括一个结尾的空字符的空间。 说明: 此成员函数返回一个指向CString对象的内部字符缓冲区的指针。返回的LPTSTR不是const,因此可以允许直接修改CString的内容。 如果你使用由GetBuffer返回的指针来改变字符串的内容,你必须在使用其它的CString成员函数之前调用ReleaseBuffer函数。 在调用ReleaseBuffer之后,由GetBuffer返回的地址也许就无效了,因为其它的CString操作可能会导致CString缓冲区被重新分配。如果你没有改变此CString的长度,则缓冲区不会被重新分配。 当此CString对象被销毁时,其缓冲区内存将被自动释放。 注意,如果你自己知道字符串的长度,则你不应该添加结尾的空字符。但是,当你用ReleaseBuffer来释放该缓冲区时,你必须指定最后的字符串长度。如果你添加了结尾的空字符,你应该给ReleaseBuffer的长度参数传递-1,ReleaseBuffer将对该缓冲区执行strlen来确定它的长度。 示例:下面的例子说明了如何用CString::GetBuffer。 // CString::GetBuffer例子 CString s( "abcd" ); #ifdef _DEBUG afxDump << "CString s" << s << "\n"; #endif LPTSTR p = s.GetBuffer( 10 ); strcpy( p, "Hello" ); // 直接访问CString对象。 s.ReleaseBuffer( ); #ifdef _DEBUG afxDump << "CString s " << s << "\n"; #endif举例:BOOL CIfasFileCreateDlg::CreateISFile(CString strIndFilePath, CString strDatFilePath) { char* pIndFilePath = NULL; char* pDatFilePath = NULL; DWORD dwCreateIsFileRet = -1;
//transform CString to char pIndFilePath = strIndFilePath.GetBuffer(strIndFilePath.GetLength()); pDatFilePath = strDatFilePath.GetBuffer(strDatFilePath.GetLength());
}