private static void EmitCtor(TypeBuilder tBuilder, ConstructorInfo ctor) { var pTypes = ctor.GetParameters().Select(p => p.ParameterType).ToArray(); var builder = ProxyUtils.GetConstructor( tBuilder, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, pTypes ); var ilGen = builder.GetILGenerator(); // No locals // Load all args, note arg 0 is this pointer, so must emit one more for (int i = 0; i <= pTypes.Length; i++) { DoEmit(ilGen, OpCodes.Ldarg_S, i); } // Call base ctor DoEmit(ilGen, OpCodes.Call, ctor); // Return DoEmit(ilGen, OpCodes.Ret); }
private static void EmitInterfaceMethod(TypeBuilder tBuilder, string ns, MethodInfo method, MethodInfo invokeMethod, MethodInfo convertMethod) { #region Emit Signatue // .method public hidebysig virtual instance void // MethodName(xxx) cil managed // { var pTypes = method.GetParameters().Select(p => p.ParameterType).ToArray(); MethodBuilder builder = ProxyUtils.GetMethod( tBuilder, method.Name, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, method.ReturnType, pTypes); #endregion var ilGen = builder.GetILGenerator(); EmitLocals(ilGen, method, pTypes); EmitHead(ilGen, method); EmitInvokeArguments(ilGen, ns, method, pTypes); EmitInvoke(ilGen, method, invokeMethod); EmitReturn(ilGen, method, convertMethod); }
private static Type EmitProxyType(Type baseType, Type interfaceType) { AssemblyBuilder asmBuilder = ProxyUtils.GetAssemblyBuilder("DynamicProxyAssembly"); ModuleBuilder mBuilder = ProxyUtils.GetModule(asmBuilder, "EmittedProxies"); TypeBuilder tBuilder = ProxyUtils.GetType(mBuilder, String.Format("{0}{1}Proxy", baseType.FullName, interfaceType), baseType, new[] { interfaceType }); // Emit parametrized ctor var constructors = baseType.GetConstructors(); foreach (var ctor in constructors) { Debug.WriteLine(ctor.Name); EmitCtor(tBuilder, ctor); } // Get namespace information var namespaceAttr = ProxyUtils.GetCustomAttribute <ProxyNamespaceAttribute>(interfaceType); var ns = namespaceAttr == null ? "" : namespaceAttr.Namespace; // Create methods in interfaceType var superType = typeof(ProxyBase); var invokeMethod = superType.GetMethod("Invoke", BindingFlags.Instance | BindingFlags.NonPublic); var convertMethod = superType.GetMethod("ConvertReturnValue", BindingFlags.Instance | BindingFlags.NonPublic); var methods = interfaceType.GetMethods(); foreach (var method in methods) { Debug.WriteLine(method.Name); EmitInterfaceMethod(tBuilder, ns, method, invokeMethod, convertMethod); } var proxyType = tBuilder.CreateType(); return(proxyType); }