Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions sources/LLVMSharp/Interop.Extensions/LLVM.ResolveLibrary.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// 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.

using System;
using System.Reflection;
using System.Runtime.InteropServices;

namespace LLVMSharp.Interop
{
public static unsafe partial class LLVM
{
public static event DllImportResolver ResolveLibrary;

static LLVM()
{
NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), OnDllImport);
}

private static IntPtr OnDllImport(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
IntPtr nativeLibrary;

if (TryResolveLibrary(libraryName, assembly, searchPath, out nativeLibrary))
{
return nativeLibrary;
}

if (libraryName.Equals("libLLVM") && TryResolveLLVM(assembly, searchPath, out nativeLibrary))
{
return nativeLibrary;
}

return IntPtr.Zero;
}

private static bool TryResolveLLVM(Assembly assembly, DllImportSearchPath? searchPath, out IntPtr nativeLibrary)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && NativeLibrary.TryLoad("libLLVM-10.so", assembly, searchPath, out nativeLibrary))
{
return true;
}

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && NativeLibrary.TryLoad("LLVM-C.dll", assembly, searchPath, out nativeLibrary))
{
return true;
}

if (NativeLibrary.TryLoad("libLLVM", assembly, searchPath, out nativeLibrary))
{
return true;
}

return false;
}

private static bool TryResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, out IntPtr nativeLibrary)
{
var resolveLibrary = ResolveLibrary;

if (resolveLibrary != null)
{
var resolvers = resolveLibrary.GetInvocationList();

foreach (DllImportResolver resolver in resolvers)
{
nativeLibrary = resolver(libraryName, assembly, searchPath);

if (nativeLibrary != IntPtr.Zero)
{
return true;
}
}
}

nativeLibrary = IntPtr.Zero;
return false;
}
}
}
4 changes: 4 additions & 0 deletions sources/LLVMSharp/LLVMSharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
</PropertyGroup>

<ItemGroup>
<Compile Remove="Interop.Extensions/LLVM.ResolveLibrary.cs" Condition="'$(TargetFramework)' == 'netstandard2.0'" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="libLLVM" />
<PackageReference Include="System.Memory" />
Expand Down