diff --git a/sources/ClangSharp.Interop/clang.cs b/sources/ClangSharp.Interop/clang.cs index 037ab5b1..c36ba1f4 100644 --- a/sources/ClangSharp.Interop/clang.cs +++ b/sources/ClangSharp.Interop/clang.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information. using System; +using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; @@ -29,7 +30,17 @@ private static IntPtr OnDllImport(string libraryName, Assembly assembly, DllImpo return nativeLibrary; } - if (libraryName.Equals("libclang", StringComparison.Ordinal) && TryResolveClang(assembly, searchPath, out nativeLibrary)) + // When invoked as a dotnet tool (ClangSharpPInvokeGenerator), native libraries + // are co-located with the executable in the NuGet cache but aren't found + // by the default resolver on Unix (default dlopen only searches system paths + // and LD_LIBRARY_PATH), so we explicitly try the application base directory. + // NativeLibrary.TryLoad with an absolute path does not apply platform-specific + // name mangling (lib prefix, .so/.dylib/.dll suffix), so we add it explicitly. + var suffix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".dll" + : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? ".dylib" + : ".so"; + + if (NativeLibrary.TryLoad(Path.Combine(AppContext.BaseDirectory, libraryName + suffix), out nativeLibrary)) { return nativeLibrary; } @@ -37,19 +48,6 @@ private static IntPtr OnDllImport(string libraryName, Assembly assembly, DllImpo return IntPtr.Zero; } - private static bool TryResolveClang(Assembly assembly, DllImportSearchPath? searchPath, out IntPtr nativeLibrary) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return NativeLibrary.TryLoad("libclang.so.20", assembly, searchPath, out nativeLibrary) - || NativeLibrary.TryLoad("libclang-20", assembly, searchPath, out nativeLibrary) - || NativeLibrary.TryLoad("libclang.so.1", assembly, searchPath, out nativeLibrary); - } - - nativeLibrary = IntPtr.Zero; - return false; - } - private static bool TryResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, out IntPtr nativeLibrary) { var resolveLibrary = ResolveLibrary;