コード例 #1
0
        private string CreateSourceName()
        {
            StackTrace st = new StackTrace(this, fNeedFileInfo: false);

            if (st.FrameCount > 0)
            {
                StackFrame sf     = st.GetFrame(0);
                MethodBase method = sf.GetMethod();

                Module module = method.Module;

                RuntimeModule rtModule = module as RuntimeModule;

                if (rtModule == null)
                {
                    System.Reflection.Emit.ModuleBuilder moduleBuilder = module as System.Reflection.Emit.ModuleBuilder;
                    if (moduleBuilder != null)
                    {
                        rtModule = moduleBuilder.InternalModule;
                    }
                    else
                    {
                        throw new ArgumentException(SR.Argument_MustBeRuntimeReflectionObject);
                    }
                }

                return(rtModule.GetRuntimeAssembly().GetSimpleName());
            }

            return(null);
        }
コード例 #2
0
 /// <summary>
 /// Creates the dynamic assembly and associated module using the referenced app domain
 /// </summary>
 /// <param name="domain"></param>
 private void MakeModule(AppDomain domain)
 {
     if (_module == null)
     {
         _dynAss = domain.DefineDynamicAssembly(new System.Reflection.AssemblyName(AssemblyName), System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave);
         _module = _dynAss.DefineDynamicModule(AssemblyName, AssemblyName + ".dll");
     }
 }
コード例 #3
0
        /// <summary>
        /// Construtor padrão.
        /// </summary>
        private ClassFactory()
        {
            var name     = new System.Reflection.AssemblyName("DynamicClasses");
            var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, System.Reflection.Emit.AssemblyBuilderAccess.Run);

                        #if ENABLE_LINQ_PARTIAL_TRUST
            new ReflectionPermission(PermissionState.Unrestricted).Assert();
#endif
            try
            {
                module = assembly.DefineDynamicModule("Module");
            }
            finally
            {
                                #if ENABLE_LINQ_PARTIAL_TRUST
                PermissionSet.RevertAssert();
#endif
            }
            classes = new Dictionary <Signature, Type>();
            rwLock  = new System.Threading.ReaderWriterLock();
        }
コード例 #4
0
        static void Main(string[] args)
        {
            System.Reflection.Emit.AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new System.Reflection.AssemblyName("Patch"), System.Reflection.Emit.AssemblyBuilderAccess.Run, (string)null);
            System.Reflection.Emit.ModuleBuilder   moduleBuilder   = assemblyBuilder.DefineDynamicModule("module");
            System.Reflection.Emit.TypeBuilder     typeBuilder     = moduleBuilder.DefineType("program", System.Reflection.TypeAttributes.Public);
            System.Reflection.Emit.MethodBuilder   methodBuilder   = typeBuilder.DefineMethod("simpleSub", System.Reflection.MethodAttributes.Static | System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.HideBySig, typeof(int), new Type[] { typeof(int), typeof(int) });

            List <MSIL.Instruction> patchedMethod = new List <MSIL.Instruction>();

            foreach (MSIL.Instruction instruction in MSIL.ReadMethod(typeof(Program).GetMethod("simpleAdd")))
            {
                if (instruction.OpCode == System.Reflection.Emit.OpCodes.Add)
                {
                    instruction.OpCode = System.Reflection.Emit.OpCodes.Sub;
                }
                patchedMethod.Add(instruction);
            }
            MSIL.EmitMethod(patchedMethod, methodBuilder);

            Type type = typeBuilder.CreateType();

            System.Reflection.MethodInfo pathedMethod = type.GetMethod("simpleSub");
            System.Console.WriteLine("result: " + (int)pathedMethod.Invoke(null, new object[] { 3, 1 }));
        }
 public SymbolWriterImpl(System.Reflection.Emit.ModuleBuilder mb)
 {
 }
コード例 #6
0
 internal QCallModule(IntPtr pObject, System.Reflection.Emit.ModuleBuilder module)
 {
     m_ptr    = pObject;
     m_module = module.GetNativeHandle().GetUnderlyingNativeHandle();
 }
