C++的wchar_t和string的互转

163 人参与 | 时间:2020年01月22日 09:53:56
//wchar_t转string
std::string a031::Wchar_tToString(wchar_t *wchar)
{
    std::string szDst;
    wchar_t * wText = wchar;
    DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, NULL, 0, NULL, FALSE);// WideCharToMultiByte的运用
    char *psText; // psText为char*的临时数组,作为赋值给std::string的中间变量
    psText = new char[dwNum];
    WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, psText, dwNum, NULL, FALSE);// WideCharToMultiByte的再次运用
    szDst = psText;// std::string赋值
    delete[]psText;// psText的清除
    return szDst;
}
wchar_t * StringToWchar_t1(const std::string & str)
{
    wchar_t * m_chatroommmsg = new wchar_t[str.size() * 2];  //
    memset(m_chatroommmsg, 0, str.size() * 2);
    setlocale(LC_ALL, "zh_CN.UTF-8");
    swprintf(m_chatroommmsg, str.size() * 2, L"%S", str.c_str());

    return m_chatroommmsg;
}
.