Cannot catch an exception caused by C dll caused by PInvoke

I am writing a C # .NET 3.5 program that uses the latest MediaInfoLib Dll .
This seems to cause exceptions for some files.

I want to catch these exceptions and ensure that my program continues to work,
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); 

Using:

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

A call to MediaInfo_Open (Handle, FileName) may throw an exception.
Instead of catching the error using the try / catch statement, my program exits and "vshost32-clr2.exe" crashes. (It also crashes as a release build and without a debugger)
After searching the Internet, I found someone who suggested checking "Enable unmanaged code debugging", which only led to the exit of my program without breaking vshost32-clr2.exe.

Any idea how I can catch the exception?

+6
c # exception try-catch pinvoke
source share
2 answers

If an unmanaged DLL causes a crash (instead of just returning some kind of error code), then there is no way to catch it. Once you go beyond the .NET runtime, it is fully consistent with unmanaged code; nothing can be done there by the .NET runtime.

+7
source share

I had a similar problem (especially with BSTR), but hopefully this helps.

There is a fix in .NET (fixed in 4.0) where the internal sorting of strings comes from unmanaged code. Additional Information

The workaround is to change your P / Invoke signature to use IntPtr and sort the strings.

 [DllImport("MediaInfo.dll", EntryPoint = "MediaInfo_Open")] private static extern IntPtr _MediaInfo_Open(IntPtr handle, IntPtr filename); internal static extern IntPtr MediaInfo_Open(IntPtr handle, string filename) { IntPtr stringPtr = Marshal.StringToBSTR(filename); return _MediaInfo_Open(handle, stringPtr); } 
0
source share

All Articles