/// <summary> /// Implements <see cref="Oragon.Spring.Aop.Framework.IAopProxy"/> interface. /// </summary> /// <param name="typeBuilder">The type builder to use.</param> protected virtual void ImplementIAopProxy(TypeBuilder typeBuilder) { Type intf = typeof(IAopProxy); MethodInfo getProxyMethod = intf.GetMethod("GetProxy", Type.EmptyTypes); typeBuilder.AddInterfaceImplementation(intf); MethodBuilder mb = typeBuilder.DefineMethod(typeof(IAdvised).FullName + "." + getProxyMethod.Name, MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, getProxyMethod.CallingConvention, getProxyMethod.ReturnType, Type.EmptyTypes); ILGenerator il = mb.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ret); typeBuilder.DefineMethodOverride(mb, getProxyMethod); }
/// <summary> /// This method does the "heavy-lifting" of actually generating a dynamic class that implements /// <see cref="IFbClient"/>, and calls the native library specified to do the actual work. /// </summary> /// <param name="dllName">The name of the libarary to use, as passed into the /// <see cref="DllImportAttribute"/> that is dynamically generated.</param> /// <returns>An implementation of <see cref="IFbClient"/>.</returns> /// <remarks> /// <para>Note: To be completly generic, we actually reflect through <see cref="IFbClient"/> /// to get the methods and parameters to generate.</para> /// </remarks> private static IFbClient GenerateFbClient(string dllName) { // Get the initial TypeBuilder, with a "blank" class definition TypeBuilder tb = CreateTypeBuilder(dllName); // It needs to implement IFbClient, obviously! tb.AddInterfaceImplementation(typeof(IFbClient)); // Now, go through all the methods in IFbClient and generate the corresponding methods // in our dynamic type. foreach (MethodInfo mi in typeof(IFbClient).GetMethods()) { GenerateMethod(tb, mi, dllName); } // Finally, create and return an instance of the type itself. Woot! return(CreateInstance(tb)); }
public ClassEmitter(ModuleScope modulescope, String name, Type baseType, IEnumerable <Type> interfaces, TypeAttributes flags, bool forceUnsigned) : this(CreateTypeBuilder(modulescope, name, baseType, interfaces, flags, forceUnsigned)) { interfaces = InitializeGenericArgumentsFromBases(ref baseType, interfaces); if (interfaces != null) { foreach (var inter in interfaces) { TypeBuilder.AddInterfaceImplementation(inter); } } TypeBuilder.SetParent(baseType); moduleScope = modulescope; }
private static void ImplementEqualsOfType(TypeBuilder anonymousTypeBuilder) { anonymousTypeBuilder.AddInterfaceImplementation(typeof(IEquatable <>).MakeGenericType(anonymousTypeBuilder)); var equalsMethodBuilder = anonymousTypeBuilder.DefineMethod(EqualsMethod, MethodAttributes.Public | MethodAttributes.Virtual, typeof(bool), new Type[] { anonymousTypeBuilder }); var ilEquals = equalsMethodBuilder.GetILGenerator(); ilEquals.Emit(OpCodes.Ldarg_0); ilEquals.Emit(OpCodes.Call, typeof(SerializationExtensionMethods).GetMethod(SerializeToXmlMethod, BindingFlags.Static | BindingFlags.Public)); ilEquals.Emit(OpCodes.Ldarg_1); ilEquals.Emit(OpCodes.Call, typeof(SerializationExtensionMethods).GetMethod(SerializeToXmlMethod, BindingFlags.Static | BindingFlags.Public)); ilEquals.Emit(OpCodes.Call, typeof(String).GetMethod(OpEqualityMethod, new Type[] { typeof(string), typeof(string) })); ilEquals.Emit(OpCodes.Ret); }
/// <summary> /// Adds an implementation to the created type. /// </summary> /// <param name="tb">Type builder object.</param> /// <param name="typeToWrap">Created class.</param> private static void AddTypeImplementation(TypeBuilder tb, Type typeToWrap) { // add implementation for the interface if (IsInterface(typeToWrap)) { tb.AddInterfaceImplementation(typeToWrap); } // create implementation for each type abstract method MethodInfo[] parentMethodInfo = typeToWrap.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance /* | BindingFlags.DeclaredOnly */); for (int i = 0; i < parentMethodInfo.Length; ++i) { if (IsAbstractMethod(parentMethodInfo[i])) { AddMethodImplementation(parentMethodInfo[i], tb); } } }
public void AddInterfaceImplementation(TypeAttributes typeAttributes) { TypeBuilder interfaceBuilder = Helpers.DynamicType(TypeAttributes.Abstract | TypeAttributes.Interface | TypeAttributes.Public); interfaceBuilder.DefineMethod("TestMethod", MethodAttributes.Abstract | MethodAttributes.Virtual | MethodAttributes.Public, typeof(int), new Type[] { typeof(int), typeof(int) }); Type createdInterface = interfaceBuilder.CreateTypeInfo().AsType(); TypeBuilder type = Helpers.DynamicType(typeAttributes); type.AddInterfaceImplementation(createdInterface); Type createdType = type.CreateTypeInfo().AsType(); Assert.Equal(createdInterface, createdType.GetTypeInfo().ImplementedInterfaces.Single(i => i.Name == createdInterface.Name)); }
private static IJson CreateSerializer(Type type) { //string dllPath = null; string SerialName = "SerializerFor" + type.Name; string ASM_NAME = SerialName; string MOD_NAME = SerialName; string TYP_NAME = SerialName; string DLL_NAME = SerialName + ".dll"; AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(ASM_NAME), AssemblyBuilderAccess.RunAndSave); ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule(MOD_NAME, DLL_NAME); TypeBuilder typBuilder = modBuilder.DefineType(TYP_NAME); typBuilder.AddInterfaceImplementation(typeof(IJson)); MethodBuilder ToJsonMethodBuilder = typBuilder.DefineMethod( "ToJson", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.ReuseSlot, typeof(string), new Type[1] { typeof(object) } ); ImplementToJsonMethod(ToJsonMethodBuilder, type); Type serialType = typBuilder.CreateType(); asmBuilder.Save(DLL_NAME); IJson createdSerial = (IJson)Activator.CreateInstance(serialType); serializers.Add(type, createdSerial); return(createdSerial); }
private static Type Create <T>() { lock (dynamicModuleLock) { if (dynamicModule == null) { var myDomain = AppDomain.CurrentDomain; var name = new AssemblyName("DataContractDynamicAssembly"); assemblyBuilder = myDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); dynamicModule = assemblyBuilder.DefineDynamicModule("DataContractDynamicAssembly"); //assemblyBuilder = myDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave); //dynamicModule = assemblyBuilder.DefineDynamicModule("DataContractDynamicAssembly", "DataContractDynamicAssembly.dll"); } Type baseClass; if (typeof(T).IsValueType) { baseClass = typeof(AbstractValueTypeDatumConverter <T>); } else { baseClass = typeof(AbstractReferenceTypeDatumConverter <T>); } TypeBuilder type = dynamicModule.DefineType( "DataContractDatumConverterFactory." + typeof(T).FullName, TypeAttributes.Class | TypeAttributes.Public, baseClass ); type.AddInterfaceImplementation(typeof(IObjectDatumConverter)); var datumConverterFactoryField = DefineDatumConverterField(type); DefineConstructor(type, datumConverterFactoryField); DefineConvertDatum <T>(type, datumConverterFactoryField); DefineConvertObject <T>(type, datumConverterFactoryField); DefineGetDatumFieldName <T>(type); Type finalType = type.CreateType(); //assemblyBuilder.Save("DataContractDynamicAssembly.dll"); return(finalType); } }
/// <param name="duck">The duck</param> /// <param name="interface">the interface to cast <paramref name="duck"/></param> /// <param name="missingMethods">How to handle missing methods</param> static IDuckDelegateFactory CreateProxy(Type duck, Type @interface, MissingMethods missingMethods) { if (duck == null) { throw new ArgumentNullException(nameof(duck)); } if (@interface == null) { throw new ArgumentNullException(nameof(@interface)); } if ([email protected]().IsInterface) { throw new ArgumentException($"{@interface} is not an interface"); } string assemblyName = "Ducks_Instance_" + @interface.AsmName() + "_" + duck.AsmName() + ".dll"; var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Run); var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName); TypeBuilder proxyBuilder = moduleBuilder.DefineType($"{duck.Name}_{@interface.Name}_DelegateProxy"); foreach (var face in @interface.GetInterfaces().Concat(@interface, typeof(IDuck))) { proxyBuilder.AddInterfaceImplementation(face); } var duckField = proxyBuilder.DefineField("duck", duck, FieldAttributes.Private | FieldAttributes.InitOnly); var ctor = proxyBuilder.DefineConstructor(duck, duckField); bool defined = false; foreach (var face in @interface.GetInterfaces().Concat(@interface)) { DefineMembers(duck, face, proxyBuilder, duckField, ref defined); } proxyBuilder.DefineUnwrapMethod(duckField); var factoryBuilder = CreateFactory(moduleBuilder, duck, ctor); proxyBuilder.CreateTypeInfo(); return((IDuckDelegateFactory)Activator.CreateInstance(factoryBuilder.CreateTypeInfo().AsType())); }
private static Type BuildType(Type baseInterface, string className, string fieldsPrefix, params Type[] types) { var assemblyName = new AssemblyName(className); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name); string[] genericParameters = new string[types.Length]; for (int i = 0; i < types.Length; i++) { genericParameters[i] = "T" + className + i; } TypeBuilder typeBuilder = moduleBuilder.DefineType(className, TypeAttributes.Class | TypeAttributes.Public); typeBuilder.AddInterfaceImplementation(baseInterface); CustomAttributeBuilder customAttribute = new CustomAttributeBuilder(typeof(SerializableAttribute).GetConstructor(Type.EmptyTypes), new object[] { }); typeBuilder.SetCustomAttribute(customAttribute); var typeParams = typeBuilder.DefineGenericParameters(genericParameters); FieldBuilder[] fields = new FieldBuilder[types.Length]; for (int i = 0; i < types.Length; i++) { fields[i] = typeBuilder.DefineField(fieldsPrefix + i, typeParams[i], FieldAttributes.Public); } var defConstructor = typeBuilder.DefineDefaultConstructor(MethodAttributes.Public); var constr = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, typeParams); var ilGenerator = constr.GetILGenerator(); for (int i = 0; i < types.Length; i++) { ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldarg_S, i + 1); ilGenerator.Emit(OpCodes.Stfld, fields[i]); } ilGenerator.Emit(OpCodes.Ret); return(typeBuilder.CreateType().MakeGenericType(types)); }
//TODO: Add indexer support private static void AddInterfaceImplementation(TypeBuilder typeBuilder, Type interfaceType, FieldBuilder handlerFieldBuilder) { typeBuilder.AddInterfaceImplementation(interfaceType); foreach (PropertyInfo propertyInfo in interfaceType.GetProperties()) { AddPropertyImplementation(typeBuilder, interfaceType, propertyInfo); } foreach (MethodInfo methodInfo in interfaceType.GetMethods()) { AddMethodImplementation(typeBuilder, interfaceType, methodInfo, handlerFieldBuilder); } foreach (EventInfo eventInfo in interfaceType.GetEvents()) { AddEventImplementation(typeBuilder, interfaceType, eventInfo); } }
void ApplyInterface(Type newInterface, TypeBuilder tb) { tb.AddInterfaceImplementation(newInterface); foreach (var f in newInterface.GetProperties()) { var fb = tb.DefineField(f.Name, f.PropertyType, System.Reflection.FieldAttributes.Public); foreach (var ca in f.GetCustomAttributesData()) { fb.SetCustomAttribute(CloneAttributes(ca)); } EmitInterfaceGetSet(newInterface, tb, fb); } foreach (var e in newInterface.GetEvents()) { AddEvent(newInterface, e, tb); } }
/// <summary> /// 通过反射发出动态实现接口T /// 为了提高性能,对反射发出的类型进行了缓存,保存在cache成员中 /// </summary> /// <typeparam name="T">类型</typeparam> /// <typeparam name="V">类型接口</typeparam> private static Type CreateType <T, V>() where T : IExtension <V> { Type targetInterfaceType = typeof(T); string generatedClassName = targetInterfaceType.Name.Remove(0, 1); AssemblyName aName = new AssemblyName("ExtensionDynamicAssembly"); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run); ModuleBuilder mb = ab.DefineDynamicModule(aName.Name); TypeBuilder tb = mb.DefineType(generatedClassName, TypeAttributes.Public); //实现接口 tb.AddInterfaceImplementation(typeof(T)); //value字段 FieldBuilder valueFiled = tb.DefineField("value", typeof(V), FieldAttributes.Private); //构造函数 ConstructorBuilder ctor = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(V) }); ILGenerator ctor1IL = ctor.GetILGenerator(); ctor1IL.Emit(OpCodes.Ldarg_0); ctor1IL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)); ctor1IL.Emit(OpCodes.Ldarg_0); ctor1IL.Emit(OpCodes.Ldarg_1); ctor1IL.Emit(OpCodes.Stfld, valueFiled); ctor1IL.Emit(OpCodes.Ret); //GetValue方法 MethodBuilder getValueMethod = tb.DefineMethod("GetValue", MethodAttributes.Public | MethodAttributes.Virtual, typeof(V), Type.EmptyTypes); ILGenerator numberGetIL = getValueMethod.GetILGenerator(); numberGetIL.Emit(OpCodes.Ldarg_0); numberGetIL.Emit(OpCodes.Ldfld, valueFiled); numberGetIL.Emit(OpCodes.Ret); //接口实现 MethodInfo getValueInfo = targetInterfaceType.GetInterfaces()[0].GetMethod("GetValue"); tb.DefineMethodOverride(getValueMethod, getValueInfo); //创建类型 Type t = tb.CreateType(); return(t); }
private static TypeBuilder GetTypeBuilder(string entityName) { var typeSignature = entityName; var an = new AssemblyName(typeSignature); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule"); TypeBuilder tb = moduleBuilder.DefineType(typeSignature , TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout , null); //Implementing IEntity to provide extension support and identify types as well tb.AddInterfaceImplementation(typeof(IEntity)); return(tb); }
private static TypeBuilder GetTypeBuilder() { var typeSignature = "MyDynamicType"; var an = new AssemblyName(typeSignature); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule"); TypeBuilder tb = moduleBuilder.DefineType(typeSignature, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, null, new Type[] { typeof(IFooContract) }); // <= Interface that the Dynamic class will implement (used for intellisens) tb.AddInterfaceImplementation(typeof(IFooContract)); // <= Specify that the class will implement that interface return(tb); }
/// <summary> /// Implemnents the OpenEngSBModel type to a sepcified type /// </summary> /// <param name="extendType">Type to extend</param> /// <returns>Type:OpenEngSBModel</returns> public static Type ImplementTypeDynamicly(Type extendType, Type interfaceType) { if (extendType.Name.ToUpper().Equals("OBJECT") || extendType.IsPrimitive || extendType.Name.ToUpper().Equals("STRING")) { return(extendType); } AssemblyName assemblyName = new AssemblyName("DataBuilderAssembly"); AssemblyBuilder assemBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemBuilder.DefineDynamicModule("DataBuilderModule"); TypeBuilder typeBuilder = moduleBuilder.DefineType(extendType.Name + interfaceType.Name, TypeAttributes.Class, extendType); typeBuilder.AddInterfaceImplementation(interfaceType); typeBuilder.DefineDefaultConstructor(MethodAttributes.Public); BuildProperty(typeBuilder, interfaceType); Type type = typeBuilder.CreateType(); return(type); }
/// <param name="duck">The duck</param> /// <param name="interface">the interface to cast <paramref name="duck"/></param> internal static Func <object, object> CreateProxy(Type duck, Type @interface, MissingMethods missingMethods) { if (duck == null) { throw new ArgumentNullException(nameof(duck)); } if (@interface == null) { throw new ArgumentNullException(nameof(@interface)); } if ([email protected]) { throw new ArgumentException($"{@interface} is not an interface"); } string assemblyName = "Ducks_Instance_" + @interface.AsmName() + "_" + duck.AsmName() + ".dll"; var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Run); var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName); TypeBuilder typeBuilder = moduleBuilder.DefineType("Proxy"); foreach (var face in @interface.GetInterfaces().Concat(@interface, typeof(IDuck))) { typeBuilder.AddInterfaceImplementation(face); } var duckField = typeBuilder.DefineField("duck", duck, FieldAttributes.Private | FieldAttributes.InitOnly); var ctor = typeBuilder.DefineConstructor(duck, duckField); foreach (var face in @interface.GetInterfaces().Concat(@interface)) { DefineMembers(duck, face, typeBuilder, duckField, missingMethods); } var create = typeBuilder.DefineStaticCreateMethod(duck, ctor, typeof(object)); typeBuilder.DefineUnwrapMethod(duckField); Type t = typeBuilder.CreateType(); return((Func <object, object>)Delegate.CreateDelegate(typeof(Func <object, object>), t.GetMethod("Create", BindingFlags.Static | BindingFlags.Public))); }
//--------------------------------------------------------------- #endregion //--------------------------------------------------------------- //--------------------------------------------------------------- #region Internal Helper Methods //--------------------------------------------------------------- void ImplementAspectComponent(Type baseInterface, TypeCodeBuilder tcBuilder, IDictionary fields) { // Add Interface IAspectComponent TypeBuilder builder = tcBuilder.TypeBuilder; builder.AddInterfaceImplementation(typeof(IAspectComponent)); // property baseInstance FieldBuilder fbBaseInstance = builder.DefineField("baseInstance", baseInterface, FieldAttributes.Private); tcBuilder.DefineStandardProperty("BaseInstance", fbBaseInstance, typeof(object), true, true, MethodAttributes.Public); fields["baseInstance"] = fbBaseInstance; // property aspect FieldBuilder fbAspect = builder.DefineField("aspectDispatcher", typeof(IAspectDispatcher), FieldAttributes.Private); tcBuilder.DefineStandardProperty("AspectDispatcher", fbAspect, typeof(IAspectDispatcher), true, true, MethodAttributes.Public); fields["aspectDispatcher"] = fbAspect; }
private static TypeBuilder CreateTypeBuilder(Type type) { var typeSignature = type.Name + "_RuntimeImpl_" + Guid.NewGuid(); TypeBuilder typeBuilder = module.Value.DefineType(typeSignature, TypeAttributes.Public | TypeAttributes.Class, null); if (type.IsInterface) { typeBuilder.AddInterfaceImplementation(type); } else { typeBuilder.SetParent(type); } return(typeBuilder); }
protected override Type GenerateWrapperType(Type interfaceToWrap, ModuleBuilder module, string moduleName) { // Define implementing type TypeBuilder typeBuilder = module.DefineType(MakeTypeName(moduleName, interfaceToWrap), TypeAttributes.Public); typeBuilder.AddInterfaceImplementation(SetupGenericClassArguments(interfaceToWrap, typeBuilder)); // Declare fields for the proxy and the target FieldBuilder fieldProxy = typeBuilder.DefineField("proxy", typeof(ILEmitProxy), FieldAttributes.Private); FieldBuilder fieldTarget = typeBuilder.DefineField("target", interfaceToWrap, FieldAttributes.Private); // Create overrides (and delegates) for all the interface methods Dictionary <FieldBuilder, MethodInfo> overloadedMethods = new Dictionary <FieldBuilder, MethodInfo>(); foreach (MethodInfo method in interfaceToWrap.GetMethods()) { // Cache a copy of the MethodInfo for each method FieldBuilder fieldMethodInfo = typeBuilder.DefineField("methodInfo" + overloadedMethods.Count, typeof(MethodInfo), FieldAttributes.Private); GenerateOverloadedMethod(typeBuilder, method, GenerateOverloadedMethodDelegate(method, typeBuilder, fieldTarget), fieldProxy, fieldTarget, fieldMethodInfo); overloadedMethods[fieldMethodInfo] = method; } // Create a single constructor which takes the proxy and target, and gets // all the necessary MethodInfo objects for the class GenerateConstructor(typeBuilder, interfaceToWrap, fieldProxy, fieldTarget, overloadedMethods); return(typeBuilder.CreateType()); }
/// <summary> /// Generates a new typed equals method using the given fields. /// </summary> /// <param name="typeBuilder">The type builder to use.</param> /// <param name="fieldsToUse">All fields to use to compute the hash code.</param> /// <returns>The created equals function.</returns> public static MethodInfo GenerateEquals( this TypeBuilder typeBuilder, FieldInfo[] fieldsToUse) { var equals = typeBuilder.DefineMethod( EqualsInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final, typeof(bool), new Type[] { typeBuilder }); var emitter = new ILEmitter(equals.GetILGenerator()); var falseLabel = emitter.DeclareLabel(); foreach (var field in fieldsToUse) { emitter.Emit(OpCodes.Ldarg_0); emitter.Emit(OpCodes.Ldflda, field); emitter.Emit(ArgumentOperation.Load, 1); emitter.Emit(OpCodes.Ldfld, field); emitter.EmitCall(field.FieldType.GetMethod( EqualsInfo.Name, new Type[] { field.FieldType })); emitter.Emit(OpCodes.Brfalse_S, falseLabel); } emitter.EmitConstant(1); emitter.Emit(OpCodes.Ret); emitter.MarkLabel(falseLabel); emitter.EmitConstant(0); emitter.Emit(OpCodes.Ret); emitter.Finish(); var equalityInstance = typeof(IEquatable <>).MakeGenericType(typeBuilder); typeBuilder.AddInterfaceImplementation(equalityInstance); return(equals); }
private JitCompiler(CpuConfig config, Type t_kernel, TypeBuilder t_xformed) { _config = config; _t_kernel = t_kernel; _m_kernel = _t_kernel.GetMethod("RunKernel", BF.All); ValidateInputParameters(); // todo. think how to support multiple methods: *Dims, *Idxes, synchronization points // todo. I'd even say that we should embed constants instead of Dims and cache such bodies between calls // todo. if some dimension is equal to 1, then strip off corresponding loop var lam = _m_kernel.Decompile(); _hir = lam.Body; _params = lam.Sig.Syms; _locals = lam.Body.LocalsRecursive(); _xhir = new Block(); _tids.Add("x", new Local("tid_x", typeof(int))); _tids.Add("y", new Local("tid_y", typeof(int))); _tids.Add("z", new Local("tid_z", typeof(int))); _xhir.Locals.AddElements(_tids.Values); InferLocalAllocationHints(); ReplicatePrivatelyAllocatedLocals(); LiftLocallyAllocatedLocals(); HoistGloballyAllocatedLocals(); _callsToSyncThreads = _hir.Family().OfType <Eval>().Where(eval => { var m1 = eval.InvokedMethod(); var syncapi_syncThreads = typeof(ISyncApi).GetMethod("SyncThreads"); return(m1.Api() == syncapi_syncThreads); }).ToReadOnly(); TransformBlock(_hir, _xhir, false); // todo. currently we don't support debuggable IL // the latter implies correct PDB-mappings and working watch for replicated vars _config.EmitDebuggableIL.AssertFalse(); _t_xformed = t_xformed; _t_xformed.AddInterfaceImplementation(typeof(IBlockRunner)); _m_xformed = _t_xformed.DefineMethod("RunBlock", MA.Public, typeof(void), typeof(int3).MkArray()); _m_xformed.DefineParameter(1, ParmA.None, "blockIdx"); CompileTransformedHir(); }
private TypeBuilder CreateTypeBuilder() { string className = Guid.NewGuid().ToString(); string moduleName = String.Format("{0}.dll", _assemblyName); // Get current currentDomain. AppDomain currentDomain = AppDomain.CurrentDomain; // Create assembly in current currentDomain. _name = new AssemblyName { Name = _assemblyName }; //name.CodeBase =clonedTypesAssemblyPath; _assemblyBuilder = currentDomain.DefineDynamicAssembly(_name, AssemblyBuilderAccess.Save); // create a module in the assembly ModuleBuilder moduleBuilder = _assemblyBuilder.DefineDynamicModule(moduleName, true); // create a type in the module TypeBuilder typeBuilder = moduleBuilder.DefineType(String.Format("{0}.{1}", _assemblyName, className), TypeAttributes.Class | TypeAttributes.Public, null, new[] { typeof(IMappedType) }); typeBuilder.AddInterfaceImplementation(typeof(IMappedType)); //Apply DataContract Attribute ConstructorInfo dataContractCtorInfo = typeof(DataContractAttribute).GetConstructor(Type.EmptyTypes); CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(dataContractCtorInfo, new object[] { }); typeBuilder.SetCustomAttribute(attributeBuilder); //Apply ProtoContractAttribute ConstructorInfo protoContractInfo = typeof(ProtoContractAttribute).GetConstructor(Type.EmptyTypes); CustomAttributeBuilder protoBuffClassAttributeBuilder = new CustomAttributeBuilder(protoContractInfo, new object[] { }); typeBuilder.SetCustomAttribute(protoBuffClassAttributeBuilder); return(typeBuilder); }
public void DefineMethodOverride_GenericInterface_Succeeds() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); type.AddInterfaceImplementation(typeof(GenericInterface <string>)); MethodBuilder method = type.DefineMethod(nameof(GenericInterface <string> .Method), MethodAttributes.Public | MethodAttributes.Virtual, typeof(string), new Type[0]); ILGenerator ilGenerator = method.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldstr, "Hello World"); ilGenerator.Emit(OpCodes.Ret); MethodInfo interfaceMethod = typeof(GenericInterface <string>).GetMethod(nameof(GenericInterface <string> .Method)); type.DefineMethodOverride(method, interfaceMethod); Type createdType = type.CreateTypeInfo().AsType(); Assert.Equal("Hello World", interfaceMethod.Invoke(Activator.CreateInstance(createdType), null)); }
public void DefineMethodOverride_InterfaceMethod() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder method = type.DefineMethod("M", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), null); ILGenerator ilGenerator = method.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldc_I4, 2); ilGenerator.Emit(OpCodes.Ret); type.AddInterfaceImplementation(typeof(DefineMethodOverrideInterface)); MethodInfo declaration = typeof(DefineMethodOverrideInterface).GetMethod("M"); type.DefineMethodOverride(method, declaration); Type createdType = type.CreateTypeInfo().AsType(); MethodInfo createdMethod = typeof(DefineMethodOverrideInterface).GetMethod("M"); Assert.Equal(2, createdMethod.Invoke(Activator.CreateInstance(createdType), null)); }
/// <summary> /// If type does not implement ICloneable, add the interface and give it a Clone() method /// (just call inherited MemberwiseClone). Otherwise do nothing. /// </summary> void MakeCloneable() { // If I don't already implement ICloneable ... if (type.GetInterface("ICloneable") == null) { MethodInfo cloneMethod = type.GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance); typeBuilder.AddInterfaceImplementation(typeof(System.ICloneable)); MethodBuilder myMethod = typeBuilder.DefineMethod("Clone", MethodAttributes.Public | MethodAttributes.Virtual, typeof(object), new Type[] {}); ILGenerator myMethodIL = myMethod.GetILGenerator(); #region | return MemberwiseClone(); myMethodIL.Emit(OpCodes.Ldarg_0); myMethodIL.Emit(OpCodes.Call, cloneMethod); myMethodIL.Emit(OpCodes.Ret); #endregion } }
private static void AddReadResolve(TypeWrapper wrapper) { MethodWrapper mw = wrapper.GetMethodWrapper("readResolve", "()Ljava.lang.Object;", false); if (mw != null && !wrapper.IsSubTypeOf(iobjectreference)) { TypeBuilder tb = wrapper.TypeAsBuilder; tb.AddInterfaceImplementation(JVM.Import(typeof(IObjectReference))); MethodBuilder getRealObject = tb.DefineMethod("IObjectReference.GetRealObject", MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final, Types.Object, new Type[] { JVM.Import(typeof(StreamingContext)) }); getRealObject.SetCustomAttribute(securityCriticalAttribute); AttributeHelper.HideFromJava(getRealObject); tb.DefineMethodOverride(getRealObject, JVM.Import(typeof(IObjectReference)).GetMethod("GetRealObject")); CodeEmitter ilgen = CodeEmitter.Create(getRealObject); mw.Link(); ilgen.Emit(OpCodes.Ldarg_0); mw.EmitCall(ilgen); ilgen.Emit(OpCodes.Ret); } }
private void EmitType(ModuleBuilder moduleBuilder) { TypeBuilder builder = moduleBuilder.DefineType("SetFor" + this._targetType.FullName + this._fieldName, TypeAttributes.Sealed | TypeAttributes.Public); builder.AddInterfaceImplementation(typeof(ISet)); builder.DefineDefaultConstructor(MethodAttributes.Public); Type[] parameterTypes = new Type[] { typeof(object), typeof(object) }; ILGenerator iLGenerator = builder.DefineMethod("Set", MethodAttributes.Virtual | MethodAttributes.Public, null, parameterTypes).GetILGenerator(); FieldInfo field = this._targetType.GetField(this._fieldName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (field != null) { iLGenerator.Emit(OpCodes.Ldarg_1); iLGenerator.Emit(OpCodes.Castclass, this._targetType); iLGenerator.Emit(OpCodes.Ldarg_2); if (this._fieldType.IsValueType) { iLGenerator.Emit(OpCodes.Unbox, this._fieldType); if (BaseAccessor.typeToOpcode[this._fieldType] != null) { OpCode opcode = (OpCode)BaseAccessor.typeToOpcode[this._fieldType]; iLGenerator.Emit(opcode); } else { iLGenerator.Emit(OpCodes.Ldobj, this._fieldType); } iLGenerator.Emit(OpCodes.Stfld, field); } else { iLGenerator.Emit(OpCodes.Stfld, field); } } else { iLGenerator.ThrowException(typeof(MissingMethodException)); } iLGenerator.Emit(OpCodes.Ret); builder.CreateType(); }
public int Implement(HashSet <Type> implementedInterfaces, int memberCount) { if (implementedInterfaces.Contains(this.@interface)) { return(memberCount); } implementedInterfaces.Add(this.@interface); typeBuilder.AddInterfaceImplementation(this.@interface); foreach (MethodInfo method in MethodsToIntercept()) { OverrideMethod(method, memberCount++); } foreach (PropertyInfo property in PropertiesToIntercept()) { OverrideProperty(property, memberCount++); } foreach (EventInfo @event in EventsToIntercept()) { OverrideEvent(@event, memberCount++); } foreach (var @extendedInterface in [email protected]()) { memberCount = new InterfaceImplementation( this.typeBuilder, @extendedInterface, new GenericParameterMapper(@extendedInterface, this.genericParameterMapper), this.proxyInterceptionPipelineField, this.explicitImplementation, this.targetField) .Implement(implementedInterfaces, memberCount); } return(memberCount); }
public static Type Create(string assemblyName, string typeName) { AssemblyName aName = new AssemblyName(assemblyName); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly( aName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll"); TypeBuilder tb = mb.DefineType(typeName, TypeAttributes.Public); tb.AddInterfaceImplementation(typeof(IJob)); MethodBuilder meth = tb.DefineMethod( "Execute", MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(JobExecutionContext) }); meth.DefineParameter(1, ParameterAttributes.In, "context"); ILGenerator methIL = meth.GetILGenerator(); methIL.Emit(OpCodes.Ldarg_0); Type t = null; try { // Finish the type. t = tb.CreateType(); } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); } // ab.Save(aName.Name + ".dll"); return(t); }
private static void RemoveReadResolve(TypeBuilder tb) { tb.AddInterfaceImplementation(JVM.Import(typeof(IObjectReference))); MethodBuilder getRealObject = tb.DefineMethod("IObjectReference.GetRealObject", MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final, Types.Object, new Type[] { JVM.Import(typeof(StreamingContext)) }); getRealObject.SetCustomAttribute(securityCriticalAttribute); AttributeHelper.HideFromJava(getRealObject); tb.DefineMethodOverride(getRealObject, JVM.Import(typeof(IObjectReference)).GetMethod("GetRealObject")); CodeEmitter ilgen = CodeEmitter.Create(getRealObject); ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ret); ilgen.DoEmit(); }
private static void AddReadResolve(DynamicTypeWrapper wrapper, TypeBuilder tb) { MethodWrapper mw = wrapper.GetMethodWrapper("readResolve", "()Ljava.lang.Object;", false); if (mw != null && !wrapper.IsSubTypeOf(iobjectreference)) { tb.AddInterfaceImplementation(JVM.Import(typeof(IObjectReference))); MethodBuilder getRealObject = tb.DefineMethod("IObjectReference.GetRealObject", MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final, Types.Object, new Type[] { JVM.Import(typeof(StreamingContext)) }); getRealObject.SetCustomAttribute(securityCriticalAttribute); AttributeHelper.HideFromJava(getRealObject); tb.DefineMethodOverride(getRealObject, JVM.Import(typeof(IObjectReference)).GetMethod("GetRealObject")); CodeEmitter ilgen = CodeEmitter.Create(getRealObject); mw.Link(); if (!wrapper.IsFinal) { // readResolve is only applicable if it exists on the actual type of the object, so if we're a subclass don't call it ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Callvirt, Compiler.getTypeMethod); ilgen.Emit(OpCodes.Ldtoken, wrapper.TypeAsBaseType); ilgen.Emit(OpCodes.Call, Compiler.getTypeFromHandleMethod); CodeEmitterLabel label = ilgen.DefineLabel(); ilgen.EmitBeq(label); ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ret); ilgen.MarkLabel(label); } ilgen.Emit(OpCodes.Ldarg_0); mw.EmitCall(ilgen); ilgen.Emit(OpCodes.Ret); ilgen.DoEmit(); } }
private static void AddGetObjectData(TypeBuilder tb) { tb.AddInterfaceImplementation(JVM.Import(typeof(ISerializable))); MethodBuilder getObjectData = tb.DefineMethod("GetObjectData", MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.NewSlot, null, new Type[] { JVM.Import(typeof(SerializationInfo)), JVM.Import(typeof(StreamingContext)) }); getObjectData.SetCustomAttribute(securityCriticalAttribute); AttributeHelper.HideFromJava(getObjectData); getObjectData.AddDeclarativeSecurity(SecurityAction.Demand, psetSerializationFormatter); tb.DefineMethodOverride(getObjectData, JVM.Import(typeof(ISerializable)).GetMethod("GetObjectData")); CodeEmitter ilgen = CodeEmitter.Create(getObjectData); ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldarg_1); TypeWrapper serializationHelper = ClassLoaderWrapper.LoadClassCritical("ikvm.internal.Serialization"); MethodWrapper mw = serializationHelper.GetMethodWrapper("writeObject", "(Ljava.lang.Object;Lcli.System.Runtime.Serialization.SerializationInfo;)V", false); mw.Link(); mw.EmitCall(ilgen); ilgen.Emit(OpCodes.Ret); ilgen.DoEmit(); }