コード例 #7
0
        /// <summary>
        /// Dynamic genereate collection instance specify object map , new instance has
        /// fields member , those fields's name is key of map , field value is value of map.
        /// </summary>
        /// <param name="objs">object maps</param>
        /// <param name="BaseType">base type</param>
        /// <returns>dynamic genereate instance</returns>
        public static object CreateAllObject(System.Collections.Hashtable objs, System.Type BaseType)
        {
            if (objs == null)
            {
                return(null);
            }
            System.Reflection.AssemblyName an = new System.Reflection.AssemblyName();
            an.Name = "XDesignerLib_AllObject_Assembly";
            System.Reflection.Emit.AssemblyBuilder ab = System.AppDomain.CurrentDomain.DefineDynamicAssembly(
                an,
                System.Reflection.Emit.AssemblyBuilderAccess.Run);
            System.Reflection.Emit.ModuleBuilder mb = ab.DefineDynamicModule("AllObjectModule");
            System.Reflection.Emit.TypeBuilder   tb = null;
            if (BaseType == null)
            {
                tb = mb.DefineType(
                    "AllObject" + System.Environment.TickCount,
                    System.Reflection.TypeAttributes.Public);
            }
            else
            {
                tb = mb.DefineType(
                    "AllObject" + System.Environment.TickCount,
                    System.Reflection.TypeAttributes.Public, BaseType);
            }
            System.Collections.ArrayList Fields = new System.Collections.ArrayList();
            foreach (string key in objs.Keys)
            {
                if (key != null && key.Length != 0)
                {
                    bool bolFind = false;
                    foreach (System.Reflection.FieldInfo f in Fields)
                    {
                        if (string.Compare(f.Name, key, true) == 0)
                        {
                            bolFind = true;
                            break;
                        }
                    }
                    if (bolFind == false)
                    {
                        Fields.Add(tb.DefineField(
                                       key,
                                       typeof(object),
                                       System.Reflection.FieldAttributes.Public));
                    }
                }
            }//foreach
            System.Type t   = tb.CreateType();
            object      obj = System.Activator.CreateInstance(t);

            foreach (System.Reflection.FieldInfo field in Fields)
            {
                t.InvokeMember(
                    field.Name,
                    System.Reflection.BindingFlags.SetField,
                    null,
                    obj,
                    new object[] { objs[field.Name] });
            }//foreach
            return(obj);
        }
コード例 #8
0
        static ParserCompiler()
        {
            var assemblyBuilder = System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly(new System.Reflection.AssemblyName("PageOfBob.Parsing.Gen"), System.Reflection.Emit.AssemblyBuilderAccess.Run);

            Builder = assemblyBuilder.DefineDynamicModule("PageOfBob.Parsing.Mod");
        }
