BepInEx / Il2CppInterop

A tool interoperate between CoreCLR and Il2Cpp at runtime
GNU Lesser General Public License v3.0
185 stars 59 forks source link

Allow static method injection #95

Open limoka opened 1 year ago

limoka commented 1 year ago

This PR enables static methods to be injected. This mostly allows to pass such methods to il2cpp delegates, which can be useful in some cases.

My main use of this is for interacting with Burst compiler. It expects us to pass delegates pointing to valid il2cpp methods to consider them for Burst compilation.

I have tested these changes on Core Keeper Unity 2021.3.14.

js6pak commented 5 months ago

My test code:

public class Test : Il2CppSystem.Object
{
    public Test() : base(ClassInjector.DerivedConstructorPointer<Test>())
    {
        ClassInjector.DerivedConstructorBody(this);
    }

    public void InstanceFoo(int a, int b)
    {
        System.Console.WriteLine($"InstanceFoo {a} {b}");
    }

    public static void StaticFoo(int a, int b)
    {
        System.Console.WriteLine($"StaticFoo {a} {b}");
    }
}
ClassInjector.RegisterTypeInIl2Cpp<Test>();
var type = Il2CppType.Of<Test>();
var methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (var methodInfo in methods)
{
    Log.LogWarning(methodInfo.Name);
    if (methodInfo.Name.EndsWith("Foo"))
    {
        var o = methodInfo.IsStatic ? null : new Test();
        methodInfo.Invoke(o, new Il2CppReferenceArray<Object>([1, 2]));
    }
}