'How to compare two BSTRs or CComBSTRs?

What is the right way to compare two CComBSTRs? I tried to use

 bool operator ==(
     const CComBSTR& bstrSrc 
 ) const throw( );

However it always return false even two ComBSTRs are the same. It did not work correctly.

Do I have to convert CComBSTRs to ANSI string first and then use strcmp?

Thanks!

-bc



Solution 1:[1]

You should probably use VarBstrCmp.

EDIT: this is actually what CComBSTR::operator== does, so without further context, your code may be incorrect.

Solution 2:[2]

BSTRs (and therefore CComBSTRs) are usually Unicode strings. You can use wcscmp() (or wcsicmp() for case-insensitive comparison).

Beware that encapsulated BSTR can be null which is a legal representation for an empty string and this should be treated as a special case, otherwise your program might run into undefined behaviour (most likely just crash).

Solution 3:[3]

To properly compare BSTR values which may contain embedded null characters you need to use something like this:

bool EqualBSTR(const BSTR String1, const BSTR String2, bool IgnoreCase = false)
{
    if (String1 == nullptr || String2 == nullptr) {
        return false;
    }

    const size_t MaxCount = std::min(static_cast<size_t>(SysStringLen(String1)), static_cast<size_t>(SysStringLen(String2)));

    if (IgnoreCase) {
        return _wcsnicmp(String1, String2, MaxCount) == 0;
    } else {
        return wcsncmp(String1, String2, MaxCount) == 0;
    }
}

Solution 4:[4]

BSTRsAreEqual(BSTR bstr1, BSTR bstr2, VARIANT_BOOL* boolptrEqual)
{
   CString s1, s2;
   s1 = bstr1;
   s2 = bstr2; 
   if (s1 == s2) { 
      *boolptrEqual = true;   
   } else { 
      *boolptrEqual = false;    
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MSN
Solution 2 sharptooth
Solution 3 Igor Levicki
Solution 4 Carl Olen