What is better to do from the very beginning, check whether the module is loaded into the memory of the process, or try to load it, catch the error via GetLastError , check its value, and if the library is already loaded, call GetModuleHandle , or do the opposite?
Those. something like this, but not only check for IntPtr.Zero but also check LastError for a match with the error code ( I don’t know the number of the error code, therefore there is no such verification )?
Although if the module was loaded, then LoadLibrary returns it to Handle and does not throw an error, which is strange.
internal static class WinApi { internal static bool FreeLibrary(IntPtr moduleHandle) { return FreeLibraryEx(moduleHandle); } internal static TDelegateType GetProcDelegate<TDelegateType>(IntPtr moduleHandle, string procName) where TDelegateType : Delegate { return Marshal.GetDelegateForFunctionPointer<TDelegateType>(GetProcAddressEx(moduleHandle, procName)); } internal static SafeLibrary LoadLibrary(string modulePath) { IntPtr result = LoadLibraryEx(modulePath); if (result == IntPtr.Zero && (result = GetModuleHandleEx(Path.GetFileName(modulePath))) == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return result; } #region Private native Methods [DllImport(Libraries.Kernel32, SetLastError = true, EntryPoint = "LoadLibrary", CallingConvention = CallingConvention.Winapi)] private static extern IntPtr LoadLibraryEx(string modulePath); [DllImport(Libraries.Kernel32, CallingConvention = CallingConvention.Winapi, EntryPoint = "FreeLibrary", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool FreeLibraryEx(IntPtr moduleHandle); [DllImport(Libraries.Kernel32, CallingConvention = CallingConvention.Winapi, EntryPoint = "GetProcAddress", CharSet = CharSet.Ansi, SetLastError = true)] private static extern IntPtr GetProcAddressEx(IntPtr moduleHandle, string procedureName); [DllImport(Libraries.Kernel32, CallingConvention = CallingConvention.Winapi, SetLastError = true, EntryPoint = "GetModuleHandle")] private static extern IntPtr GetModuleHandleEx(string moduleName); #endregion }