【问题标题】:Convert BSTR to int将 BSTR 转换为 int
【发布时间】:2010-09-15 03:28:15
【问题描述】:

有人知道如何在 VC++ 2008 中将 BSTR 转换为 int

提前致谢。

【问题讨论】:

    标签: c++ winapi


    【解决方案1】:

    您可以 pass a BSTR safely 到任何期望 wchar_t * 的函数。所以你可以使用_wtoi()。

    【讨论】:

    • 不能,NULL 是有效的 BSTR 值。
    【解决方案2】:

    谷歌建议VarI4FromStr

    HRESULT VarI4FromStr(
      _In_   LPCOLESTR strIn,
      _In_   LCID lcid,
      _In_   ULONG dwFlags,
      _Out_  LONG *plOut
    );
    

    【讨论】:

      【解决方案3】:

      试试_wtoi函数:

      int i = _wtoi( mybstr );
      

      【讨论】:

        【解决方案4】:

        您应该使用 ::VarI4FromStr(...)。

        【讨论】:

          【解决方案5】:
          BSTR s = SysAllocString(L"42");
          int i = _wtoi(s);
          

          【讨论】:

            【解决方案6】:

            这是我用来从字符串中解析值的方法。类似于Boost's lexical cast

            std::wistringstream iss(mybstr);   // Should convert from bstr to wchar_t* for the constructor
            iss >> myint;                      // Puts the converted string value in to myint
            if(iss.bad() || iss.fail())
            {
               // conversion failed
            }
            

            【讨论】:

              【解决方案7】:

              你应该可以使用 boost::lexical_cast

              #include <boost/lexical_cast.hpp>
              #include <iostream>
              
              int main()
              {
                  wchar_t     plop[]  = L"123";
                  int value   = boost::lexical_cast<int>(plop);
              
                  std::cout << value << std::endl;
              }
              

              很酷的是 lexical_cast
              它适用于任何可以通过流传递的类型及其类型安全

              【讨论】:

                【解决方案8】:

                您应该像其他人指出的那样使用VarI4FromStrBSTR 不是wchar_t*,因为它们的NULL semantics 存在差异(SysStringLen(NULL) 可以,但wcslen(NULL) 不行)。

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2011-04-08
                  • 2013-05-12
                  • 1970-01-01
                  • 2013-05-24
                  • 2023-03-14
                  • 1970-01-01
                  • 2010-10-11
                  • 1970-01-01
                  相关资源
                  最近更新 更多