visual c++ - C# code not catching SEHExceptions -
i have c# application invokes managed c++ dll deliberately accesses invalid address; enabled seh exceptions
in c++ project, added _se_translator_function
c++ code , added signal handler when sigsegv
occurs. using c++ code purely native test, works perfectly, when invoke c++ code .net app, app crashes a:
unhandled exception: system.accessviolationexception: attempted read or write protected memory. indication other memory corrupt.
@ k.killnative() in c:\users\ebascon\documents\visual studio 2013\projects\consoleapplication3\consoleapplication4\source.cpp:line 32
this c# console app:
namespace consoleapplication3 { class program { static void main(string[] args) { try { var k = new nativekiller(); k.kill(); } catch (exception ex) { console.writeline("catching " + ex); } } } }
and c++/cli code invoked:
void mxxexceptiontranslator(unsigned int, struct _exception_pointers*) { throw std::exception("crash happens"); } void killnative() { try { _set_se_translator(mxxexceptiontranslator); signal(sigsegv, [](int) { puts("exception"); exit(-1); }); int* p = reinterpret_cast<int*>(0xdeadbeef); printf("%d\n", *p); } catch (...) { //removing catch not change puts("doing nothing"); } } public ref class nativekiller { public: void kill() { killnative(); } };
what think doing wrong? in real world problem, need c++/cli process (that bridge legacy app) log error message , die gracefully instead of popping "the program stopped working" window.
thanks in advance,
ernesto
this kind of problem have, helps discover not building code correctly. c++/cli compiler pretty powerful, too powerful, , can translate native code il. exact same kind of il c# compiler generates. , treated same @ runtime, jitter translates machine code @ runtime.
this not want. native c or c++ code ought translated directly machine code compiler. msdn article _set_se_translator() decent job of warning this:
when using _set_se_translator managed code (code compiled /clr) or mixed native , managed code, aware translator affects exceptions generated in native code only. managed exceptions generated in managed code (such when raising system::exception) not routed through translator function.
the usual way fall in pit of success compiling native code separately in own source file or library project. easier take advantage of c++/cli compiler's ability dynamically switch back-and-forth between il , machine code generation in single source file. fix:
#pragma managed(push, off) void mxxexceptiontranslator(unsigned int, struct _exception_pointers*) { ... } void killnative() { ... } #pragma managed(pop) public ref class nativekiller { ... }
and you'll see exception translator works fine.
Comments
Post a Comment