|
| 1 | +// Copyright (c) Microsoft and Contributors. All rights reserved. Licensed under the University of Illinois/NCSA Open Source License. See LICENSE.txt in the project root for license information. |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Reflection; |
| 5 | +using System.Runtime.InteropServices; |
| 6 | + |
| 7 | +namespace LLVMSharp.Interop |
| 8 | +{ |
| 9 | + public static unsafe partial class LLVM |
| 10 | + { |
| 11 | + public static event DllImportResolver ResolveLibrary; |
| 12 | + |
| 13 | + static LLVM() |
| 14 | + { |
| 15 | + NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), OnDllImport); |
| 16 | + } |
| 17 | + |
| 18 | + private static IntPtr OnDllImport(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) |
| 19 | + { |
| 20 | + IntPtr nativeLibrary; |
| 21 | + |
| 22 | + if (TryResolveLibrary(libraryName, assembly, searchPath, out nativeLibrary)) |
| 23 | + { |
| 24 | + return nativeLibrary; |
| 25 | + } |
| 26 | + |
| 27 | + if (libraryName.Equals("libLLVM") && TryResolveLLVM(assembly, searchPath, out nativeLibrary)) |
| 28 | + { |
| 29 | + return nativeLibrary; |
| 30 | + } |
| 31 | + |
| 32 | + return IntPtr.Zero; |
| 33 | + } |
| 34 | + |
| 35 | + private static bool TryResolveLLVM(Assembly assembly, DllImportSearchPath? searchPath, out IntPtr nativeLibrary) |
| 36 | + { |
| 37 | + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && NativeLibrary.TryLoad("libLLVM-10.so", assembly, searchPath, out nativeLibrary)) |
| 38 | + { |
| 39 | + return true; |
| 40 | + } |
| 41 | + |
| 42 | + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && NativeLibrary.TryLoad("LLVM-C.dll", assembly, searchPath, out nativeLibrary)) |
| 43 | + { |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + if (NativeLibrary.TryLoad("libLLVM", assembly, searchPath, out nativeLibrary)) |
| 48 | + { |
| 49 | + return true; |
| 50 | + } |
| 51 | + |
| 52 | + return false; |
| 53 | + } |
| 54 | + |
| 55 | + private static bool TryResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, out IntPtr nativeLibrary) |
| 56 | + { |
| 57 | + var resolveLibrary = ResolveLibrary; |
| 58 | + |
| 59 | + if (resolveLibrary != null) |
| 60 | + { |
| 61 | + var resolvers = resolveLibrary.GetInvocationList(); |
| 62 | + |
| 63 | + foreach (DllImportResolver resolver in resolvers) |
| 64 | + { |
| 65 | + nativeLibrary = resolver(libraryName, assembly, searchPath); |
| 66 | + |
| 67 | + if (nativeLibrary != IntPtr.Zero) |
| 68 | + { |
| 69 | + return true; |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + nativeLibrary = IntPtr.Zero; |
| 75 | + return false; |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments