Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unload a DLL loaded using DllImport

Tags:

c#

dllimport

How do I unload a DLL which has been loaded using DllImport in C#?

like image 773
subbu Avatar asked Mar 15 '10 06:03

subbu


People also ask

How to unload DLL from memory c#?

A shared DLL loaded in domain neutral manner cannot be unloaded unless the Process is exited. Domain specific DLLs are unloaded alongwith Domain. There is however no way to unload individual DLLs even if the DLL has been loaded for reflection only.

What is the use of DllImport in C#?

DllImport Attribute is a declarative tag used in C# to mark a class method as being defined in an external dynamic-link library (DLL) rather than in any . NET assembly.

How does DllImport work?

It uses two core winapi functions. First is LoadLibrary(), the winapi function that loads a DLL into a process. It uses the name you specified for the DLL. Second is GetProcAddress(), the winapi function that returns the address of a function in a DLL.


1 Answers

The most reliable way to unload an unmanaged DLL from a process that got loaded by a [DllImport] pinvoke declaration is to load it yourself, again, by pinvoking LoadLibrary(). That gives you a reliable handle to the DLL and works correctly even if the module name of the DLL is ambiguous. It doesn't have any affect at runtime, other than the Windows loader increasing the internal reference count on the DLL from 1 to 2.

You can then pinvoke FreeLibrary() twice to decrease the reference count to 0, passing it the IntPtr you got from LoadLibrary(). That unloads the DLL, as well as any dependent DLLs that got loaded.

Beware that you'll get very nasty failure when you try to pinvoke any exported function on the DLL again, any time after doing this. The pinvoke marshaller is unaware that the DLL isn't around anymore and will call the function at the address it thinks is still valid. Which bombs your program with an AccessViolation exception if you are lucky. Or runs a completely random bit of code if you are not so lucky and the address space formerly occupied by the DLL got re-used by another DLL. Anything can happen then, none of it good.

like image 159
Mitch Wheat Avatar answered Sep 21 '22 03:09

Mitch Wheat