I'm hoping someone here has some insight cuz I'm really stuck on this one
So here's the scenario:
1) I'm trying to dynamically create an event handler for a delegate type.
2) I'd like for the event handler to simply call an anonymous method.
I've been fooling around with DynamicMethod with some success as I'm able to get an instance of EventInfo, generate a simple DynamicMethod instance, and create a Delegate dynamically using the DynamicMethod.CreateDelegate(Type) method.
While I haven't been able to figure out how to call the anonymous method that's passed in, I have been able to simply get it to write a line to the console using ILGenerator.EmitWriteLine(String) of the ILGenerator of the DynamicMethod.
Where I've failed is the generation of the call to the anonymous method. For the most part, I'm convinced that my only error now seems to be in the IL generation after I've created the DynamicMethod instance.
For testing purposes, I'm using the following simple code:
I've simplified it since I really only need to test the IL generation at this point.Code:using System; using System.Reflection.Emit; namespace ConsoleApplication4 { internal class Program { public delegate void VoidNoArgs(); private static void Main(string[] args) { Program program = new Program(); program.Run(); } private string text = "Hello World!"; private void Run() { Helper helper = new Helper(); helper.Test(delegate { Print(null); }); } public void Print(string message) { Console.Out.WriteLine(message); } } internal class Helper { public void Test(Program.VoidNoArgs del) { // Test invocation of dynamic method DynamicMethod method = new DynamicMethod( "NewMethod", typeof (void), new Type[] {}, typeof (Program)); ILGenerator generator = method.GetILGenerator(256); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Call, del.Method); generator.Emit(OpCodes.Ret); Delegate d = method.CreateDelegate(typeof (Program.VoidNoArgs)); d.DynamicInvoke(); } } }
If I replace the code generation with:
The code works fine, but obviously, it's only able to output a fixed string instead of having the desired effect of invoking the anonymous method.Code:generator.EmitWriteLine("Fixed string :("); generator.Emit(OpCodes.Ret);
So, what am I doing wrong here![]()


Reply With Quote