代码之家  ›  专栏  ›  技术社区  ›  Toran Billups

如何在C++中转换STD::String到LPCWSTR(Unicode)

  •  99
  • Toran Billups  · 技术社区  · 17 年前

    我正在寻找一个方法,或者将std::string转换为lpcwstr的代码段。

    5 回复  |  直到 7 年前
        1
  •  112
  •   Toran Billups    17 年前

    感谢您链接到msdn文章。这正是我要找的。

    std::wstring s2ws(const std::string& s)
    {
        int len;
        int slength = (int)s.length() + 1;
        len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
        wchar_t* buf = new wchar_t[len];
        MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
        std::wstring r(buf);
        delete[] buf;
        return r;
    }
    
    std::wstring stemp = s2ws(myString);
    LPCWSTR result = stemp.c_str();
    
        2
  •  94
  •   James EJ    13 年前

    解决方案实际上比任何其他建议都简单得多:

    std::wstring stemp = std::wstring(s.begin(), s.end());
    LPCWSTR sw = stemp.c_str();
    

    最重要的是,它是独立于平台的。H2H:)

        3
  •  8
  •   17 of 26    17 年前

    如果您在ATL/MFC环境中,则可以使用ATL转换宏:

    #include <atlbase.h>
    #include <atlconv.h>
    
    . . .
    
    string myStr("My string");
    CA2W unicodeStr(myStr);
    

    然后可以使用unicodestr作为lpcwstr。unicode字符串的内存在堆栈上创建并释放,然后执行unicodestr的析构函数。

        4
  •  -1
  •   Ed Swangren    17 年前

    您可以使用std::wstring而不是std::string。

    编辑:对不起,这不是更解释性的,但我必须运行。

    使用std::wstring::c_str()。

        5
  •  -2
  •   Milind Morey    7 年前
    string  myMessage="helloworld";
    int len;
    int slength = (int)myMessage.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, buf, len);
    std::wstring r(buf);
     std::wstring stemp = r.C_str();
    LPCWSTR result = stemp.c_str();