zoukankan      html  css  js  c++  java
  • 静态与动态加载Dll [示例代码]

    1、DLL源代码

    MyDll.h

    1. ////////////////////////////////////////////////////////////////////////// 
    2. // MyDll.h 
    3. // 声明函数 
    4. int _stdcall Add(int a,int b); 
    5. int _stdcall Sub(int a,int b); 

    MyDll.cpp

    1. ////////////////////////////////////////////////////////////////////////// 
    2. // MyDll.pp 
    3. // 声明实现 
    4. #include "MyDll.h" 
    5. int _stdcall Add(int a,int b) 
    6.     return a+b; 
    7. int _stdcall Sub(int a,int b) 
    8.     return a-b; 

    MyDll.def

    1. ; MyDll为工程名 
    2. LIBRARY MyDll 
    3. ; 在这里声明需要导出的函数 
    4. EXPORTS 
    5. Add 
    6. Sub 

    2、Exe测试代码

    演示动态与静态加载的方法,看代码吧!

    1. void CTestDlg::OnBtnStatic()  
    2.     // TODO: Add your control notification handler code here 
    3.     // 静态加载的方法: 
    4.     // 1、添加头文件 #include "MyDll.h" 
    5.     // 2、引入Lib库  #pragma comment(lib,"MyDll.lib") 
    6.     // 3、这样就可以直接使用MyDll.h中导入的函数 
    7.     CString str; 
    8.     str.Format("静态加载: 1+1=%d 1-1=%d",Add(1,1),Sub(1,1)); 
    9.     MessageBox(str); 
    10. void CTestDlg::OnBtnDynamic()  
    11.     // TODO: Add your control notification handler code here 
    12.     // 动态加载的方法: 
    13.     // 不需要引入头文件与lib文件,仅需要一个dll即可 
    14.     // 注意这里的条约调用约定_stdcall不要忘记加(不然会引会esp出错) 
    15.      
    16.     typedef int (_stdcall *ADDPROC)(int,int); 
    17.     typedef int (_stdcall *SUBPROC)(int,int); 
    18.     HINSTANCE handle; 
    19.     handle = LoadLibrary("MyDll.dll"); 
    20.     if(handle) 
    21.     { 
    22.         // GetProcAddress第二个参数有两种方法: 
    23.         // 1、通过DLL中的函数名 
    24.         // 2、通过Depend工具中Ordinal索引值来查看 
    25.         ADDPROC MyAdd = (ADDPROC)GetProcAddress(handle,"Add"); 
    26.         SUBPROC MySub = (ADDPROC)GetProcAddress(handle,MAKEINTRESOURCE(2)); 
    27.         if( !MyAdd ) 
    28.         { 
    29.             MessageBox("函数Add地址获取失败!"); 
    30.             return
    31.         } 
    32.         if( !MySub ) 
    33.         { 
    34.             MessageBox("函数Sub地址获取失败!"); 
    35.             return
    36.         } 
    37.         CString str; 
    38.         str.Format("动态加载: 1+1=%d 1-1=%d",MyAdd(1,1),MySub(1,1)); 
    39.         MessageBox(str); 
    40.     } 
    41.     FreeLibrary(handle); 
  • 相关阅读:
    AJAX
    前端上传文件 后端PHP获取文件
    PHP基础语法
    JS错误记录
    JS学习笔记
    python利用xlrd读取excel文件始终报错原因
    安装xlwt和xlrd
    编程菜鸟的日记-Linux无处不在
    编程菜鸟的日记-《软件测试》Ron Patton著-读书笔记
    编程菜鸟的日记-初学尝试编程-C++ Primer Plus 第6章编程练习9
  • 原文地址:https://www.cnblogs.com/lidabo/p/2848728.html
Copyright © 2011-2022 走看看