I am making a code generation utility for my application, and I have a problem - I don't know how can I replace a method's parameter with a variable created inside it.
Example:
a) Code before code-generation:
public void SomeMethod(Foo foo)
{
DoSomethingWithFoo(foo);
int someInfo = foo.ExamleValue * 12;
// etc
}
b) Expected code after code-generation:
// BitwiseReader class is deserializing byte array received from UDP stream into types
public void SomeMethod(BitwiseReader reader)
{
Foo foo = reader.ReadFoo();
DoSomethingWithFoo(foo);
int someInfo = foo.ExamleValue * 12;
// etc
}
I have tried making a second method, that converts BitwiseReader into Foo and passes it to the actual SomeMethod(Foo) method. But I am making a high-performance application and that second method visibly increased processing time.
The biggest problem is that Mono.Cecil handles Parameters & Variables very differently & I don't know how to replace a param into a generated variable.
FAQ to "Micro optimization is bad (TM)" guys:
I am making a very high-performance application that handles tens of thousands of operations per second. And as I said - my workaround with a second method decreased performance in a visible way.
If you look in the original IL code you'll see something like this:
Basically what you will need to is:
Replace the parameter type Foo with BitwiseReader
Find the instruction that is loading the 1st parameter (IL_0002 in the above), i.e, previously
foo, nowreaderAdd a call to
ReadFoo()just after the instruction found in the previous step.After these steps your IL will looks like:
Finally some good tools you can use may find useful when experimenting with Mono.Cecil / IL / C#: