C#C
C#7mo ago
Exanite

✅ Is throwing and catching an exception in an UnmanagedCallersOnly method valid?

I'm getting a crash under some very specific conditions:
  1. Must be on Linux (Windows is fine)
  2. Must have the debugger attached (not attaching the debugger is fine). The VS Code and Rider debuggers both crash.
  3. The program must be built in Debug configuration (Release is fine)
  4. The exception must be thrown from a callback function marked with UnmanagedCallersOnly.
I'm also using .NET 9.

The process just crashes without printing any error messages... or at least it appears to. The process actually stays open and must be killed manually.

I'm planning to write up a Github issue for this, but I want to double check to make sure that this is valid and that I'm submitting the issue to the right place.
Can someone make sure that the code below is valid and point me to which .NET/C# repo I should submit an issue to?

From my understanding, exceptions are fine as long as all of the exceptions are caught before exiting back to native code.
The following reproduction code is the least amount of code I've tested that reproduces the issue.

Reproduction code:
// I'm using Stdcall here, but it doesn't seem to matter which calling convention is used
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
public static void Callback()
{
    Console.WriteLine("Hello from Callback()!");

    try
    {
        Console.WriteLine("Throwing the exception in Callback()!");
        throw new Exception("Exception in Callback()");
    }
    catch
    {
        Console.WriteLine("Caught the exception in Callback()!");
    }
}

public static unsafe void Main()
{
    Console.WriteLine("Starting program!");

    delegate* unmanaged[Stdcall]<void> callback = &Callback;
    callback();

    Console.WriteLine("Ending program!");
}
Was this page helpful?