views:

322

answers:

1

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[] { });
    }
}
A: 

Instead of:

var testGeneric = testClass
    .GetMethod("TestMethod")
    .MakeGenericMethod(typeof(int));

You need:

var testGeneric = testClassOfObject
    .GetMethod("TestMethod")
    .MakeGenericMethod(typeof(int));

because testClass is an open generic class type and if you try to invoke a method it would crash.

Darin Dimitrov
Cheers, this answer led me to solve the more complicated problem I had. The project still isn't working, but I'm much closer.
Thomas Coats