Invalid IL code when using callvirt with Mono.Cecil - C#

633 views Asked by At

I'm trying to execute this code:

Assembly.LoadFrom(Path.Combine(Application.dataPath, "Mods/VapidModLoader.dll")).GetType("Vapid.ModLoader.ModLoaderActivator").GetMethod("Activate").Invoke(null, null);

In my attempt of doing so, I wrote this using Mono.Cecil.

ILProcessor processor = gameAwakeMethod.Body.GetILProcessor();
processor.Body.Instructions.Clear(); // Clear old instructions

processor.Body.Instructions.Insert(0, processor.Create(OpCodes.Call, ImportMethod(game, typeof(Application), "get_dataPath")));
processor.Body.Instructions.Insert(1, processor.Create(OpCodes.Ldstr, "Mods/VapidModLoader.dll"));
processor.Body.Instructions.Insert(2, processor.Create(OpCodes.Call, ImportMethod(game, typeof(Path), "Combine")));
processor.Body.Instructions.Insert(3, processor.Create(OpCodes.Call, ImportMethod(game, typeof(Assembly), "LoadFrom")));
processor.Body.Instructions.Insert(4, processor.Create(OpCodes.Ldstr, "Vapid.ModLoader.ModLoaderActivator"));
processor.Body.Instructions.Insert(5, processor.Create(OpCodes.Callvirt, ImportMethod(game, typeof(Assembly), "GetType")));
processor.Body.Instructions.Insert(6, processor.Create(OpCodes.Ldstr, "Activate"));
processor.Body.Instructions.Insert(7, processor.Create(OpCodes.Callvirt, ImportMethod(game, typeof(Type), "GetMethod")));
processor.Body.Instructions.Insert(8, processor.Create(OpCodes.Ldnull));
processor.Body.Instructions.Insert(9, processor.Create(OpCodes.Ldnull));
processor.Body.Instructions.Insert(10,processor.Create(OpCodes.Callvirt, ImportMethod(game, typeof(MethodBase), "Invoke")));
processor.Body.Instructions.Insert(11,processor.Create(OpCodes.Pop));

My ImportMethod method looks like this

private static MethodReference ImportMethod(AssemblyDefinition assembly, Type type, string name)
{
    var importedType = assembly.MainModule.Import(type);
    return assembly.MainModule.Import(importedType.Resolve().Methods.First(f => f.Name == name));
}

This is the error I get:

InvalidProgramException: Invalid IL code in PlanetRotateMouse:Start (): IL_0023: callvirt 0x0a000235

This is what the IL Code looks like when compiled enter image description here

Sorry if I don't have enough details, but I included everything related and I don't have too too much knowledge in these subjects. Any help would or explanations as to what's going wrong would be greatly appreciated. Thank you!

0

There are 0 answers