I'm dynamically sub classing a generic type (filling it's contract) that has a generic method. I attempt to call this generic method but the assembly I produce has errors. Reflector crashes when trying to open the assembly and this code snippet does not run.
The exception I get is:
An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
Any help would be appreciated. I'm going to install PEVerify to have a look at the generated code.
using System;
using System.Reflection;
using System.Reflection.Emit;
public class TestClass<TFirst>
{
public void TestMethod<TSecond>()
{
Console.WriteLine("It works");
}
}
public class Program
{
static void Main(string[] args)
{
// create a dynamic assembly and module
var assemblyName = new AssemblyName("DynamicAssembly");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var module = assemblyBuilder.DefineDynamicModule("DynamicAssembly.dll");
// public class Voodoo.Dynamic.Class : TestClass<object>
var testClass = typeof(TestClass<>);
var testClassOfObject = testClass.MakeGenericType(typeof(object));
var typeBuilder = module.DefineType(
"Voodoo.Dynamic.Class",
TypeAttributes.Public | TypeAttributes.Class,
testClassOfObject);
// public void Run()
var methodBuilder = typeBuilder.DefineMethod("Run", MethodAttributes.Public);
// this.TestMethod<int>();
var testGeneric = testClass.GetMethod("TestMethod").MakeGenericMethod(typeof(int));
var il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // load this
il.Emit(OpCodes.Call, testGeneric);
il.Emit(OpCodes.Ret);
// bake it
var classType = typeBuilder.CreateType();
assemblyBuilder.Save("DynamicAssembly.dll");
// var instance = new Voodoo.Dynamic.Class();
var instance = Activator.CreateInstance(classType);
// instance.Run();
classType.GetMethod("Run").Invoke(instance, new object[] { });
}
}