How to call the C # metalization function from C ++ in a C # application, so that the C ++ stacks unwind correctly?

Is it possible to call the C # metalization function from a C ++ call in a C # application to hide the C ++ stacks? Are there any documents about this?

For example, 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 and the C # exception was successful, but releaseResourceOnDestruction did not call its destructor. This seems to indicate that the C ++ stacks are not unwinding properly - is it possible to be convenient here? Is there any documentation on this behavior?

In context: I want, if possible, to sometimes trigger a C # exception from C ++ code, so I donโ€™t need every C # call in C ++ to have to check something to see if an exception needs to be raised FROM#.

+5
source share
1 answer

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, an exception that returns to the C ++ level does not have enough information to properly promote it.

+2
source

Source: https://habr.com/ru/post/1202188/


All Articles