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

有些话、适合烂在心里 提交于 2019-12-10 13:28:01

问题


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?


回答1:


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.




回答2:


I've had a similar problem (with BSTR specifically) but hopefully this will help.

There is a bug in .NET (fixed in 4.0) when internally marshalling strings back from unmanaged code. More Info

The work-around is to change your P/Invoke signature to use an IntPtr and do the string marshalling yourself.

[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);
}


来源:https://stackoverflow.com/questions/4987470/cant-catch-exception-caused-by-c-dll-called-via-pinvoke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!