public static DynamicMethodBody InsertBefore
            (this MethodDefinition that)
        {
            var worker = that.Body.GetILProcessor();

            var firstInstruction = worker.Body.Instructions[0];
            var emitter = new CecilILEmitter(
                that.Module.Assembly,
                worker,
                inst => worker.InsertBefore(firstInstruction, inst));

            var dinfo = new DynamicMethodInfo(emitter);
            that.LoadArgsTo(dinfo);

            return dinfo.Body;
        }
        public static DynamicMethodBody ReplaceWith
            (this MethodDefinition that)
        {
            var worker = that.Body.GetILProcessor();
            var emitter = new CecilILEmitter(
                that.Module.Assembly,
                worker,
                worker.Append
                );

            worker.Body.Instructions.Clear();

            var dinfo = new DynamicMethodInfo(emitter);
            that.LoadArgsTo(dinfo);

            return dinfo.Body;
        }
Example #3
0
        public static DynamicMethodBody InsertBeforeRet
            (this MethodDefinition that)
        {
            ILProcessor worker = that.Body.GetILProcessor();
            var aggregator = new EmittersAggregator();
            foreach (var instruction in worker.Body.Instructions)
            {
                if (instruction.OpCode == OpCodes.Ret)
                {
                    Instruction instruction1 = instruction;
                    var emitter = new CecilILEmitter(
                        that.Module.Assembly,
                        worker,
                        inst => worker.InsertBefore(instruction1, inst));
                    aggregator.Emitters.Add(emitter);
                }
            }
            var dinfo = new DynamicMethodInfo(aggregator);
            that.LoadArgsTo(dinfo);

            return dinfo.Body;
        }
        public static DynamicMethodBody NewMethod
            (this TypeDefinition that, string methodName, MethodAttributes methodAttributes, Type returnType, AssemblyDefinition assembly)
        {
            var typeReference = assembly.MainModule.Import(returnType);

            var method = new MethodDefinition(methodName, methodAttributes, typeReference);

            var worker = method.Body.GetILProcessor();

            var emitter = new CecilILEmitter(
                assembly,
                worker,
                method.Body.Instructions.Add);

            var dinfo = new DynamicMethodInfo(emitter);
            method.LoadArgsTo(dinfo);

            that.Methods.Add(method);

            return dinfo.Body;
        }