mercredi 18 janvier 2017

How to proxy IDisposable.Dispose to field using EMIT

I'm writing a simple code-generation utility and encounter a problem when I just cannot proxy simple method call to field: here is my code

...
else if (ReferenceEquals(interfaceMethod, ReflectionHelper.DisposeMethod))
{
    var implementation = tb.DefineMethod(interfaceMethod.Name, MethodAttributes.Public | MethodAttributes.Virtual);
    var il = implementation.GetILGenerator();
    il.Emit(OpCodes.Ldfld, typeof(AsyncClientBase).GetTypeInfo().GetField("Processor", BindingFlags.Instance | BindingFlags.NonPublic));
    il.Emit(OpCodes.Callvirt, interfaceMethod);
    il.Emit(OpCodes.Ret);
    tb.DefineMethodOverride(implementation, interfaceMethod);
}
...

Where DisposeMethod is

public static MethodInfo DisposeMethod { get; } = typeof (IDisposable).GetTypeInfo().GetDeclaredMethod("Dispose");

And Processor is of type IAsyncRequestProcessor:

public interface IAsyncRequestProcessor : IDisposable
{
}

When I run it i get

Common Language Runtime detected an invalid program.

But I don't understand why. I loaded my field, I called method. What's wrong with it?

Just for a reference: AsyncClientBase

public abstract class AsyncClientBase
{
    protected readonly IAsyncRequestProcessor Processor;

    protected AsyncClientBase(IAsyncRequestProcessor processor)
    {
        Processor = processor;
    }
}





Aucun commentaire:

Enregistrer un commentaire