简体   繁体   中英

Convert BSTR to int

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

Thanks in advance.

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

Google suggests VarI4FromStr :

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

尝试_wtoi函数:

int i = _wtoi( mybstr );

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

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 !

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
}
BSTR s = SysAllocString(L"42");
int i = _wtoi(s);

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM