Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't catch exception caused by C dll called via PInvoke

I'm writing a C# .NET 3.5 program wich uses the latest MediaInfoLib Dll.
It seems that it causes an exception for some files.

I want to catch those exceptions and ensure my program continues running,
but for some reason I can't catch it with a simple try/catch statement.

PInvoke Methods:

    [DllImport("MediaInfo.dll")]
    private static extern IntPtr MediaInfo_New();
    [DllImport("MediaInfo.dll")]
    private static extern IntPtr MediaInfo_Open(IntPtr Handle,MarshalAs(UnmanagedType.LPWStr)] string FileName);

Usage:

    Handle = MediaInfo_New();
    try{
        MediaInfo_Open(Handle, FileName)
    } catch { } 

Calling MediaInfo_Open(Handle, FileName) might cause an exception.
Instead of catching the error with the try/catch statement, my program exits and "vshost32-clr2.exe" crashes. (It also crashes as a release build and with no debugger attached)
After searching the web, I found someone who suggested to check "Enable unmanaged code debugging", which only resulted in my program exiting without vshost32-clr2.exe crashing.

Any idea how I can catch the exception?

like image 262
Arokh Avatar asked Feb 13 '11 22:02

Arokh


1 Answers

If the unmanaged DLL is causing the crash (rather than just returning an error code of some kind), then there's no way to catch it. Once you've gone outside of the .NET runtime's control, it's entirely up to the unmanaged code; there's nothing the .NET runtime can do.

like image 54
Adam Robinson Avatar answered Oct 07 '22 06:10

Adam Robinson