コード例 #9
0
        // *** CONSTRUCTION *** //

        #region Constructor
        public Manager()
        {
            #region Create Member Objects
            GameClasses                 = new Dictionary <string, Type>();
            GameAttributes              = new Dictionary <string, GameAttribute>();
            AppearanceAttributes        = new Dictionary <string, AppearanceAttribute>();
            Environment                 = new Compiler.Environment();
            PieceTypeLibrary            = new PieceTypeLibrary();
            EngineLibrary               = new EngineLibrary();
            InternalEngine              = new EngineConfiguration();
            InternalEngine.FriendlyName = "ChessV";
            InternalEngine.InternalName = "ChessV 2.2 RC1";
            #endregion

            #region Add ChessV Data Types to Environment
            Environment.AddSymbol("MoveCapability", typeof(MoveCapability));
            Environment.AddSymbol("Direction", typeof(Direction));
            Environment.AddSymbol("BitBoard", typeof(BitBoard));
            Environment.AddSymbol("Rule", typeof(Rule));
            Environment.AddSymbol("Game", typeof(Game));
            Environment.AddSymbol("PieceType", typeof(PieceType));
            Environment.AddSymbol("Piece", typeof(Piece));
            Environment.AddSymbol("Location", typeof(Location));
            #endregion

            #region Load Internal Games

            // *** LOAD INTERNAL GAMES *** //

            //	Load games and piece types from the main ChessV.Base module
            Module module = typeof(Game).Module;
            loadPieceTypesFromModule(module);
            loadGamesFromModule(module);

            //	Load games and piece types from the ChessV.Games DLL
            string   moduleName    = module.FullyQualifiedName;
            string   modulePath    = moduleName.Substring(0, Math.Max(moduleName.LastIndexOf('\\'), moduleName.LastIndexOf('/')) + 1);
            string   gamesDllName  = modulePath + "ChessV.Games.dll";
            Assembly gamesAssembly = Assembly.UnsafeLoadFrom(gamesDllName);
            foreach (Module gamesModule in gamesAssembly.GetModules())
            {
                loadPieceTypesFromModule((Module)gamesModule);
                loadGamesFromModule((Module)gamesModule);
                loadPieceTypePropertyAttributesFromModule((Module)gamesModule);
                loadRulesFromModule((Module)gamesModule);
                loadEvaluationsFromModule((Module)gamesModule);
            }
            #endregion

            #region Load Games from Include Folder

            // *** LOAD GAMES FROM INCLUDE FOLDER *** //

            //	Search for the include folder.  We provide some flexibility
            //	regarding where this path is located
            string currPath    = Directory.GetCurrentDirectory();
            string includePath = Path.Combine(currPath, "Include");
            if (!Directory.Exists(includePath))
            {
                int iIndex = currPath.LastIndexOf("ChessV");
                if (iIndex > 0)
                {
                    iIndex = currPath.IndexOf(Path.DirectorySeparatorChar, iIndex);
                    if (iIndex > 0)
                    {
                        currPath    = currPath.Remove(iIndex);
                        includePath = Path.Combine(currPath, "Include");
                        if (!Directory.Exists(includePath))
                        {
                            currPath = Directory.GetCurrentDirectory();
                            iIndex   = currPath.IndexOf("ChessV");
                            if (iIndex > 0)
                            {
                                iIndex = currPath.IndexOf(Path.DirectorySeparatorChar, iIndex);
                                if (iIndex > 0)
                                {
                                    currPath    = currPath.Remove(iIndex);
                                    includePath = Path.Combine(currPath, "Include");
                                }
                            }
                        }
                    }
                }
            }

            if (Directory.Exists(includePath))
            {
                AppDomain    myDomain     = Thread.GetDomain();
                AssemblyName assemblyName = new AssemblyName();
                assemblyName.Name = "DynamicGamesAssembly";
                System.Reflection.Emit.AssemblyBuilder assemblyBuilder = myDomain.DefineDynamicAssembly(assemblyName, System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave);
                System.Reflection.Emit.ModuleBuilder   dynamicModule   = assemblyBuilder.DefineDynamicModule("ChessVDynamicGames");
                Compiler.Compiler compiler     = new Compiler.Compiler(assemblyBuilder, dynamicModule, Environment);
                string[]          includeFiles = Directory.GetFiles(includePath, "*.cvc");
                foreach (string file in includeFiles)
                {
                    TextReader reader = new StreamReader(file);
                    compiler.ProcessInput(reader);
                    reader.Close();
                }
                foreach (KeyValuePair <string, Type> pair in compiler.GameTypes)
                {
                    GameClasses.Add(pair.Key, pair.Value);
                    GameAttributes.Add(pair.Key, compiler.GameAttributes[pair.Key]);
                    if (compiler.GameAppearances.ContainsKey(pair.Key))
                    {
                        AppearanceAttributes.Add(pair.Key, compiler.GameAppearances[pair.Key]);
                    }
                }
            }
            #endregion
        }
コード例 #10
0
        static System.Type GenerateFunctionType(System.Type functionType)
        {
            SQLiteFunctionAttribute attribute = AttributeExtensions.GetCustomAttribute <SQLiteFunctionAttribute>(functionType);

            if (attribute == null)
            {
                return(null);
            }
            bool        ex       = TypeExtensions.IsInheritFrom(functionType, typeof(SQLiteFunctionEx)) || attribute.Type == FunctionTypes.Collation;
            FastWrapper baseType = GetType(ex ? "System.Data.SQLite.SQLiteFunctionEx" : "System.Data.SQLite.SQLiteFunction");


            System.Reflection.AssemblyName assemblyName = new System.Reflection.AssemblyName(functionType.Namespace + ".DynamicClass_" + functionType.Name);
            System.Reflection.Emit.AssemblyBuilderAccess accemblyBuilderAccess =
#if netcore
                System.Reflection.Emit.AssemblyBuilderAccess.Run;
#else
                IsDebug
                    ? System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave
                    : System.Reflection.Emit.AssemblyBuilderAccess.Run;
#endif
            System.Reflection.Emit.AssemblyBuilder assembly =
#if netcore
                System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly(assemblyName, accemblyBuilderAccess);
#else
                System.AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, accemblyBuilderAccess);
