• 静态与动态加载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); 
  • 相关阅读:
    [整理III]微软等数据结构+算法面试100题[最新第61-80题]
    横空出世,席卷互联网--评微软等公司数据结构+算法面试100题
    SQL Server2008创建约束图解
    sqlserver2008中如何用右键可视化的设置外键
    SQL的主键和外键约束
    Visual Basic|VB 6.0中文版
    java 用eclipse j2ee写的servlet 程序,WEB-INF下的配置文件web.xml在哪啊?谢谢!
    SQL Server数据的导入导出
    MySQL命令行导出数据库
    VS2010数据库连接问题
  • 原文地址:https://www.cnblogs.com/lidabo/p/2848728.html
Copyright © 2020-2023  润新知