(2) CString转换成char*

  若将CString类转换成char*(LPSTR)类型,常常使用下列三种方法:

  方法一,使用强制转换。例如:

CString theString( "This is a test" );
LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;


  方法二,使用strcpy。例如:

CString theString( "This is a test" );
LPTSTR lpsz = new TCHAR[theString.GetLength()+1];
_tcscpy(lpsz, theString);


  需要说明的是,strcpy(或可移值Unicode/MBCS的_tcscpy)的第二个参数是 const wchar_t* (Unicode)或const char* (ANSI),系统编译器将会自动对其进行转换。

  方法三,使用CString::GetBuffer。例如:

CString s(_T("This is a test "));
LPTSTR p = s.GetBuffer();
// 在这里添加使用p的代码
if(p != NULL) *p = _T(’’);
s.ReleaseBuffer();
// 使用完后及时释放,以便能使用其它的CString成员函数


  (3) BSTR转换成char*

  方法一,使用ConvertBSTRToString。例如:

#include "comutil.h"
#pragma comment(lib, "comsupp.lib")
int _tmain(int argc, _TCHAR* argv[]){
  BSTR bstrText = ::SysAllocString(L"Test");
  char* lpszText2 = _com_util::ConvertBSTRToString(bstrText);
  SysFreeString(bstrText); // 用完释放
  delete[] lpszText2;
  return 0;
}


  ** 此方法不好,会造成内存泄露,SysFreeString也没有效果。

  方法二,使用_bstr_t的赋值运算符重载。例如:

_bstr_t b = bstrText;
char* lpszText2 = b;


  * 不会有内存泄露,推荐方法