so I was fooling around with DNLIB recently, and I was trying to add methods to a .net file. I got the methods from a previously compiled file, so basically, I was trying to mimic the method.
There are 3 methods: GetTheTypes, InvokeIt, and InvokeCall.
Firstly, I had to create the methods GetTheTypes and InvokeIt because InvokeCall calls both the GetTheTypes method and the InvokeIt method. So I added those methods, and they were added perfectly. It compiled and saved, and I was able to see them in a reflector/ILSpy with no problem. Note: when I add the methods, I have a check to see if they should be static or non-static, so that is not an issue. They are also all public methods.
Then, I wanted to add the InvokeCall method. So I did the same thing I did for the other methods, opened the methods I wanted mimicked in ILSpy, then basically copied all of the instructions and local variables into a new CilBody which were added to the InvokeCall method that I was mimicking. The only problem was it threw an error saying "Error Calculating Max Stack Value". The weird thing was, if I changed the OPCode from Call to NewObj, it compiled fine. But that is not what I want to do. What I want to do throws the error mentioned above.
Here is the code I use to add the instruction:
cBody.Instructions.Add(OpCodes.Call.ToInstruction(_getTheTypesMethod))
The _getThetypesMethod variable is defined as a MethodDefUser and consists of the method I created ealier and compiled just fine. I have also tried this:
cBody.Instructions.Add(OpCodes.Call.ToInstruction(t.Asm.Import(_getTheTypesMethod)))
That also did not work. I have also tried to get the DeclaringType of the method as well, then Finding the method like this:
cBody.Instructions.Add(OpCodes.Call.ToInstruction(t.Asm.Import(_getTheTypesMethod.GetDeclaringType().FindMethod("GetTheTypes")))
That didn't work either.
So if anyone has any suggestions as to how to call a method that was just created, please tell me. I've been trying to find out how to fix this problem for the last day or so, with no prevail. Thanks.