示例#1
0
        private static void ImplementMethod(TypeBuilder typeBuilder, DllImportXOptions options)
        {
            var method     = options.Method;
            var parameters = method.GetParameters().Select(x => x.ParameterType).ToArray();
            var callee     = DefinePInvokeMethod(typeBuilder, options);
            var caller     = typeBuilder.DefineMethod(method.Name, MethodAttributes.Virtual, method.ReturnType, parameters);
            var il         = caller.GetILGenerator();

            for (int i = 1, c = parameters.Length; i <= c; i++)
            {
                il.Emit(OpCodes.Ldarg, i);
            }
            il.Emit(OpCodes.Call, callee);
            il.Emit(OpCodes.Ret);

            typeBuilder.DefineMethodOverride(caller, options.Method);
        }
示例#2
0
        public static MethodInfo DefinePInvokeMethod(TypeBuilder typeBuilder, DllImportXOptions options)
        {
            var clrImportType = typeof(DllImportAttribute);
            var ctor          = clrImportType.GetConstructor(new[] { typeof(string) });

            var fields = new[] {
                clrImportType.GetField("EntryPoint"),
                clrImportType.GetField("ExactSpelling"),
                clrImportType.GetField("PreserveSig"),
                clrImportType.GetField("SetLastError"),
                clrImportType.GetField("CallingConvention"),
                clrImportType.GetField("CharSet"),
                clrImportType.GetField("BestFitMapping"),
                clrImportType.GetField("ThrowOnUnmappableChar")
            };

            var fieldValues = new object[] {
                options.EntryPoint,
                options.ExactSpelling,
                options.PreserveSig,
                options.SetLastError,
                options.CallingConvention,
                options.CharSet,
                options.BestFitMapping,
                options.ThrowOnUnmappableChar
            };

            var clrImport = new CustomAttributeBuilder(ctor, new[] { options.DllName }, fields, fieldValues);

            var ifaceMethod = options.Method;
            var parameters  = ifaceMethod.GetParameters();
            var method      = typeBuilder.DefineMethod(
                ifaceMethod.Name,
                MethodAttributes.Private | MethodAttributes.Static,
                ifaceMethod.ReturnType,
                ifaceMethod.GetParameters().Select(x => x.ParameterType).ToArray()
                );

            if (!options.IgnoreAttributes)
            {
                DefineAttributes(ifaceMethod, method);
            }

            method.SetCustomAttribute(clrImport);
            return(method);
        }