1

How to do the transform bstr_t to double in c++?

I was thinking to convert to *char, then *char to double?

edgarmtze
  • 24,683
  • 80
  • 235
  • 386
  • What is a `bstr_t`? Post code and/or decode the type into C++ primitive types. – Kerrek SB Jul 15 '11 at 00:23
  • 1
    It's an RAII wrapper class for a COM `BSTR` (which is a pointer to wide char with special semantics, basically) – Steve Townsend Jul 15 '11 at 00:28
  • @Kerrek SB: It's a Windows-specific [C++ reference counting wrapper](http://msdn.microsoft.com/en-us/library/zthfhkd6.aspx) for the Windows-specific [`BSTR` type](http://msdn.microsoft.com/en-us/library/1b2d7d2c-47af-4389-a6b6-b01b7e915228(VS.85)), which stands for "basic string". It's essentially a doubly-null-terminated Unicode string that has a 4-byte length prefix. – In silico Jul 15 '11 at 00:30
  • It is _bstr_t. Cast to const wchar_t* to avoid it doing all this unnecessary work. Then wcstod(). – Hans Passant Jul 15 '11 at 00:33

3 Answers3

4

If you have a char* or wchar_t* string, use the strtod/wcstod functions to read a double.

E.g. using @Steve's suggestion:

_bstr_t x;
double q = wcstod(x, NULL); // implicit conversion!
double p = strtod(x, NULL); // same

Apparently _bstr_t has implicit conversion operators both to const char * and const wchar_t*, so you can use them directly in the float parsing functions.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Note that the conversion to char * invokes [ConvertBSTRToString](http://msdn.microsoft.com/en-us/library/ewezf1f6(v=VS.100).aspx) which allocates memory so it is relatively expensive (although the result is cached). Conversion to wchar_t* is inexpensive since BSTR is basically a wide char anyway. – Frank Boyne Jul 15 '11 at 01:02
  • Frank: Good to know. So prefer the `wcstod` version :-) – Kerrek SB Jul 15 '11 at 01:05
2

You can cast to const char* (there is a converter for this that handles mapping from wide char to MBCS under the covers) and then convert to double as you wish - stringstream::operator>> for example

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
2

Call wcstod or _wcstod_l if you want to control locale.

bstr_t myBstr_t = L"1.234";

double d = wcstod(myBstr_t, NULL);
Frank Boyne
  • 4,400
  • 23
  • 30