3

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.

Community
  • 1
  • 1
Scorpion
  • 784
  • 7
  • 25
  • Is the exception being thrown at the call-site or when the program loads (but before you actually try to call those functions)? – Lasse V. Karlsen Nov 06 '09 at 10:29
  • Catching exceptions is suboptimal, as one should avoid having exceptions being part of the normal application flow. In your case, on a specific platform, each call would first throw an exception, which I'd avoid if possible. – Lucero Nov 06 '09 at 10:52

2 Answers2

2

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.

Lucero
  • 59,176
  • 9
  • 122
  • 152
1

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.

Vitaliy Liptchinsky
  • 5,221
  • 2
  • 18
  • 25