samedi 12 janvier 2019

Creating a non-generic delegate from a MethodInfo

I have an interface, for instance:

public interface IInterface
{
    int Run(IntPtr client, [MarshalAs(UnmanagedType.LPStr)] string args);
}

I need a way at runtime to create a delegate type to invoke that method.

There are plenty of other questions of the subject, such as this one, and the answer always suggests to use Expression.GetDelegateType/Expression.GetFuncType/Expression.GetActionType to get the delegate type. However, those methods only return a specialized Action<T> or Func<T>. For my precise use-case, I have two additional constraints:

  • The delegate needs to keep the marshaling attributes declared on the original method
  • The delegate type cannot be generic (I need to feed it to Marshal.GetDelegateForFunctionPointer, which for some reason does not accept generic delegate types)

I'm thinking of using Reflection.Emit but that's an awful lot of code. Is there a faster/smarter way?





Aucun commentaire:

Enregistrer un commentaire