A2W和W2A :很好的多字节和宽字节字符串的转换宏

  以前看《Window核心编程》,感觉多字节和宽字节之间还比较麻烦的,至少MultiByteToWideChar函数和WideCharToMultiByte函数有足够多的参数的意义让我们去理解。近日接触了ATL的一个很好的字符串的转换宏:A2W和W2A。

 用法很简单,A2W的用法:

    

           #include <atlconv.h>
       DoSomething(LPWSTR str);  //  函数声明

       USES_CONVERSION;
       DoSomething(A2W("SomeString"));

 

       W2A的用法:

    #include <atlconv.h>
    DoSomething(LPCSTR str); //  函数声明

     USES_CONVERSION;
    DoSomething(W2A(L"SomeString"));

          

另外使用这两个宏时最好把它们单独放入一个函数实现,具体原因见:

谨慎使用A2W等字符转换宏

这儿一篇详细介绍这两个宏的原理的文章:VC中一个关于宏的使用问题

 

转Unicode中文乱码??

/*
*函数名称:ConvertToUnicode(CString &strOut, const char* strUtf8)
*函数介绍:将指定字符串由UTF-8转换为GBK
*输入参数:待转换的UTF-8字符串
*输出参数:CString
*返回值  :无
*/
void ConvertToUnicode(CString &strOut, const char* strUtf8)
{
    //char* strTemp = new char[strlen(strUtf8)+1];
    //strcpy(strTemp, strUtf8);

    int len = MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, NULL, 0);
    unsigned short * wszGBK = new unsigned short[len];
    memset(wszGBK, 0, len * 2);
    MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, (LPWSTR)wszGBK, len);

    len = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wszGBK, -1, NULL, 0, NULL, NULL);
    char *szGBK = new char[len];
    memset(szGBK, 0, len);
    WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wszGBK, -1, szGBK, len, NULL, NULL);

    strOut = szGBK;
    delete[] szGBK;
    delete[] wszGBK;

    return;
}

 

posted on 2015-10-15 11:47  JUDE008  阅读(433)  评论(0)    收藏  举报

导航