Search code examples
.netpinvoke

What does the AllowReversePInvokeCallsAttribute do?


I've done reverse pInvokes and not used this attribute. I note from the documentation that it was added in 3.5 but the docs don't provide any example of how to use it or describe what it does. Can someone say what it does, and provide an example of how it might be used and when it is needed?


Solution

  • The comment in the Reference Source gives some insight:

    // To be used on methods that sink reverse P/Invoke calls.
    // This attribute is a CoreCLR-only security measure, currently ignored by the desktop CLR.
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public sealed class AllowReversePInvokeCallsAttribute : Attribute
    {
        public AllowReversePInvokeCallsAttribute()
        {
        }
    }
    

    CoreCLR is the CLR version that drives Silverlight. Big on sandboxing. You won't find it used at all in the desktop version but all over the place in the Silverlight assemblies. Samples are the MS.Internal.FrameworkCallbacks class and the System.Windows namespace. Have a look-see with Reflector. The intention is clear, when the CLR marshals a call from native to managed, it checks if the managed method is expected to be invoked.