CString与char之间的转换

来源:互联网 发布:日本人的气质 知乎 编辑:程序博客网 时间:2024/06/02 07:07
1、多字符集设置下:
CString To char*:
1)、
CString str; 
char *buf = str.GetBuffer();
2)、
CString str;
char *buf = (LPSTR)(LPCSTR)str;


char* To CString
1)、
char *buf;
CString str(buf);


2、Unicode字符集下:
CString To char*:
1)、
CString st =_T("123");  
int len =WideCharToMultiByte(CP_ACP,0,str,-1,NULL,0,NULL,NULL);  
char *buf =new char[len +1];  
WideCharToMultiByte(CP_ACP,0,str,-1,buf,len,NULL,NULL );  
  
//...  
delete[] buf;


char* To CString
1)、
char *buf;
CString str(buf);


3、方法:
static std::string Unicode2ANSI(LPCWSTR lpszSrc)
{
std::string sResult;
if (lpszSrc != NULL)
{
int  nANSILen = WideCharToMultiByte(CP_ACP, 0, lpszSrc, -1, NULL, 0, NULL, NULL);
char* pANSI = new char[nANSILen + 1];
if (pANSI != NULL)
{
ZeroMemory(pANSI, nANSILen + 1);
WideCharToMultiByte(CP_ACP, 0, lpszSrc, -1, pANSI, nANSILen, NULL, NULL);
sResult = pANSI;
delete[] pANSI;
}
}
return sResult;
}


static std::wstring ANSI2Unicode(LPCSTR lpszSrc)
{
std::wstring sResult;
if (lpszSrc != NULL)
{
int nUnicodeLen = MultiByteToWideChar(CP_ACP, 0, lpszSrc, -1, NULL, 0);
LPWSTR pUnicode = new WCHAR[nUnicodeLen + 1];
if (pUnicode != NULL)
{
ZeroMemory((void*)pUnicode, (nUnicodeLen + 1) * sizeof(WCHAR));
MultiByteToWideChar(CP_ACP, 0, lpszSrc,-1, pUnicode, nUnicodeLen);
sResult = pUnicode;
delete[] pUnicode;
}
}
return sResult;
}
原创粉丝点击