1.采用类方式
class a2w
{
wchar_t* buffer;
public:
explicit a2w(const char* str):buffer(0)
{
if(str) {
size_t nu = strlen(str);
size_t n = ::MultiByteToWideChar(CP_ACP,0,(const char *)str,int(nu),NULL,0);
buffer = new wchar_t[n+1];
::MultiByteToWideChar(CP_ACP,0,(const char *)str,int(nu),buffer,int(n));
}
}
~a2w() { delete[] buffer; }
operator const wchar_t*() { return buffer; }
};
备注:
explicit:用来修饰类的构造函数,表明该构造函数是显式的。主要防止这种类构造时被编译器自动转换操作。
2.采用函数模式
/*
wBuf 为申明指针即可。
*/
chr2wch(const char* buffer, wchar_t* wBuf)
{
size_t len = strlen(buffer);
size_t wlen = MultiByteToWideChar(CP_ACP, 0, (const char*)buffer, int(len), NULL, 0);
wBuf = new wchar_t[wlen + 1];
MultiByteToWideChar(CP_ACP, 0, (const_char*)buffer, int(len), wBuf, int(wlen));
}
//--------------------------------
随机文章:
LPWSTR ConvertLPCSTRToLPWSTR (char* pCstring)
{
LPWSTR pszOut = NULL;
if (pCstring != NULL)
{
int nInputStrLen = strlen (pCstring);
// Double NULL Termination
int nOutputStrLen = MultiByteToWideChar(CP_ACP, 0, pCstring, nInputStrLen, NULL, 0) + 2;
pszOut = new WCHAR [nOutputStrLen];
if (pszOut)
{
memset (pszOut, 0x00, sizeof (WCHAR)*nOutputStrLen);
MultiByteToWideChar (CP_ACP, 0, pCstring, nInputStrLen, pszOut, nInputStrLen);
}
}
return pszOut;
}
After using this method do remember to delete the allocated string.
eg:
char * str = new char[strlen("ASHOK") + 1];
strcpy(str, "ASHOK");
WCHAR * pwStr = ConvertLPCSTRToLPWSTR(str);
//Use this pwStr
......
.....
//delete the wide char pointer.
delete []pwStr;
//--------------------------
wstring MultCHarToWideChar(string str)
{
//获取缓冲区的大小,并申请空间,缓冲区大小是按字符计算的
int len=MultiByteToWideChar(CP_ACP,0,str.c_str(),str.size(),NULL,0);
TCHAR *buffer=new TCHAR[len+1];
//多字节编码转换成宽字节编码
MultiByteToWideChar(CP_ACP,0,str.c_str(),str.size(),buffer,len);
buffer[len]='/0';//添加字符串结尾
//删除缓冲区并返回值
wstring return_value;
return_value.append(buffer);
delete []buffer;
return return_value;
}
string WideCharToMultiChar(wstring str)
{
string return_value;
//获取缓冲区的大小,并申请空间,缓冲区大小是按字节计算的
int len=WideCharToMultiByte(CP_ACP,0,str.c_str(),str.size(),NULL,0,NULL,NULL);
char *buffer=new char[len+1];
WideCharToMultiByte(CP_ACP,0,str.c_str(),str.size(),buffer,len,NULL,NULL);
buffer[len]='/0';
//删除缓冲区并返回值
return_value.append(buffer);
delete []buffer;
return return_value;
}