Search code examples
c++stringexceptioncombstr

Invalid null pointer when using _bstr_t


I have a COM DLL that I am developing and I am running into a few issues. I have a try catch around a block of code and in the catch I get a _bstr_t from the exception. What I wanted to do was catch that exception and print it out to a string, however, it is throwing an Invalid null pointer error at me when that exception gets thrown. I tried looking at the MSDN on how to check for a null pointer, but it doesn't seem like it is working. I can't really debug the error because this is on a client machine and when trying to output the information I get this error.

catch(const _com_error& ex)
{
    ::OutputDebugStringW(ex.Description());

    _variant_t ret;
    std::string str = "#N/A ExcelException: ";
    _bstr_t desc = ex.Description();

    if(!desc || desc.GetBSTR() == L"")
    {
        str += ConvertBSTRToMBS(desc);
    }

    ret.SetString(str.c_str());
    *Result = ret.Detach();
}

std::string ConvertBSTRToMBS(_bstr_t bstr) 
{
    std::string converted((char *)bstr);
    return converted;
} 

Solution

  • Due to a mistake in if condition, ConvertBSTRToMBS is called only when bstr is null. Correct it as follows

    if(!!desc && desc.length() != 0)
    {
        str += ConvertBSTRToMBS(desc);
    }
    

    The strange !!desc expression means !(desc.operator!()). _bstr_t::operator! returns true if BSTR is null, therefore you have to negate it to check for non-null.