Skip to content

Instantly share code, notes, and snippets.

@gregseth
Last active December 14, 2015 00:59
Show Gist options
  • Save gregseth/5003080 to your computer and use it in GitHub Desktop.
Save gregseth/5003080 to your computer and use it in GitHub Desktop.
Allows a managed .NET class to unload an unmanaged DLL.
public class LibUnloader, IDisposable
{
[DllImport("kernel32.dll")]
private static extern bool FreeLibrary(IntPtr _HModule);
[DllImport("kernel32.dll")]
private static extern bool LoadLibraryA(string _HModule);
[DllImport("kernel32.dll")]
private static extern bool GetModuleHandleExA(UInt32 _Flags, string _ModuleName, ref IntPtr _HModule);
private string ModuleName;
private string LibName;
LibUnloader(string _ModuleName)
{
ModuleName = _ModuleName;
LibName = ModuleName+ ".dll";
LoadLibraryA(LibName);
}
void Dispose()
{
IntPtr hMod = IntPtr.Zero;
if (GetModuleHandleExA(0, ModuleName, ref hMod))
{
while (FreeLibrary(hMod));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment