/// <summary> /// Try to load a native library by providing the full path including the file name of the library. /// </summary> /// <returns>True if the library was successfully loaded or if it has already been loaded.</returns> static bool TryLoadFile(string directory, string relativePath, string fileName) { lock (StaticLock) { if (NativeHandles.Value.TryGetValue(fileName, out IntPtr libraryHandle)) { return(true); } var fullPath = Path.GetFullPath(Path.Combine(Path.Combine(directory, relativePath), fileName)); if (!File.Exists(fullPath)) { // If the library isn't found within an architecture specific folder then return false // to allow normal P/Invoke searching behavior when the library is called return(false); } #if NET5_0_OR_GREATER try { if (!NativeLibrary.TryLoad(fullPath, out libraryHandle) || libraryHandle == IntPtr.Zero) { return(false); } } catch { return(false); } NativeHandles.Value[fileName] = libraryHandle; return(true); #else try { // If successful this will return a handle to the library libraryHandle = IsWindows ? WindowsLoader.LoadLibrary(fullPath) : IsMac?MacLoader.LoadLibrary(fullPath) : LinuxLoader.LoadLibrary(fullPath); } catch (Exception e) { LastException = e; return(false); } if (libraryHandle == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); var exception = new System.ComponentModel.Win32Exception(lastError); LastException = exception; return(false); } LastException = null; NativeHandles.Value[fileName] = libraryHandle; return(true); #endif } }
/// <summary> /// Try to load a native library by only the file name of the library. /// </summary> /// <returns>True if the library was successfully loaded or if it has already been loaded.</returns> static bool TryLoadDirect(string fileName) { lock (StaticLock) { if (NativeHandles.Value.TryGetValue(fileName, out IntPtr libraryHandle)) { return(true); } #if NET5_0_OR_GREATER try { if (!NativeLibrary.TryLoad(fileName, out libraryHandle) || libraryHandle == IntPtr.Zero) { return(false); } } catch { return(false); } NativeHandles.Value[fileName] = libraryHandle; return(true); #else try { // If successful this will return a handle to the library libraryHandle = IsWindows ? WindowsLoader.LoadLibrary(fileName) : IsMac?MacLoader.LoadLibrary(fileName) : LinuxLoader.LoadLibrary(fileName); } catch (Exception e) { LastException = e; return(false); } if (libraryHandle == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); var exception = new System.ComponentModel.Win32Exception(lastError); LastException = exception; return(false); } LastException = null; NativeHandles.Value[fileName] = libraryHandle; return(true); #endif } }