Is this code not going to produce an error:
_bstr_t text=n.GetText();
atof((char*)text)
Where text is a double value.
I know that the _bstr_t
produces a const char*
in the conversion; so I'm not sure if the atof()
is going to work?
Is this code not going to produce an error:
_bstr_t text=n.GetText();
atof((char*)text)
Where text is a double value.
I know that the _bstr_t
produces a const char*
in the conversion; so I'm not sure if the atof()
is going to work?
First of all, _bstr_t
has operator char*() const
, so you don't need a cast. Then, this operator calls ConvertBSTRToString() which returns a heap-allocated char array you need to delete[]
later (see the example in the linked article), failing to do so will result in a memory leak. Finally, you should be aware that _bstr_t
can encapsulate a null pointer which corresponds to an empty string and your program should handle such situations.
It seems to me it is absolutely safe to use _wtof(text)
(see http://msdn.microsoft.com/en-us/library/hc25t012.aspx) to make the conversion which you need.
@sharptooth: In general BSTR
data must not be always zero-terminated string. But corresponds to description of the _bstr_t
class (see http://msdn.microsoft.com/en-us/library/zthfhkd6.aspx):
A _bstr_t object encapsulates the BSTR data type. The class manages resource allocation and deallocation through function calls to SysAllocString and SysFreeString and other BSTR APIs when appropriate.
Only data allocated with SysAlloc-functions other as SysAllocString
can be not zero-terminated. The function SysAllocString
allocate always additional two bytes and fill there with L'\0'. To read more information about this subject I refer to http://blogs.msdn.com/b/ericlippert/archive/2003/09/12/52976.aspx.