I'm using reflection to grab a field that happens to be a delegate. I need to replace this delegate with my own, but the type of the delegate is private (so I can't create it from my method and assign it)
I have a delegate type with an exactly matching signature, so is there some way I can dynamically cast my delegate to this other type? I have a Type object representing the unknown type.
I realize what I've said above may not very clear, so here's some code:
var delegate_type = Assembly.GetAssembly(typeof(A.F))
// public delegate in A.ZD (internal class)
.GetType("A.ZD+WD");
The type signature of the A.ZD+WS
(obfuscated name) delegate is void(System.Drawing.Graphics)
.
Is there a way I can cast an Action<Graphics>
to this delegate type?
It is only working for Delegates that are attached to managed methods. If trying to use Mike's article for a delegate attached to unmanaged dll function with GetDelegateForFunctionPointer, then the CreateDelegate technique will return a null attachment, and therefore crash uppon invocation. In this case I see a way to bypass the cast issue by using a wrapper class. where the abstract class has this interface:
Then the assembly you get your delegate from has to be modified to wrap the actual delegate with a class inherting from IInvokable. for example:
at this point the type must be fully "hardcoded" meaning that is can not use Func because it would prevent use of GetDelegateForFunctionPointer, because of a stupid limitation of that function (can't work with generics, because MS team is incompetent basically, c.f. msdn forums for the source on that).
my solution around this, is to use:
as found on another answer here on StackOverflow. and generate code for the various Invokable on the fly. creating instances using:
in the end a very complex system. thank you MS for being so lazy, really.
This article seems to have what you want.