Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a throwing C# function from C++ in a C# app such that the C++ stack is unwound properly?

Is it possible to call a throwing C# function from a C++ call in a C# app such that the C++ stack is unwound properly? Is there any documentation of this?

For example, please consider this C# code:

using System;

public class Test
{
    public static void CalledFromCpp()
    {
        throw new Exception("Is this safe? Is C++ stack unwound properly?");
    }

    public static void Main()
    {
        try {
            CppFunc(CalledFromCpp);
        }
        catch(Exception e)
        {
            Console.Writeline("Exception e: {0}", e);
        }
    }

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    delegate void CsFuncToBeCalledFromCpp();

    [DllImport("CppApp", CallingConvention = CallingConvention.Cdecl)]
    private static extern void
    CppFunc(CsFuncToBeCalledFromCpp callback);
}

Along with this C++ code:

void CppFunc(void (*handler))
{
   SomeResourceWrappingClass releasesResourceOnDestruction();
   handler();
}

I tried this out, and the C# exception was caught successfully, but releasesResourceOnDestruction didn't have it's destructor called. This seems to indicate that the C++ stack is not being unwound properly -- is it possible to get it to unwind properly here? Is there any documentation on this behavior?

For context: I want to sometimes trigger a C# exception from C++ code if possible, so that I don't need every call from C# into C++ have to check something afterwards to see if a C# exception needs to be thrown.

like image 520
JDiMatteo Avatar asked Oct 31 '22 17:10

JDiMatteo


1 Answers

Try enabling Structured Exception Handling in your C++ project (Project Properties -> C/C++ -> Code Generation -> Enable C++ Exceptions -> "Yes with SEH Exceptions (/EHa)"). Without SEH exceptions, the exception that is returned to the C++ layer does not have enough information to unwind the stack properly.

like image 161
Velox Avatar answered Nov 15 '22 05:11

Velox