qxn
qxn

Reputation: 17584

Implications of throwing exception in delegate of unmanaged callback

What are the implications or unperceived consequences of throwing an exception inside of a delegate that is used during an unmanaged callback? Here is my situation:

Unmanaged C:

int return_callback_val(int (*callback)(void))
{
  return callback();
}

Managed C#:

[DllImport("MyDll.dll")]
static extern int return_callback_val(IntPtr callback);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int CallbackDelegate();

int Callback()
{
  throw new Exception();
}

void Main()
{
  CallbackDelegate delegate = new CallbackDelegate(Callback);
  IntPtr callback = Marshal.GetFunctionPointerForDelegate(delegate);
  int returnedVal = return_callback_val(callback);
}

Upvotes: 6

Views: 724

Answers (2)

Hans Passant
Hans Passant

Reputation: 941605

The native code will bomb on the unhandled exception and the program terminates.

If you actually want to handle that exception then you need to use the custom __try/__catch keywords in the native code. Which is pretty useless, all the details of the managed exception are lost. The only distinguishing characteristic is the exception code, 0xe0434f4d. Since you cannot know exactly what went wrong, you cannot reliably restore the program state either. Better not catch it. Or better not throw it.

Upvotes: 7

Pavel Donchev
Pavel Donchev

Reputation: 1899

I think the correct way to say to a COM Object you have an exception is simply to return HRESULT.E_FAIL.

Could not test it right now, but I think that if the COM Object is in another process, all you will do is to kill your process and the COM Object may become unresponsive, waiting for your code to return from the callback function (since your process is dead already).

Upvotes: 0

Related Questions