I have this method:
public int Test()
{
ExternalClass cls = new ExternalClass();
return cls.ExternalMethod();
}
I need to change it using IL Injection so I can pass the type as parameter and remove the direct object creation, like this:
public int Test(ExternalClass cls)
{
return cls.ExternalMethod();
}
I am able to add the additional parametr using <>.Parameters.Add(____) and generate the new Assembly.
The issue is that I am not able to remove the instruction for the new object creation. Below are the lines I used to remove that.
ILProcessor ilProcessor = <<MethodDefinition>>.Body.GetILProcessor();
ilProcessor.Remove(<<newobj instruction>>);
Once I tried to call the modified assembly method like below, it’s throwing the error “Common Language Runtime detected an invalid program.”
ExternalClass ext = new ExternalClass();
int i = prg1.Test(ext);
I know I may need to handle memory allocation related stuff, too. I would appreciate if anybody is able to provide additional steps to be implemented here.
You can’t just remove the
newobjinstruction; you’re left with an invalid program, as the runtime told you. Here’s roughly how the original method translates to IL:If you remove only the
newobjinstruction then thestlocinstruction will have nothing on the stack to store in the local. You need to turn the method into this:So you need to do three things:
ldlocinstruction.ldarg.1instruction at the beginning of the method.Optionally, you may also remove the
ExternalClasslocal. (This will be optimized away by the JIT-compiler, but will bloat the IL image.)