zoukankan      html  css  js  c++  java
  • 动态调用Win32 Function(API)

    动态调用Win32 Function(API)
     
      在很多场合,我们需要动态进行平台调用。
      .Net 平台下不同于 Win32,无法直接通过函数指针调用函数,并且对于 DLL 也只能事先声明函数签名后才能调用。

      下面是动态平台调用的解决方案
      1.通过 Win32 DLL 进行平台调用
        缺点 : 无法和.Net进行交互。
        参看 : 无

      2.通过定义动态程序集声明函数签名并反射调用平台调用
        缺点 : 效率低下,资源占用过大,并且无法释放动态程序集所占用的资源,如果使用AppDomain,虽然可以释放动态程序集,但是却会占用更多资源。
        参看 : 无

      3.通过定义动态程序集生成全局方法,在全局方法中使用 MSIL 指令调用函数指针。
        缺点 : 除了效率可以接受外,其他缺点同上。
        参看 : http://blog.csdn.net/pansiom/archive/2006/01/01/568096.aspx

      4.使用 System.Runtime.InteropServices.Marshal类的GetDelegateForFunctionPointer方法根据委托来动态调用函数指针
        缺点 : 必须现定义好委托才可以调用函数指针,失去了"动态"的效果
        参看 : http://www.cnblogs.com/rick/archive/2006/07/13/449849.aspx

      5.在 DynamicMethod 中使用 MSIL 指令调用函数指针
        缺点 : 几乎没有
        参看 : 本文内容

      在这里,我们就是使用 DynamicMethod 来完成动态平台调用,他的好处主要有以下几个:
      1.轻量:占用很少的资源,当不使用 DynamicMethod 时,可以释放资源。
      2.效率:IronPython 何以比 CPython 高效?就是因为借助了 DynamicMethod 和 JIT。
      3.灵活:你几乎可以使动态调用任何定义的Win32 Function,无论是调用约定不同还是参数中有结构。

      MSDN中对 DynamicMethod 的描述:
        可以使用 DynamicMethod 类在运行时生成和执行方法,而不必生成动态程序集和动态类型来包含该方法。动态方法是生成和执行少量代码的最有效方式。

    实例代码:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Zealic.Windows;

    namespace ConsoleApplication1
    {
        
    class Program
        {
            
    static void Main(string[] args)
            {
                
    //测试1
                DynamicLibrary hilib = new DynamicLibrary("hi.dll");
                NativeMethodBuilder hiBuilder 
    = new NativeMethodBuilder();
                NativeMethod method 
    = hiBuilder.MakeMethod(hilib, "func");
                Console.WriteLine(
    "请关闭弹出的对话框 'Hille'");
                method.Invoke();
                hilib.Free();

                
    //测试2
                DynamicLibrary krnlib = new DynamicLibrary("kernel32.dll");
                NativeMethodBuilder beepBuilder 
    = new NativeMethodBuilder();
                beepBuilder.ParameterLength 
    = 2;
                beepBuilder.SetParameterInfo(
    0typeof(int));
                beepBuilder.SetParameterInfo(
    1typeof(int));
                method 
    = beepBuilder.MakeMethod(krnlib,"Beep");
                Console.WriteLine(
    "听,你的机器在尖叫!");
                method.Invoke(
    10001000);
                Console.WriteLine(
    "按任意键退出!");
                Console.ReadKey(
    true);
            }
        }
    }



      说这么多,代码才是最实在的 :
      点击下载代码和示例

    引用:http://www.cnblogs.com/zealic/archive/2007/02/28/658836.html

  • 相关阅读:
    codevs 1115 开心的金明
    POJ 1125 Stockbroker Grapevine
    POJ 2421 constructing roads
    codevs 1390 回文平方数 USACO
    codevs 1131 统计单词数 2011年NOIP全国联赛普及组
    codevs 1313 质因数分解
    洛谷 绕钉子的长绳子
    洛谷 P1276 校门外的树(增强版)
    codevs 2627 村村通
    codevs 1191 数轴染色
  • 原文地址:https://www.cnblogs.com/gxlinhai/p/659511.html
Copyright © 2011-2022 走看看