This sounds like such an obvious thing but I am having a lot of difficulty. Basically, what I’m doing is generating a method using Reflection.Emit and I then want to call it. So far, I have the method building and such, but I can’t get a reference to the method after it’s built because “The invoked member is not supported before the type is created.”
Here is what I basically do:
AssemblyBuilder assembly;
ModuleBuilder module;
TypeBuilder containerTypeBuilder;
Type containerType;
var name = new AssemblyName();
name.Name = "DynamicWrapper";
var domain = Thread.GetDomain();
assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
module = assembly.DefineDynamicModule(assembly.GetName().Name, false);
containerTypeBuilder = module.DefineType("__DynamicWrapperType",
TypeAttributes.Public | TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout, typeof(object));
//build method
var mb = containerTypeBuilder.DefineMethod("generatedmethod" + (unique++),
MethodAttributes.Public | MethodAttributes.Static, typeof (int),
new Type[] {});
//build method body and all that
.....
var type=module.GetType("__DynamicWrapperType");
var info=type.GetMethod(mb.Name, BindingFlags.Static | BindingFlags.Public); //error here
How do I take my freshly built method and load it up so that I can invoke it?
Also, I’ve tried mb.Invoke, but that yields “The invoked member is not supported in a dynamic module.”
If you are creating individual method(s), then
DynamicMethodis a much better choice (especially since your method is static) – you just useCreateDelegate(specifying the delegate type), cast to that delegate, and invoke. It is also less overhead, and collectible.But if you are forced to use
MethodBuilder: you must useCreateTypeon theTypeBuilder, then use reflection on the now real type (returned fromCreateType).