Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an extension point to override native libraries loading #1922

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
36 changes: 34 additions & 2 deletions binding/Binding.Shared/LibraryLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,31 @@ namespace SkiaSharp
#endif
{
#if USE_DELEGATES || USE_LIBRARY_LOADER
public static class LibraryLoaderSettings
{
private static bool _isFrozen;
private static Func<string, IntPtr> _loadLibraryOverride;

/// <summary>
/// Gets or sets the function to override the default native library loading behavior.
/// The func gets the name of the native library to be loaded as a parameter, returns the OS handle for the loaded native library.
/// Can be set only on initialization stage before the first library is loaded, otherwise an exception will be thrown.
/// </summary>
public static Func<string, IntPtr> LoadLibraryOverride
{
get => _loadLibraryOverride;
set
{
if (_isFrozen)
throw new Exception ("After any native library is loaded, the load method cannot be changed.");

_loadLibraryOverride = value;
}
}

internal static void Freeze () => _isFrozen = true;
}

internal static class LibraryLoader
{
static LibraryLoader ()
Expand All @@ -33,9 +58,16 @@ static LibraryLoader ()

public static IntPtr LoadLocalLibrary<T> (string libraryName)
{
var libraryPath = GetLibraryPath (libraryName);
LibraryLoaderSettings.Freeze ();

IntPtr handle;
if (LibraryLoaderSettings.LoadLibraryOverride != null)
handle = LibraryLoaderSettings.LoadLibraryOverride (libraryName);
else {
var libraryPath = GetLibraryPath (libraryName);
handle = LoadLibrary (libraryPath);
}

var handle = LoadLibrary (libraryPath);
if (handle == IntPtr.Zero)
throw new DllNotFoundException ($"Unable to load library '{libraryName}'.");

Expand Down