Error handling when using unmanaged code in managed (C ++, C, C ++ / CLI, C #)

I use a poorly written third-party (C / C ++) Api. I used it from managed code (C ++ / CLI). Receive sometimes "access violation errors". And this is the crash of the entire application. I know that I can’t deal with these errors [what can I do if the pointer enters an illegal memory location, etc.).

But I do not want my request to depend on the whole. At least if there is a real problem, my application should gracefully say β€œOK. I can’t do my work .BYE.” :-), then it least performs some alternative scene and finally closes itself.

But there seems to be no way to catch (maybe a wrong term, a harsh word may be reported) about access violation and similar errors. Is there any way to get information about these errors. Therefore, I can complete my alternative scene.

PS: standard exception handling does not solve this.

#include "stdafx.h" #include <iostream> using namespace System; using namespace std; static void ThrowingManagedException() { throw gcnew ArgumentException("For no good reason"); } static void ThrowingNativeException() { throw std::exception("For no good reason"); } static void SomeBadThingsHappen() { short a[1]; a[0]=1; a[2]= 2; // SomeOne make stupid mistake } int main(array<System::String ^> ^args) { Console::WriteLine(L"Test Exceptions"); try { SomeBadThingsHappen(); //ThrowingNativeException(); //ThrowingManagedException(); } catch(Exception^ e) { Console::WriteLine("Something awful happened: "+ e); } Console::WriteLine("Press enter to exit"); Console::Read(); return 0; } 
+6
source share
1 answer

If you are sure that the problems are due to errors in the library, and not because you are passing bad arguments, then your most reliable option is to use interprocess communication with the hosting process that loads the library. Thus, the separation of processes in the OS does not allow the library to delete your application.

You can try to catch access violations in the process using SEH, but if the library writes wild pointers, not simple null pointers, then the process will not be saved even with an exception handler.

Your example will not lead to access violation, this is an overflow of the buffer buffer in the stack, therefore, in the neighboring memory cell there are some other reliable data that fall.

+4
source

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


All Articles