Il2CppInterop icon indicating copy to clipboard operation
Il2CppInterop copied to clipboard

Allow static method injection

Open limoka opened this issue 1 year ago • 1 comments

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.

limoka avatar Jun 10 '23 08:06 limoka

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]));
    }
}

js6pak avatar Feb 25 '24 19:02 js6pak