https://www.cnblogs.com/Hisin/archive/2012/05/01/2478092.html
在做MFC编程的时候,时常会碰到CString、CStringA、CStringW之间相互转换的问题,也即chat字符串与wchar_t字符串相互转换的问题。
现本人写了一个它们之间相互转换的函数,代码如下:
头文件CStringToolEx.h
#ifndef _CSTRING_TOOL_EX_
#define _CSTRING_TOOL_EX_
#include <cstringt.h>
//
// CString转CStringA
//
#ifndef CStrT2CStrA
#ifdef _UNICODE
#define CStrT2CStrA(cstr) CStrW2CStrA((cstr))
#else
#define CStrT2CStrA(cstr) (cstr)
#endif
#endif
//
// CString转CStringW
//
#ifndef CStrT2CStrW
#ifdef _UNICODE
#define CStrT2CStrW(cstr) (cstr)
#else
#define CStrT2CStrW(cstr) CStrA2CStrW((cstr))
#endif
#endif
//
// CStringA转CString
//
#ifndef CStrA2CStrT
#ifdef _UNICODE
#define CStrA2CStrT(cstr) CStrA2CStrW((cstr))
#else
#define CStrA2CStrT(cstr) (cstr)
#endif
#endif
//
// CStringW转CString
//
#ifndef CStrW2CStrT
#ifdef _UNICODE
#define CStrW2CStrT(cstr) (cstr)
#else
#define CStrW2CStrT(cstr) CStrW2CStrA((cstr))
#endif
#endif
//
// CStringA转CStringW
//
CStringW CStrA2CStrW(const CStringA &cstrSrcA);
//
// CStringW转CStringA
//
CStringA CStrW2CStrA(const CStringW &cstrSrcW);
#endif
源文件CStringToolEx.cpp
#include "stdafx.h"
#include "CStringToolEx.h"
#include <cstringt.h>
//
// CStringA转CStringW
//
CStringW CStrA2CStrW(const CStringA &cstrSrcA)
{
int len = MultiByteToWideChar(CP_ACP, 0, LPCSTR(cstrSrcA), -1, NULL, 0);
wchar_t *wstr = new wchar_t[len];
memset(wstr, 0, len*sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, LPCSTR(cstrSrcA), -1, wstr, len);
CStringW cstrDestW = wstr;
delete[] wstr;
return cstrDestW;
}
//
// CStringW转CStringA
//
CStringA CStrW2CStrA(const CStringW &cstrSrcW)
{
int len = WideCharToMultiByte(CP_ACP, 0, LPCWSTR(cstrSrcW), -1, NULL, 0, NULL, NULL);
char *str = new char[len];
memset(str, 0, len);
WideCharToMultiByte(CP_ACP, 0, LPCWSTR(cstrSrcW), -1, str, len, NULL, NULL);
CStringA cstrDestA = str;
delete[] str;
return cstrDestA;
}