DynamicInvoke for CF 2.0

March 22nd, 2009 at 22:14 Ryan Rogers

This solution only works for .Net CF prior to 3.5 as the Target and Method properites did not exist before that. Any ideas how to “fake” DynamicInvoke for CF 2.0? I am using extension methods through the ExtensionAttribute trick.
Delegatedynamicinvoke-for-net-compact-framework

Hello Ryan,

The problem is that the .NET compact framework 2.0 is lacking some really important functionality. What we can get by using ugly reflection code is the target object where the delegate points to and the method pointer of the target method.

The code is provided below:

 
public static class DelegateExtensions
    {
        public static object DynamicInvoke(this Delegate dlg, params object[] args)
        {
            const BindingFlags MyBindingFlags = BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance;
            FieldInfo targetObject = dlg.GetType().GetField("_target", MyBindingFlags);
            FieldInfo targetMethod = dlg.GetType().GetField("_methodPtr", MyBindingFlags);
            object target = targetObject.GetValue(dlg);
            IntPtr ptr = (IntPtr)targetMethod.GetValue(dlg);
            
            // and now we are stucked as far as I know!
        }
    }

The problem is that when we retrieved the pointer to the method we have no way to find out to which method the pointer actually points to (by means of the compact framework). I have not found a solution to retrieve an appropriate RuntimeMethodHandle via the retrieved pointer to dynamically retrieve the MethodInfo/MethodBase of the target method. If this would be possible we would be able to execute the target method via the reflected MethodInfo. I hope that helps!

About the author

Daniel Marbach

2 comments

  • In your post: “This solution only works for .Net CF prior to 3.5 as the Target and Method properites did not exist before that.”

    There is missing a “not”. Otherwise it’s quite confusing 😉

By Daniel Marbach

Recent Posts