Example #1
0
        public void TestIlInstructionReader()
        {
            Type[] args = { typeof(string), typeof(int) };


            var opCodeFields = typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static);

            ILOpCodeValues parseResult = ILOpCodeValues.Nop;

            foreach (var field in opCodeFields)
            {
                var OpCode = (OpCode)field.GetValue(null);

                var name       = field.Name;
                var lookup     = Enum.TryParse(name, out parseResult);
                var shortValue = unchecked ((short)parseResult);
                if (shortValue == 254)
                {
                    continue;                    //Prefix 1 is used to indicate a two byte instruction.
                }
                Assert.IsTrue(OpCode.Value == shortValue);

                var il       = CompileMethod(OpCode);
                var ilStream = ILInstructionReader.FromByteCode(il);
                var first    = ilStream.First();
                Assert.IsTrue(first.OpCode == OpCode);
                Assert.IsTrue(first.OpCode.Value == shortValue);
            }
        }
Example #2
0
        public void TestEmitString()
        {
            Func <string> tst      = () => "hello";
            Func <int>    tstToken = () =>
            {
                var tstMethod   = tst.Method;
                var methodBytes = tstMethod.GetMethodBody().GetILAsByteArray();
                var ilStream    = ILInstructionReader.FromByteCode(tstMethod.GetMethodBody().GetILAsByteArray());
                return((int)ilStream[0].Arg);
            };
            int stringToken = tstToken();

            var expected = tst();
            var builder  = new ILInstructionBuilder();

            builder.Write(OpCodes.Ldstr, stringToken);
            builder.Write(OpCodes.Ret);
            var ilMethod = new ILMethod(MethodBase.GetCurrentMethod().Name, expected.GetType());

            ilMethod.AddInstructions(builder.Instructions.ToArray());
            ilMethod.Module = this.GetType().Module;
            var method = ilMethod.Compile();
            var actual = method.Invoke(null, Type.EmptyTypes);

            Assert.IsTrue((string)actual == expected, $"Actual: {actual}\r\nExpected:{expected}");
        }
 protected List <ILInstruction> GetIlInstructions(MethodInfo method)
 => ILInstructionReader.FromByteCode(method.GetMethodBody().GetILAsByteArray());