在开发MFC应用程序的过程中,经常需要将几种不同类型的数据进行转换,为了提高开发效率,在此,将自己在开发过程中使用过的类型转换方法,整理成一篇博客,方便以后进行查找及使用。
本博客主要涉及CString类型与其他类型之间的相互转化,其中包括:CString 转 string,string 转 CString,CString 转 int,int 转 CString,CString 转 char*,char* 转 CString,CString 转 BSTR,BSTR 转 CString,CString 转 LPSTR,LPSTR 转 CString,CString 转 wstring,wstring 转 CString, CString 转 CComVariant(VARIANT *),CComVariant(VARIANT *) 转 CString;下面介绍在VC 2010,多字节字符集(在某些转化下,多字节字符集与unicode字符集有区别)环境下,以上类型相互转换的方法:
1. CString 与 string 之间的转化:
1.1 CString 转 string
CString csStr = "hello";
std::string sStr;
sStr = csStr.GetBuffer(0);
csStr.ReleaseBuffer(); // 使用完后,及时释放
1.2 string 转 CString
CString csStr;
std::string sStr = "hello";
csStr = sStr.c_str();
2. CString 与 int 之间的转化:
2.1 CString 转 int
CString csStr = "123";
int iNum;
iNum = _ttoi(csStr);
2.2 int 转 CString
int iNum = 123;
CString csStr;
csStr.format(_T("%d"), iNum);
3. CString 与 char*之间的转化:
3.1 CString 转 char*
CString csStr = "hello";
char *pStr = (LPSTR)(LPCTSTR)csStr;
3.2 char* 转 CString
char * pStr = "hello";
CString csStr;
csStr.format(_T("%s"), pStr);
4. CString 与 BSTR 之间的转化:
4.1 CString 转 BSTR
CString csStr = “hello”;
BSTR bstrStr;
bstrStr = csStr.AllocSysString();
...... // bstrStr的使用
SysFreeString(bstrStr); // 使用AllocSysString后,一定要记得释放
4.2 BSTR 转 CString
BSTR bstrStr = ::SysAllocString(L"hello");
CStringA csStrA(bstrStr);
CString csStr;
csStr = csStrA;
5. CString 与 LPSTR 之间的转化:
5.1 CString 转 LPSTR
CString csStr = "hello";
LPSTR lpstrStr;
lpstrStr = csStr.GetBuffer();
csStr.ReleaseBuffer(); // 使用完后,及时释放
5.2 LPSTR 转 CString
LPSTR lpstrStr = _T("hello");
CString csStr(lpstrStr);
6. CString 与 wstring 之间的转化:
6.1 CString 转 wstring
CString csStr = "hello";
std::wstring wsStr;
wsStr = csStr.AllocSysString();
6.2 wstring 转 CString
std::wstring wsStr = L"hello";
CString csStr(wsStr.c_str());
7. CString 与 CComVariant 之间的转化:
7.1 CString 转 CComVariant
CString csStr = "hello";
std::wstring wsStr;
wsStr = csStr.AllocSysString();
CComVariant vStr( SysAllocString( wsStr.c_str() ) );
7.2 CComVariant 转 CString
暂时还未遇到该类型的转换,未完待续……
8. CString 与 LPARAM之间的转化:
8.1 CString 转 LPARAM
CString csStr = "hello";
LPARAM lStr((LPARAM)(LPCTSTR)csStr);
8.2 LPARAM 转 CString
暂时还未遇到该类型的转换,未完待续…… 在后续的学习和工作过程中,遇到其他的类型转化,都会及时更新到该博客中与大家分享,也欢迎大家在博客下方评论区分享与交流。