feat: Added cross-platform .NET scripts support (#1185)

This PR intends to add support for .NET scripts that can extend ImHex's
functionality in a portable and cross-platform way.

---------

Co-authored-by: Justus Garbe <55301990+Nowilltolife@users.noreply.github.com>
This commit is contained in:
Nik
2023-07-15 14:29:14 +02:00
committed by GitHub
parent 4e3b8111fd
commit 5171bea0bf
36 changed files with 1219 additions and 34 deletions

View File

@@ -0,0 +1,6 @@
.vs/
bin/
obj/
*.dll
*.pdb
*.json

View File

@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>AssemblyLoader</AssemblyName>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<SelfContained>true</SelfContained>
</PropertyGroup>
<PropertyGroup>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,70 @@
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
namespace ImHex
{
public class EntryPoint
{
public static int ExecuteScript(IntPtr arg, int argLength)
{
try
{
return ExecuteScript(Marshal.PtrToStringUTF8(arg, argLength)) ? 0 : 1;
}
catch (Exception e)
{
Console.WriteLine("[.NET Script] Exception in AssemblyLoader: " + e.Message);
return 1;
}
}
private static bool ExecuteScript(string path)
{
AssemblyLoadContext? context = new("ScriptDomain_" + Path.GetFileNameWithoutExtension(path), true);
try
{
var assembly = context.LoadFromStream(new MemoryStream(File.ReadAllBytes(path)));
var entryPointType = assembly.GetType("Script");
if (entryPointType == null)
{
Console.WriteLine("[.NET Script] Failed to find Script type");
return false;
}
var entryPointMethod = entryPointType.GetMethod("Main", BindingFlags.Static | BindingFlags.Public);
if (entryPointMethod == null)
{
Console.WriteLine("[.NET Script] Failed to find ScriptMain method");
return false;
}
entryPointMethod.Invoke(null, null);
}
catch (Exception e)
{
Console.WriteLine("[.NET Script] Exception in AssemblyLoader: " + e.Message);
return false;
}
finally
{
context.Unload();
context = null;
for (int i = 0; i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
return true;
}
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>bin\Release\net7.0\publish\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<_TargetId>Folder</_TargetId>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<History>True|2023-06-16T15:24:52.9876162Z;</History>
<LastFailureDetails />
</PropertyGroup>
</Project>