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