Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling errors while using unmanaged code in a managed one ( C++, C, C++/CLI, C#)

I am using a badly written 3rd party (C/C++) Api. I used it from managed code( C++/ CLI). Get sometimes "access violation errors". And this crash whole application. I know i can not handle those errors[ what can i do if a pointer acess to illegal memory location etc].

But I do not want my application crash as a whole. At least if there is a real problem, my application gracefully should say "OK.I can not do my job.BYE. " :-) then it least execute some alternative scenarious and finally close itself.

But there seems to be no way, to catch( may be wrong term, the rigth word may be to be informed about) access violation and similiar errors.Is there a way to be informed about those errors. So i can execute my alternative scenarious.

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;
}
like image 456
Novalis Avatar asked Jul 15 '11 17:07

Novalis


1 Answers

If you're sure that the problems are bugs in the library, and not a result of you passing in bad arguments, then your most robust option is inter-process communication with a hosting process that loads the library. That way your OS process separation keeps the library from bringing down your application.

You can try to catch access violations in-process, using SEH, but if the library writes to wild pointers and not simple null pointers, then the process won't survive even with an exception handler.

Your example will not cause an access violation, it's a buffer overrun of a buffer on the stack, so the adjacent memory location contains some other valid data which gets stomped on.

like image 117
Ben Voigt Avatar answered Oct 28 '22 16:10

Ben Voigt