Skip to content

Commit

Permalink
Ok
Browse files Browse the repository at this point in the history
  • Loading branch information
Sandro Hanea committed Feb 17, 2025
1 parent 535bd75 commit c059c3a
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,6 @@ public IEnumerable<string> GetDependencies(string nativeLibPath)
{
yield return stringEntry.Value;
}
else
{
var type = entry.GetType();
var genericArgs = type.GetGenericArguments();
throw new Exception($"The dynamic entry was not of type string but {type.Name} with {genericArgs?.FirstOrDefault()?.Name}");
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,12 @@ public IEnumerable<LoadLibResult> TryLoad(string nativeLibraryPath)
if (!NativeLibrary.TryLoad(fullPath, out var handle))
{
var pinvokeError = Marshal.GetLastPInvokeErrorMessage();
var checkIfAlreadyLoaded = NativeLibraryChecker.IsLibraryLoaded(Path.GetFileName(fullPath));
yield return new LoadLibResult()
{
LibraryName = libName,
LibraryPath = fullPath,
LoadError = $"Couldn't load the native library on this system. PInvoke: {pinvokeError}",
LoadError = $"Couldn't load the native library on this system. PInvoke: {pinvokeError}. Different version loaded: {checkIfAlreadyLoaded}",
WasLoaded = false
};
continue;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
namespace WhisperNetDependencyChecker.DependencyWalker;

using System;
using System.Runtime.InteropServices;

public static class NativeLibraryChecker
{
// Windows API (GetModuleHandle)
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);

// Linux/macOS API (dlopen with RTLD_NOLOAD)
private const int RTLD_NOLOAD = 0x4; // Flag to check if the library is already loaded

[DllImport("libdl.so.2", EntryPoint = "dlopen", SetLastError = true)]
private static extern IntPtr dlopen_linux(string filename, int flags);

[DllImport("libSystem.dylib", EntryPoint = "dlopen", SetLastError = true)]
private static extern IntPtr dlopen_macos(string filename, int flags);

public static IntPtr GetLibraryHandle(string libraryName)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return GetModuleHandle(libraryName);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return dlopen_linux(libraryName, RTLD_NOLOAD);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return dlopen_macos(libraryName, RTLD_NOLOAD);
}
else
{
throw new PlatformNotSupportedException("Unsupported operating system.");
}
}

public static bool IsLibraryLoaded(string libraryName)
{
return GetLibraryHandle(libraryName) != IntPtr.Zero;
}
}

0 comments on commit c059c3a

Please sign in to comment.