protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // free managed resources } if (_loadedModuleHandle != IntPtr.Zero) { if (_loadedFromMemory) { this.MemoryFreeLibrary(_loadedModuleHandle); } else { WinBase.FreeLibrary(_loadedModuleHandle); } _loadedModuleHandle = IntPtr.Zero; } _disposed = true; } }
/// <summary> /// Deattach from the process and do a cleanup. /// </summary> /// <param name="hModule">Pointer to a memory module.</param> private void MemoryFreeLibrary(IntPtr hModule) { if (hModule == IntPtr.Zero) { return; } MEMORY_MODULE *memory_module = (MEMORY_MODULE *)hModule; if (memory_module != null) { if (memory_module->initialized != 0) { this.CallDllEntryPoint(memory_module, WinNT.DLL_PROCESS_DETACH); } if (memory_module->modules != null) { // free previously opened libraries for (int index = 0; index < memory_module->numModules; index++) { if (memory_module->modules[index] != IntPtr.Zero) { WinBase.FreeLibrary(memory_module->modules[index]); } } Marshal.FreeHGlobal((IntPtr)memory_module->modules); } if ((IntPtr)memory_module->codeBase != IntPtr.Zero) { // release memory of library WinBase.VirtualFree((IntPtr)memory_module->codeBase, 0, WinNT.MEM_RELEASE); } Marshal.FreeHGlobal((IntPtr)memory_module); } }