Search code examples
visual-c++comcom-interopdirectshownew-operator

Is there a clean way of handling bad_alloc exceptions thrown inside C++ COM objects?


I'm working on various C++ COM DirectShow filters called from C# clients via COM interop. There's little use of C++ exceptions in the code. The main exception is operator new which can throw bad_alloc exceptions.

Is there a clean way of handling bad_alloc exceptions in a way which can be caught by the C# client?

Could a new handler throw some an SEH exception that could be caught by COM interop clients?

Or would it be better to link with the backwardly-compatible non-throwing version of new in Visual Studio libraries and check every allocation?

One tedious alternative is to write a try/catch for hundreds of COM entry points which doesn't seem worthwhile since bad_alloc exceptions are rarely recoverable.

The DirectShow base classes generally check for null returns from operator new as they seem to have been written for earlier versions of Visual C++ that didn't throw bad_alloc exceptions.


Solution

  • The COM API contract requires that you not allow ANY C++ exceptions to flow across the COM API boundry.

    That means you need to catch all C++ exceptions and turn them into HRESULTs before they leave your COM API.

    You might be able to get away with this in some rare circumstances (if, for instance you can guarantee that the COM client and COM server were built with the same version ofthe compiler), but there are a myriad of circumstances that can mess this up (for instance the COM server lives behind a proxy/stub (which can happen if you have multiple apartments or if the server is out-of-proc), or if the COM server is being called from another language like one of the CLR languages).

    In general, something like:

     catch (...)
     { 
         return E_FAIL;
     }
    

    at the end of each of your COM APIs will go a long way to improve the robustness of your code.