MSIL - how do you invoke a private method from MSIL?

后端 未结 3 1150
礼貌的吻别
礼貌的吻别 2021-01-02 20:04

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

相关标签:
3条回答
  • 2021-01-02 20:44

    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).

    0 讨论(0)
  • 2021-01-02 20:47

    Use Call, not Callvirt.

    [Edit: Not as a general recommendation, but specifically to address this issue]

    Callvirt is for calling virtual methods, where the destination address also depends upon the exact type of the instance. That doesn't work when you're using a weak reference.

    The target of a private method, on the other hand, can be determined at compile-time. It is therefore appropriate to invoke it using Call.

    0 讨论(0)
  • 2021-01-02 20:49

    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.

    0 讨论(0)
提交回复
热议问题