public static partial class Util { const string kDelegateInvokeMethodName = "Invoke"; // http://www.codeproject.com/Tips/441743/A-look-at-marshalling-delegates-in-NET public static T GetDelegateForFunctionPointer(IntPtr ptr, System.Runtime.InteropServices.CallingConvention call_conv) where T : class { Contract.Requires(typeof(T).IsSubclassOf(typeof(Delegate))); Contract.Requires(ptr != IntPtr.Zero); Contract.Requires(call_conv != System.Runtime.InteropServices.CallingConvention.ThisCall, "TODO: ThisCall's require a different implementation"); Contract.Ensures(Contract.Result() != null); var type = typeof(T); var method = type.GetMethod(kDelegateInvokeMethodName); var ret_type = method.ReturnType; var param_types = (from param in method.GetParameters() select param.ParameterType) .ToArray(); var invoke = new System.Reflection.Emit.DynamicMethod(kDelegateInvokeMethodName, ret_type, param_types, typeof(Delegate)); var il = invoke.GetILGenerator(); // Generate IL for loading all the args by index // TODO: IL has Ldarg_0 to Ldarg_3...do these provide any tangible perf benefits? for (int x = 0; x < param_types.Length; x++) il.Emit(System.Reflection.Emit.OpCodes.Ldarg, x); // Generate the IL for Calli's entry pointer (pushed to the stack) if (Environment.Is64BitProcess) il.Emit(System.Reflection.Emit.OpCodes.Ldc_I8, ptr.ToInt64()); else il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, ptr.ToInt32()); il.EmitCalli(System.Reflection.Emit.OpCodes.Calli, call_conv, ret_type, param_types); il.Emit(System.Reflection.Emit.OpCodes.Ret); return invoke.CreateDelegate(type) as T; } };