Search code examples
c#wpf.net-coreavaloniaui

Unable to Instantiate this Delegate Using Reflection


I need to pass a specific delegate as a parameter to a method of which I can't change. The delegate is 'System.Windows.Interop.HwndSourceHook' which is part of PresentationCore.dll. It has to be that delegate, it cannot be a generic delegate with the same signature. And AFIAK you can't cast delegates from one type to another.

This is the method for the delegate:

public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    if (condition) {// Do stuff };
    return IntPtr.Zero;
}

Everything works fine when the assembly is loaded at compile time. However I'm porting the project to the Avalonia framework and this particular assembly must be loaded at runtime, so I have to use reflection.

I thought this should work...

Assembly dll = Assembly.LoadFrom(@"C:\Temp\PresentationCore.dll");
Type hwndSourceHookDelegateType = dll.GetType("System.Windows.Interop.HwndSourceHook"); 
MethodInfo wndProc = typeof(MyClass).GetMethod(nameof(this.WndProc));
Delegate del = Delegate.CreateDelegate(hwndSourceHookDelegateType, wndProc)

... but the last line throws:

System.ArgumentException: 'Cannot bind to the target method because its signature is not compatible with that of the delegate type.'

Even though the signature is correct.


Solution

  • You method isn't a static method, so you need to use:

    Delegate del = Delegate.CreateDelegate(hwndSourceHookDelegateType, this, wndProc);
    

    or

    IntPtr del = (IntPtr) Delegate.CreateDelegate(hwndSourceHookDelegateType, this, wndProc);
    

    Passing "this" to the second argument will allow the method to be bound to the instance method on the current object