【问题标题】:Convert TCHAR * -> std::wstring in both unicode and non-unicode environments在 unicode 和非 unicode 环境中转换 TCHAR * -> std::wstring
【发布时间】:2011-03-22 04:52:28
【问题描述】:

我在一个库中有一些代码必须在内部使用 wstring,这一切都很好。但它是使用 TCHAR 字符串参数调用的,来自 unicode 和非 unicode 项目,我无法为这两种情况找到一个简洁的转换。

我看到了一些 ATL 转换等但看不到正确的方法,没有使用 #define 定义多个代码路径

【问题讨论】:

    标签: c++ visual-c++ unicode atl


    【解决方案1】:

    假设 TCHAR 在 Unicode 构建中扩展为 wchar_t

    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);
       // ...
    }
    

    【讨论】:

    • eeeeeeeeeeeeeeew!虽然,很好地使用重载来避免#define
    • CP_UTF8 在旧版 Windows 程序中非常不太可能。请改用 CP_ACP。或者只使用 mbstowcs()。
    • @John:我不确定你想告诉我什么。无论如何,重载的优点是这两个版本都可用于 Unicode 和非 Unicode 程序。
    • @sbi:看起来代码很多。我以前见过这种类型的东西,但希望能有一些对我有用的东西。
    • @John:事实上WideCharToMultiByte() 是为你做的。但它是一个 C API 函数,并且由于 C 无法处理资源,调用它很痛苦。但是,如果这看起来太复杂,您可以随时使用我的答案的第一个版本。 :)
    猜你喜欢
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2013-03-10
    • 2017-01-02
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多