代码之家  ›  专栏  ›  技术社区  ›  Mr. Boy

在unicode和非unicode环境中转换TCHAR*->std::wstring

  •  0
  • Mr. Boy  · 技术社区  · 14 年前

    #define

    1 回复  |  直到 14 年前
        1
  •  3
  •   sbi    14 年前

    假设 TCHAR 扩展到 wchar_t 在Unicode版本中:

    inline std::wstring convert2widestr(const wchar_t* const psz)
    {
      return psz;
    }
    inline std::wstring convert2widestr(const char* const psz)
    {
      std::size_t len = std::strlen(psz);
      if( psz.empty() ) return std::wstring();
      std::vector<wchar_t> result;
      const int len = WideCharToMultiByte( CP_ACP
                                         , 0
                                         , reinterpret_cast<LPCWSTR>(psz)
                                         , static_cast<int>(len)
                                         , NULL
                                         , 0
                                         , NULL
                                         , NULL
                                         );
    
      result.resize( len );
      if(result.empty()) return std::wstring();
      const int cbytes = WideCharToMultiByte( CP_ACP
                                            , 0
                                            , reinterpret_cast<LPCWSTR>(psz)
                                            , static_cast<int>(len)
                                            , reinterpret_cast<LPSTR>(&result[0])
                                            , static_cast<int>(result.size())
                                            , NULL
                                            , NULL
                                            );
      assert(cbytes);
      return std::wstring( result.begin(), result.begin() + cbytes );
    }
    

    像这样使用:

    void f(const TCHAR* psz)
    {
       std::wstring str = convert(psz);
       // ...
    }