问题
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