Skip to content

Commit

Permalink
app-win: implement dll-import resolver
Browse files Browse the repository at this point in the history
Like the previous commit but for the windows loader.

This is generally not required on Windows, but might help with
fuse-x/studio#20.
  • Loading branch information
mortend committed Sep 9, 2023
1 parent 73170e6 commit 6832e00
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion src/runtime/win/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

Expand Down Expand Up @@ -29,12 +32,55 @@ static Program()
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

AppDomain.CurrentDomain.AssemblyLoad += (sender, ev) => {
try
{
if (!UsesUnoPInvoke(ev.LoadedAssembly))
return;

// Set DllImportResolver for loading native libraries in assemblies generated by Uno
NativeLibrary.SetDllImportResolver(ev.LoadedAssembly, (libraryName, assembly, searchPath) => {
if (!libraryName.Contains(".dll") || libraryName.StartsWith("/"))
return IntPtr.Zero;

var dir = Path.GetDirectoryName(assembly.Location);
var lib = Path.Combine(dir, libraryName);

if (File.Exists(lib))
return LoadLibrary(lib);

Console.Error.WriteLine("Native library not found: " + lib);
return IntPtr.Zero;
});
}
catch (Exception e)
{
Console.Error.WriteLine("NativeLibrary.SetDllImportResolver: " + e);
}
};
}

static bool UsesUnoPInvoke(Assembly asm)
{
foreach (var attr in asm.GetCustomAttributes())
{
var metadata = attr as AssemblyMetadataAttribute;

if (metadata?.Key == "Uno.PInvoke")
return bool.Parse(metadata.Value);
}

return false;
}

static void UnoGenerated()
{
// Uno compiler will replace this.
// Uno compiler will replace this function
new DummyApp();
}

[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string filename);
}
}

0 comments on commit 6832e00

Please sign in to comment.