public static IntPtr GetFunctionPointerForDelegate(T delegateCallback, out object binder) where T : class { var del = delegateCallback as Delegate; IntPtr result; try { result = Marshal.GetFunctionPointerForDelegate(del); binder = del; } catch (ArgumentException) // generic type delegate { var delegateType = typeof (T); var method = delegateType.GetMethod("Invoke"); var returnType = method.ReturnType; var paramTypes = method .GetParameters() .Select((x) => x.ParameterType) .ToArray(); // builder a friendly name for our assembly, module, and proxy type var nameBuilder = new StringBuilder(); nameBuilder.Append(delegateType.Name); foreach (var pType in paramTypes) { nameBuilder .Append("`") .Append(pType.Name); } var name = nameBuilder.ToString(); // check if we've previously proxied this type before var proxyAssemblyExist = AppDomain .CurrentDomain .GetAssemblies() .FirstOrDefault((x) => x.GetName().Name == name); Type proxyType; if (proxyAssemblyExist == null) { /// create a proxy assembly var proxyAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName(name), AssemblyBuilderAccess.Run ); var proxyModule = proxyAssembly.DefineDynamicModule(name); // begin creating the proxy type var proxyTypeBuilder = proxyModule.DefineType(name, TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.Sealed | TypeAttributes.Public, typeof (MulticastDelegate) ); // implement the basic methods of a delegate as the compiler does var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual; proxyTypeBuilder .DefineConstructor( MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName, CallingConventions.Standard, new Type[] {typeof (object), typeof (IntPtr)}) .SetImplementationFlags( MethodImplAttributes.Runtime | MethodImplAttributes.Managed ); proxyTypeBuilder .DefineMethod( "BeginInvoke", methodAttributes, typeof (IAsyncResult), paramTypes) .SetImplementationFlags( MethodImplAttributes.Runtime | MethodImplAttributes.Managed); proxyTypeBuilder .DefineMethod( "EndInvoke", methodAttributes, null, new Type[] {typeof (IAsyncResult)}) .SetImplementationFlags( MethodImplAttributes.Runtime | MethodImplAttributes.Managed); proxyTypeBuilder .DefineMethod( "Invoke", methodAttributes, returnType, paramTypes) .SetImplementationFlags( MethodImplAttributes.Runtime | MethodImplAttributes.Managed); // create & wrap an instance of the proxy type proxyType = proxyTypeBuilder.CreateType(); } else { // pull the type from an existing proxy assembly proxyType = proxyAssemblyExist.GetType(name); } // marshal and bind the proxy so the pointer doesn't become invalid var repProxy = Delegate.CreateDelegate(proxyType, del.Target, del.Method); result = Marshal.GetFunctionPointerForDelegate(repProxy); binder = Tuple.Create(del, repProxy); } return result; }