将BSTR转换为int

时间:2020-03-06 15:05:16  来源:igfitidea点击:

有谁知道如何将BSTR转换为VC ++ 2008中的int

提前致谢。

解决方案

Google建议使用" VarI4FromStr":

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

BSTR s = SysAllocString(L"42");
int i = _wtoi(s);

尝试_wtoi函数:

int i = _wtoi( mybstr );

我们可以将BSTR安全地传递给任何需要wchar_t *的函数。因此,我们可以使用_wtoi()。

我们应该使用:: VarI4FromStr(...)。

我们应该可以使用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 <>
它适用于可以通过流传递的任何类型,并且类型安全!

这是我用来解析字符串值的一种方法。它类似于Boost的词汇表转换。

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
}

我们应该像其他人指出的那样使用VarI4FromStr。 BSTR不是wchar_t *,因为它们的NULL语义不同(SysStringLen(NULL)是可以的,而wcslen(NULL)不是)。