Find the system Vulkan loader on macOS and Linux

macOS loaded VulkanEx, which links libvulkan.1.dylib through an rpath of
/usr/local/lib and so only works with the LunarG SDK installed there. Try
the loader directly first (the default search path, Homebrew and
/usr/local), then VulkanEx as before.

Linux loaded "vulkan", i.e. libvulkan.so, which only ships in -dev
packages. Try libvulkan.so.1 first.

Signed-off-by: Capsup <capsup@live.dk>
This commit is contained in:
Capsup 2026-10-20 09:39:45 +02:00
commit 411f18c290

View file

@ -16,19 +16,7 @@ public partial class Vulkan
static Vulkan()
{
// Load the correct Vulkan library for the platform
if (OperatingSystem.IsWindows())
Dll = NativeLibrary.Load("vulkan-1", typeof(Vulkan).Assembly, DllImportSearchPath.System32);
// TODO: This is a hack which only works if SDK is installed, we need to package the Vulkan binary on macOS
if (OperatingSystem.IsMacOS())
Dll = NativeLibrary.Load("VulkanEx", typeof(Vulkan).Assembly, DllImportSearchPath.LegacyBehavior);
if (OperatingSystem.IsLinux())
Dll = NativeLibrary.Load("vulkan", typeof(Vulkan).Assembly, DllImportSearchPath.LegacyBehavior);
if (Dll == nint.Zero)
throw new NullReferenceException("Failed to load Vulkan library");
Dll = LoadVulkanLibrary();
// Assign the native library to the assembly resolver
NativeLibrary.SetDllImportResolver(
@ -47,4 +35,25 @@ public partial class Vulkan
throw new NullReferenceException("Failed to load vkGetInstanceProcAddr from Vulkan library");
}
}
private static nint LoadVulkanLibrary()
{
if (OperatingSystem.IsWindows())
return NativeLibrary.Load("vulkan-1", typeof(Vulkan).Assembly, DllImportSearchPath.System32);
// Prefer the system Vulkan loader, falling back to the old names
string[] candidates = OperatingSystem.IsMacOS()
? ["libvulkan.1.dylib", "/opt/homebrew/lib/libvulkan.1.dylib", "/usr/local/lib/libvulkan.1.dylib", "VulkanEx"]
: OperatingSystem.IsLinux()
? ["libvulkan.so.1", "vulkan"]
: [];
foreach (var candidate in candidates)
{
if (NativeLibrary.TryLoad(candidate, typeof(Vulkan).Assembly, DllImportSearchPath.LegacyBehavior, out var dll))
return dll;
}
throw new DllNotFoundException($"Failed to load Vulkan library, tried: {string.Join(", ", candidates)}");
}
}