#endif
#if !netcore
            bool canSave = (accemblyBuilderAccess == System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave || accemblyBuilderAccess == System.Reflection.Emit.AssemblyBuilderAccess.Save);
#endif
            System.Reflection.Emit.ModuleBuilder module =
#if netcore
                assembly.DefineDynamicModule(assemblyName.Name);
#else
                canSave
                    ? assembly.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll")
                    : assembly.DefineDynamicModule(assemblyName.Name);//, n.Name + ".dll");
#endif
            System.Reflection.Emit.TypeBuilder type = module.DefineType(
                assemblyName.Name + ".DynamicClass",
                System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Sealed | System.Reflection.TypeAttributes.AutoClass,
                baseType.Type,
                System.Type.EmptyTypes);

            {
                FastWrapper wrapper = GetType("System.Data.SQLite.SQLiteFunctionAttribute");
                System.Reflection.PropertyInfo[] properties = new System.Reflection.PropertyInfo[] {
                    wrapper.Type.GetProperty("Name"),
                    wrapper.Type.GetProperty("Arguments"),
                    wrapper.Type.GetProperty("FuncType"),
                };
                System.Reflection.Emit.CustomAttributeBuilder attributeBuilder = new System.Reflection.Emit.CustomAttributeBuilder(wrapper.Type.GetConstructor(System.Type.EmptyTypes), new object[0],
                                                                                                                                   properties, new object[] {
                    attribute.Name,
                    attribute.Arguments,
                    TypeExtensions.Convert(attribute.Type, GetType("System.Data.SQLite.FunctionType").Type),
                });
                type.SetCustomAttribute(attributeBuilder);
            }
            System.Reflection.Emit.FieldBuilder _o = type.DefineField("_o", functionType, FieldAttributes.Private);

            {
                System.Reflection.Emit.ConstructorBuilder ctor = type.DefineConstructor(
                    System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.SpecialName | System.Reflection.MethodAttributes.RTSpecialName,
                    System.Reflection.CallingConventions.HasThis,
                    System.Type.EmptyTypes);
                System.Reflection.Emit.ILGenerator il = ctor.GetILGenerator();
                il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                il.Emit(System.Reflection.Emit.OpCodes.Call, baseType.Type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, System.Type.EmptyTypes, new System.Reflection.ParameterModifier[0]));
                il.Emit(System.Reflection.Emit.OpCodes.Nop);
                il.Emit(System.Reflection.Emit.OpCodes.Nop);
                il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                il.Emit(System.Reflection.Emit.OpCodes.Newobj, functionType.GetConstructor(System.Type.EmptyTypes));
                il.Emit(System.Reflection.Emit.OpCodes.Stfld, _o);
                il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                il.Emit(System.Reflection.Emit.OpCodes.Ldfld, _o);
                il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                if (attribute.Type == FunctionTypes.Collation)
                {
                    il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_1);
                }
                else
                {
                    il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0);
                }
                il.Emit(System.Reflection.Emit.OpCodes.Callvirt, functionType.GetMethod("Init", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, new System.Type[] {
                    typeof(object), typeof(bool)
                }, null));
                il.Emit(System.Reflection.Emit.OpCodes.Nop);
                il.Emit(System.Reflection.Emit.OpCodes.Ret);
            }
            CreateMethodDelegate createMethod = (methodInfo, action) => {
                System.Reflection.ParameterInfo[] parameters = methodInfo.GetParameters();
                System.Type[] parameterTypes = new System.Type[parameters.Length];
                for (int i = 0; i < parameters.Length; i++)
                {
                    parameterTypes[i] = parameters[i].ParameterType;
                }
                System.Reflection.Emit.MethodBuilder method = type.DefineMethod(methodInfo.Name, (methodInfo.Attributes | MethodAttributes.NewSlot) ^ MethodAttributes.NewSlot, methodInfo.CallingConvention, methodInfo.ReturnType, parameterTypes);
                for (int i = 0; i < parameters.Length; i++)
                {
                    System.Reflection.Emit.ParameterBuilder parameter = method.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name);
                    if (parameters[i].IsOptional)
                    {
                        if (parameters[i].ParameterType.IsValueType && parameters[i].DefaultValue == null)
                        {
                            continue;
                        }
                        parameter.SetConstant(parameters[i].DefaultValue);
                    }
                }
                System.Reflection.Emit.ILGenerator il = method.GetILGenerator();
                bool hasReturn = (methodInfo.ReturnType != typeof(void));
                System.Reflection.Emit.LocalBuilder @return = null;
                if (hasReturn)
                {
                    @return = il.DeclareLocal(methodInfo.ReturnType);
                }
                il.Emit(System.Reflection.Emit.OpCodes.Nop);
                il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                il.Emit(System.Reflection.Emit.OpCodes.Ldfld, _o);
                action(functionType.GetMethod(methodInfo.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance), method, il);
                il.Emit(System.Reflection.Emit.OpCodes.Ret);
            };
            if (attribute.Type == FunctionTypes.Scalar)
            {
                createMethod(baseType.Type.GetMethod("Invoke"), (methodInfo, method, il) => {
                    il.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                    il.Emit(System.Reflection.Emit.OpCodes.Callvirt, methodInfo);
                    il.Emit(System.Reflection.Emit.OpCodes.Stloc_0);
                    System.Reflection.Emit.Label label = il.DefineLabel();
                    il.Emit(System.Reflection.Emit.OpCodes.Br_S, label);
                    il.MarkLabel(label);
                    il.Emit(System.Reflection.Emit.OpCodes.Ldloc_0);
                });
            }
            else if (attribute.Type == FunctionTypes.Collation)
            {
                createMethod(baseType.Type.GetMethod("Compare"), (methodInfo, method, il) => {
                    il.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                    il.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                    il.Emit(System.Reflection.Emit.OpCodes.Callvirt, methodInfo);
                    il.Emit(System.Reflection.Emit.OpCodes.Stloc_0);
                    System.Reflection.Emit.Label label = il.DefineLabel();
                    il.Emit(System.Reflection.Emit.OpCodes.Br_S, label);
                    il.MarkLabel(label);
                    il.Emit(System.Reflection.Emit.OpCodes.Ldloc_0);
                });
            }
            else
            {
                createMethod(baseType.Type.GetMethod("Final"), (methodInfo, method, il) => {
                    il.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                    il.Emit(System.Reflection.Emit.OpCodes.Callvirt, methodInfo);
                    il.Emit(System.Reflection.Emit.OpCodes.Stloc_0);
                    System.Reflection.Emit.Label label = il.DefineLabel();
                    il.Emit(System.Reflection.Emit.OpCodes.Br_S, label);
                    il.MarkLabel(label);
                    il.Emit(System.Reflection.Emit.OpCodes.Ldloc_0);
                });
                createMethod(baseType.Type.GetMethod("Step"), (methodInfo, method, il) => {
                    il.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                    il.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                    il.Emit(System.Reflection.Emit.OpCodes.Ldarg_3);
                    il.Emit(System.Reflection.Emit.OpCodes.Callvirt, methodInfo);
                    il.Emit(System.Reflection.Emit.OpCodes.Nop);
                });
            }
            {
                System.Reflection.MethodInfo methodInfo_base = baseType.Type.GetMethod("Dispose", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, new System.Type[] { typeof(bool) }, null);
                createMethod(methodInfo_base, (methodInfo, method, il) => {
                    il.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                    il.Emit(System.Reflection.Emit.OpCodes.Callvirt, methodInfo);
                    il.Emit(System.Reflection.Emit.OpCodes.Nop);
                    il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                    il.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                    il.Emit(System.Reflection.Emit.OpCodes.Call, methodInfo_base);
                    il.Emit(System.Reflection.Emit.OpCodes.Nop);
                });
            }

#if netcore20
            var result = type.CreateTypeInfo();
#else
            var result = type.CreateType();
#endif
#if !netcore
            if (canSave)
            {
                assembly.Save(assemblyName.Name + ".dll");
            }
#endif
            return(result);
        }