Catch DllNotFoundException from P/Invoke

1.5k Views Asked by At

Found post with a solution: How do I handle a failed DllImport?

I'm writing an app that checks the OS version to do different things depending on whether the host is using a Vista-series or NT-series version of Windows. If Vista-series, it loads some DLLs (using DllImport), but doesn't use these otherwise. The problem is, using DllImport to load them will cause a DllNotFoundException at runtime if used on older versions of Windows that don't have those DLLs.

How can I catch / prevent / ignore the DllNotFoundExceptions? Trying to set the exception to "Handled" in my unhandled exception event does not allow the app to continue.

2

There are 2 best solutions below

0
On BEST ANSWER

I think you should be able to go the "traditional" way with the win32 LoadLibrary/GetProcAddress/FreeLibrary and a delegate (just as you do it with callback functions).

http://msdn.microsoft.com/en-us/library/d186xcf0.aspx might be a starting point...

This should get you started:

[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr LoadLibrary(string lpFileName);

[DllImport("kernel32.dll", SetLastError=true)]
static extern bool FreeLibrary(IntPtr hModule);

[DllImport("kernel32.dll", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

Then you declare a delegate with the correct signature of the export to be called, and use Marshal.GetDelegateForFunctionPointer() to create it from a function pointer you got back from GetProcAddress.

0
On

As an option you could write some sort of decorator component in C++/CLI which would forward all calls to windows dlls using LoadLibrary or static linking and handle manually any absences of those dlls.