Skip to content

Instantly share code, notes, and snippets.

@am11
Last active December 30, 2021 13:08
Show Gist options
  • Save am11/e53442f76f3d0f751dde818d446fc424 to your computer and use it in GitHub Desktop.
Save am11/e53442f76f3d0f751dde818d446fc424 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
public class YourLibrary
{
private static bool? s_isAmazon;
// static constructor
static YourLibrary () =>
NativeLibrary.SetDllImportResolver(typeof(YourLibrary).Assembly, MyNativeLibraryLoaderForLibFoo);
private static IntPtr MyNativeLibraryLoaderForLibFoo (string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
if (!OperatingSystem.IsLinux() || libraryName != "libFoo.so")
return IntPtr.Zero; // continue with default runtime native library loader
if (s_isAmazon == null)
{
s_isAmazon = RuntimeInformation.OSDescription.Contains("amazon", StringComparison.OrdinalIgnoreCase);
if (s_isAmazon == false)
{
// check release files as well
string filename = File.Exists("/etc/os-release") ? "/etc/os-release" : File.Exists("/etc/release") ? "/etc/release" : null;
if (filename is not null)
{
try
{
s_isAmazon = File.ReadAllText(filename).Contains("amazon", StringComparison.OrdinalIgnoreCase);
}
catch (IOException)
{
// ignore
}
}
}
}
if (s_isAmazon == true)
{
NativeLibrary.TryLoad("libFoo_amazon.so", out IntPtr lib);
return lib;
}
// other distros?
return IntPtr.Zero;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment