DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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); 
posted on   DoubleLi  阅读(330)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示