C#动态构造调用原生dll

 public static T Register<T>(string dllName, string methodName, object[] parameters)
        {

            //COM has no Type class, so do the necessary conversions
            Type returnType = typeof(T);

            Type[] parameterTypes = new Type[parameters.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                parameterTypes[i] = parameters[i].GetType();
            }

            if (methodName == "VirtualProtect")
            {
                parameterTypes[parameters.Length - 1] = parameterTypes[parameters.Length - 1].MakeByRefType();
            }

            // Begin to build the dynamic assembly
            AppDomain domain = AppDomain.CurrentDomain;
            AssemblyName name = new System.Reflection.AssemblyName("PInvokeAssembly");
            AssemblyBuilder assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
            ModuleBuilder module = assembly.DefineDynamicModule("PInvokeModule");
            TypeBuilder type = module.DefineType("PInvokeType", TypeAttributes.Public | TypeAttributes.BeforeFieldInit);

            // Define the actual P/Invoke method
            MethodBuilder method = type.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.PinvokeImpl, returnType, parameterTypes);

            // Apply the P/Invoke constructor
            ConstructorInfo ctor = typeof(DllImportAttribute).GetConstructor(new Type[] { typeof(string) });
            CustomAttributeBuilder attr = new System.Reflection.Emit.CustomAttributeBuilder(ctor, new Object[] { dllName });
            method.SetCustomAttribute(attr);

            // Create the temporary type, and invoke the method.
            Type realType = type.CreateType();
            return (T)realType.InvokeMember(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, parameters);

        }

IntPtr lib = Register<IntPtr>("kernel32.dll", "LoadLibrary",
                new object[] { "fake.dll"});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值