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

泪湿孤枕 提交于 2019-11-30 14:13:58

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!