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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With