Exemplo n.º 1
0
        public void TestDynamicMethodEmitCalliBlittable()
        {
            int a = 1, b = 1, result = 2;

            Type returnType = typeof(int);

            var dynamicMethod = new DynamicMethod("F", returnType, new Type[] { typeof(IntPtr), typeof(int), typeof(int) });

            ILGenerator il = dynamicMethod.GetILGenerator();

            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Ldarg_0);
            il.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, returnType, new Type[] { typeof(int), typeof(int) });
            il.Emit(OpCodes.Ret);

            var    del     = new Int32SumStdCall(Int32Sum);
            IntPtr funcPtr = Marshal.GetFunctionPointerForDelegate(del);

            object resultValue = dynamicMethod
                                 .Invoke(null, new object[] { funcPtr, a, b });

            GC.KeepAlive(del);

            Assert.IsType(returnType, resultValue);
            Assert.Equal(result, resultValue);
        }
Exemplo n.º 2
0
        public void TestEmitCalliBlittable()
        {
            int a = 1, b = 1, result = 2;

            ModuleBuilder moduleBuilder = Helpers.DynamicModule();
            TypeBuilder   typeBuilder   = moduleBuilder.DefineType("T", TypeAttributes.Public);
            Type          returnType = typeof(int);

            MethodBuilder methodBuilder = typeBuilder.DefineMethod("F",
                                                                   MethodAttributes.Public | MethodAttributes.Static, returnType, new Type[] { typeof(IntPtr), typeof(int), typeof(int) });

            methodBuilder.SetImplementationFlags(MethodImplAttributes.NoInlining);

            ILGenerator il              = methodBuilder.GetILGenerator();

            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Ldarg_0);
            il.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, returnType, new Type[] { typeof(int), typeof(int) });
            il.Emit(OpCodes.Ret);

            Type dynamicType = typeBuilder.CreateType();

            var    del     = new Int32SumStdCall(Int32Sum);
            IntPtr funcPtr = Marshal.GetFunctionPointerForDelegate(del);

            object resultValue = dynamicType
                                 .GetMethod("F", BindingFlags.Public | BindingFlags.Static)
                                 .Invoke(null, new object[] { funcPtr, a, b });

            GC.KeepAlive(del);

            Assert.IsType(returnType, resultValue);
            Assert.Equal(result, resultValue);
        }