4

Does any one know how can I convert a BSTR to an int in VC++ 2008

Thanks in advance.

Jordan Parmer
  • 36,042
  • 30
  • 97
  • 119
Alonso
  • 1,069
  • 5
  • 12
  • 22

8 Answers8

12

You can pass a BSTR safely to any function expecting a wchar_t *. So you can use _wtoi().

Community
  • 1
  • 1
moonshadow
  • 86,889
  • 7
  • 82
  • 122
7

Google suggests VarI4FromStr:

HRESULT VarI4FromStr(
  _In_   LPCOLESTR strIn,
  _In_   LCID lcid,
  _In_   ULONG dwFlags,
  _Out_  LONG *plOut
);
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Scott Hanselman
  • 17,712
  • 6
  • 74
  • 89
4

Try the _wtoi function:

int i = _wtoi( mybstr );
Charlie
  • 44,214
  • 4
  • 43
  • 69
2

You should use ::VarI4FromStr(...).

Jordan Parmer
  • 36,042
  • 30
  • 97
  • 119
1
BSTR s = SysAllocString(L"42");
int i = _wtoi(s);
dalle
  • 18,057
  • 5
  • 57
  • 81
1

You should be able to use 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;
}

The cool thing is that lexical_cast<>
It will work for any types that can be passed through a stream and its type safe!

Martin York
  • 257,169
  • 86
  • 333
  • 562
1

This is a method I use to parse values out of strings. It's similar to 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
}
luke
  • 36,103
  • 8
  • 58
  • 81
0

You should use VarI4FromStr like others pointed out. BSTR is not wchar_t* because of differences in their NULL semantics (SysStringLen(NULL) is ok, but wcslen(NULL) is not).

Constantin
  • 27,478
  • 10
  • 60
  • 79