static SafeLoadLibrary() { try { IntPtr hKernel32 = UnsafeSystemNativeMethods.GetModuleHandleW(KERNEL32); if (hKernel32 != IntPtr.Zero && UnsafeSystemNativeMethods.GetProcAddress(hKernel32, AddDllDirectory) != IntPtr.Zero) { _flags = LOAD_LIBRARY_SEARCH_SYSTEM32; } } catch { /* noop to ensure this class can initialize */ } }
//private SafeLoadLibrary(bool ownsHandle) : base(ownsHandle) { } //internal static readonly SafeLoadLibrary Zero = new SafeLoadLibrary(false); internal unsafe static SafeLoadLibrary LoadLibraryEx(string library) { SafeLoadLibrary result = UnsafeSystemNativeMethods.LoadLibraryExW(library, null, 0); if (result.IsInvalid) { //NOTE: //IsInvalid tests the numeric value of the handle. //SetHandleAsInvalid sets the handle as closed, so that further closing //does not have to take place in the critical finalizer thread. // //You would think that when you assign 0 or -1 to an instance of //SafeHandleZeroOrMinusoneIsInvalid, the handle will not be closed, since after all it is invalid //It turns out that the SafeHandleZetoOrMinusOneIsInvalid overrides only the IsInvalid() method //It does not do anything to automatically close it. //So we have to SetHandleAsInvalid --> Which means mark it closed -- so that //we will not eventually call CloseHandle on 0 or -1 result.SetHandleAsInvalid(); } return(result); }
protected override bool ReleaseHandle() { return(UnsafeSystemNativeMethods.FreeLibrary(handle)); }