James Simpson
James Simpson

Reputation: 1150

Using "Method" MethodInfo property from an Action<T> delegate in il.EmitCall

Is something like this possible?

//
//  create a delegate
Action<Type> action = (t) => t.DoSomething;

//
// get the IL generator for a method
ILGenerator il = myMethodBuilder.GetILGenerator();

//
// try and call the delegate
il.EmitCall(OpCodes.Callvirt, action.Method, null);

Im getting a MethodAccessException whenever I try to invoke the method.

Thanks

Upvotes: 0

Views: 910

Answers (3)

Michael B
Michael B

Reputation: 7577

If you use a dynamic method you can use the skip visibility checks in the jitter.

Upvotes: 0

Tim Robinson
Tim Robinson

Reputation: 54734

Im getting a MethodAccessException whenever I try to invoke the method.

This is because the method generated for the C# (t) => t.DoSomething lambda is private. Chances are this lambda won't be static, either, depending on which of the local variables it captures from the outer method. You're issuing a callvirt instruction but you don't appear to be supplying an instance.

You can verify this by loading your application's code in Reflector and looking at the implementation of your (t) => t.DoSomething lambda.

You need to either:

  • Upgrade your lambda to a real public static method in an externally-visible class
  • Find a way to include a parameter of type Action<Type> in your IL method, generate code that calls Action<Type>.Invoke, then pass your action variable into the generated method

Upvotes: 3

VoodooChild
VoodooChild

Reputation: 9784

See if this is related to what is mention Here.

Upvotes: 0

Related Questions