无法捕获由PInvoke调用的C dll引起的exception

我正在编写一个使用最新MediaInfoLib Dll的C#.NET 3.5程序。
它似乎导致某些文件的exception。

我想捕获这些exception并确保我的程序继续运行,
但由于某种原因,我无法通过简单的try / catch语句来捕获它。

PInvoke方法:

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

用法:

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

调用MediaInfo_Open(Handle,FileName)可能会导致exception。
我的程序退出并且“vshost32-clr2.exe”崩溃,而不是使用try / catch语句捕获错误。 (它也作为发布版本崩溃,没有附加调试器)
在搜索网络后,我发现有人建议检查“启用非托管代码调试”,这只导致我的程序退出而没有vshost32-clr2.exe崩溃。

知道我怎么能抓住exception吗?

如果非托管DLL导致崩溃(而不仅仅是返回某种错误代码),那么就无法捕获它。 一旦你超出.NET运行时的控制范围,它完全取决于非托管代码; .NET运行时无法做到。

我遇到了类似的问题(特别是BSTR),但希望这会有所帮助。

当从非托管代码内部编组字符串时,.NET中存在一个错误(在4.0中修复)。 更多信息

解决方法是更改​​P / Invoke签名以使用IntPtr并自己进行字符串编组。

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