静态与动态加载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.h // 声明函数 int _stdcall Add(int a,int b); 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.pp // 声明实现 #include "MyDll.h" int _stdcall Add(int a,int b) { return a+b; } int _stdcall Sub(int a,int b) { return a-b; }

 

MyDll.def

  1. ; MyDll为工程名 
  2. LIBRARY MyDll 
  3. ; 在这里声明需要导出的函数 
  4. EXPORTS 
  5. Add 
  6. Sub 
; MyDll为工程名 LIBRARY MyDll ; 在这里声明需要导出的函数 EXPORTS Add 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); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值