I've got a CLR hosting application, designed in unmanaged C++. I wish to sign up for AppDomain.UnhandledException event from unmanaged C++ code.

The imported AppDomain interface has got the following method:

HRESULT add_UnhandledException (struct _UnhandledExceptionEventHandler *value)

Where UnhandledExceptionEventHandler understood to be:

struct __declspec(uuid("84199e64-439c-3011-b249-3c9065735adb"))

_UnhandledExceptionEventHandler : IDispatch 

I don't learn how to make use of this handler for connecting it my callback function. So, now you ask , using it?

I've not seen anybody doing the work, however it might enable you to think about the following:

  1. a handled delagate is not a "simple" callback within the c++ sence, it gets in the clr-object, code i've observed in c++ connecting occasions was always handled c++.
  2. following the unhandled exception handler is triggered what goes on next is dependent about the clr policy configurations (see 3.)
    1. either the operation is ended (default)
    2. the appdomain unloaded
    3. or even the clr disabled
    4. swallow the exception (behavior of clr insinternet 1.x)
  3. you are able to alter the default action to two.2, 2.3, 2.4 with the IHostPolicyManager
  4. let us say you place a policy to unload or disable, you should use IActionOnCLREvent to create a callback on unloaded/disabled.
  5. with 3) and 4) you are able to setup the body
    1. to cleanup/log/save (no matter what you'll need) in handled code inside your UnhandledExceptionHandler
    2. you receive informed from the unload of the appdomain in unmanaged code ... and do no matter what you'll still have to do.
  6. presuming this isn't enough (your unmanaged code must know some particulars from the exception) you can define com connects (see idl sample below) your handled application implements IMyApplication as well as your unmanaged code IMyApplicationSink whenever you setup your appdomain you pass within the unmanaged implementation IMypplicationSink (your hook), the handled application needs to call that hook within the handled unhandledexception eventhandler:

    interface IMyApplicationSink : IUnknown
    interface IMyApplicationControl : IUnknown

    Note: for particulars regarding how to obtain the custom com interface see "Implement IHostControl::SetAppDomainManager" of "Designing the Microsoft .Internet Framework Common Language Runtime" (presently parts free readable here)

  7. if you're not in charge from the handled application, load first a credit card applicatoin that is inside your control - the default appdomain - the unhandled exception handler is going to be known as there too (see msdn)

  8. should you set a policy to swallow (2.4) your unmanaged code will not be informed the clr could keep going - you can obviously mix this using the custom com interface (6.)