how do you invoke a private method from MSIL?

I'm writing a "weak event factory" - code which converts any Delegate into a new delegate with an identical signature, but with implementing a WeakReference on the target. I'm using MSIL to avoid calls to Delegate.CreateDelegate (which performance have shown to be slow).

The weak reference delegates work perfectly as long as the underlying method (the Method of the original delegate), was declared public. As soon as a private or anonymous method is used, the MSIL bombs at run time with a MethodAccessException .

Using compiled expression trees, I've been able to invoke private methods, so it must be possible to dynamically emit MSIL which invokes a private method. ...so what's wrong with the following?

        // var target = this.Target
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Callvirt, targetPropGetter);         
        il.Emit(OpCodes.Stloc, ilTarget);            

        // if(target != null)
        // {
        il.Emit(OpCodes.Ldloc, ilTarget);
        il.Emit(OpCodes.Brfalse_S, ilIsNullLabel);

        //      Method( @target, parm1, parm2 ...);
        il.Emit(OpCodes.Ldloc, ilTarget);                  // this = Target
        short argIndex = 1;
        foreach (var parm in delgParams)                   // push all other args
            il.Emit(OpCodes.Ldarg, argIndex++);

        il.Emit(OpCodes.Callvirt, delegat.Method);   // <-- Bombs if method is private
        il.Emit(OpCodes.Ret);

        // }
        il.MarkLabel(ilIsNullLabel);

So what's the secret to invoking a private member? Reflection can do it, expression trees can do it... why is the above code failing?


EDIT: Much thanks to all of you who provided answers here. It turns out that the only solution which consistently worked in my context was to use generic delegates (Action)... because Action originates from the mscorlib, the JIT seems perfectly happy to let it invoke a private method. try using your own delegate and the JIT pukes just the same as if you emit a Call or Callvirt directly to the target.

Anyone who's interested in seeing the working code can head over to codeplex - the answers given here helped in implementing the WeakDelegate capabilities.


Are you inserting your IL into a DynamicMethod or into a method within a dynamic assembly? As I understand it, there is no way to skip visibility checks from within a dynamic assembly, but you can skip them when using a DynamicMethod (see here).


The solution (to my particular problem), was to used delegates instead of direct method calls. You can comfortably construct an open delegate and pass it to the IL code, and then when the IL code invokes the delegate's Invoke method, the JIT accepts the pattern as legal and allows the invoke of the private methods.

Like I said, this is a solution (which happily allows runtime-generated code to call private methods), though it still doesn't explain how technolgies like Expression Trees and Reflection manage to call private methods.


I just stumpled upon this thread finding a solution to 'break into non-public methods' for my particular case, so with regard to the options above (IL-generation, compiled expression trees), will they work in my case, or is it hopeless?

I just want to call RuntimeMethodInfo.InternalGetCurrentMethod(...), passing my own parameter (so I can implement GetCallingMethod(), or directly use RuntimeMethodInfo.InternatGetCurrentMethod(StackCrawlMark.LookForMyCaller in my logging routines). GetCurrentMethod is implemented as:

[MethodImpl(MethodImplOptions.NoInlining)]
public static MethodBase GetCurrentMethod()
{
    StackCrawlMark lookForMyCaller = StackCrawlMark.LookForMyCaller;
    return RuntimeMethodInfo.InternalGetCurrentMethod(ref lookForMyCaller);
}

where InternalGetCurrentMethod is declared: internal :-).

I have no problem calling the method using reflection, but this messes up the call stack and that is just the one thing that has to be preserved, otherwise it defeats its purpose.

What are my odds of keeping the stacktrace close to the original (at least within the distance of the allowed StackCrawlMarks, which are LookForMe, LookForMyCaller and LookForMyCallersCaller), using any of the discussed methods?

链接地址: http://www.djcxy.com/p/36062.html

上一篇: 工具链还是IDE? (调试器问题)

下一篇: 你如何从MSIL调用私有方法?