C# Library works in editor but not in build

Godot Version

v4.2.1.stable.mono.official [b09f793f5]

Question

I’ve been trying to use Harmony (GitHub - pardeike/Harmony: A library for patching, replacing and decorating .NET and Mono methods during runtime) with Godot, and strangely it works perfectly within the editor, but it doesn’t work in an exported build.

The issue seems to be related to .Net version incompatibility. Within the Godot Editor, System.Environment.Version is 8.0.2, but in an exported build, the version is 6.0.27.

Despite this, none of the Harmony releases of any version appear to work with an exported Godot build. (More details here: Harmony fails to patch method and throws exception in exported Godot build · Issue #572 · pardeike/Harmony · GitHub)

The one thing I have identified is that the .dll files appear to be slightly different between a .Net 6.0.27 Console App (which works correctly with Harmony), and the exported Godot build. All the metadata seems to be the same, but the filesizes differ.

Does anyone have any idea what’s going on here, or how to fix this problem?

1 Like

After researching some more, this appears to be a known issue with Godot and external .dll files. Loading external DLL at runtime errors · Issue #75160 · godotengine/godot · GitHub

It’s possible to work around this by using reflection as described in this answer: Loading external DLL at runtime errors · Issue #75160 · godotengine/godot · GitHub

public partial class ModLoader : Node
{
	public override void _Ready()
	{
		string modPath = ProjectSettings.GlobalizePath("user://TestMod.dll");

		var alc = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly());
		Assembly assembly = alc.LoadFromAssemblyPath(modPath);

		Type t = assembly.GetType("TestMod.TestModInit");

		t.GetMethod("Init")?.Invoke(null, null);
	}
}

Do note that at runtime you will need to get the dll file using

OS.GetExecutablePath().GetBaseDir().PathJoin(file: "dllname.dll")

instead

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.