dll的弱引用和强引用

先描述下dll的创建方法


Test.h和Test.cpp

  1. #pragma  once  
  2.   
  3. #ifdef __COMMON  
  4. #define __COMMON_EXPORT __declspec(dllexport)  
  5. #else  
  6. #define __COMMON_EXPORT __declspec(dllimport)  
  7. #endif    
  8.   
  9.   
  10. extern "C" __COMMON_EXPORT int __cdecl testFunc1(int a,int b);  
  11.   
  12. class __COMMON_EXPORT  MyClass{  
  13. public:  
  14.     int addFunc(int a,int b);  
  15. };  

Test.cpp

  1. #include "test.h"  
  2.   
  3. int testFunc2(int a,int b){  
  4.     return a+b;  
  5. }  
  6.   
  7.  int  testFunc1(int a,int b){  
  8.     return testFunc2(a,b);  
  9. }  
  10.   
  11.   
  12. int MyClass::addFunc(int a,int b){  
  13.     return a+b;  
  14. }  

生成了Common.dll和Common.lib文件


使用方法,新建工程

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. #include <Windows.h>  
  3. #include <WinBase.h>  
  4.   
  5. #include "../CommonDll/test.h"  
  6. using namespace std;  
  7.   
  8. #pragma comment(lib,"CommonDll")  
  9.   
  10.   
  11. int main(){  
  12.   
  13.     //弱引用dll,弱引用dll不能使用导出的类  
  14. //  HMODULE module=LoadLibraryA("CommonDll.dll");  
  15. //  typedef int (*func)(int,int);  
  16. //  func f=(func)GetProcAddress(module,"testFunc1");  
  17.   
  18.     //强引用dll  
  19.     int a=testFunc1(2,5);  
  20.     cout<<a<<endl;  
  21.     MyClass cat;  
  22.     cout<<cat.addFunc(6,7)<<endl;  
  23. }  

对于dll的引用,有两种方法

第一种方法:使用LoadLibrary和GetProcAddress配合,这种方法称为弱引用,其优点是 可以跨编译器使用,也就是用vs2008编译的dll,使用时候,到vs2010下代码可以直接用。  缺点是 不能使用导出的类


第二种方法:引用CommonDll.lib来引用,这种方法的优缺点就和 弱应用刚好互补,优点是使用方便,可以使用导出的类,缺点是 vs2008编译出来的lib,到vs2010或者其他版本的编译器就有可能不能使用。



  1. #ifdef __COMMON  
  2. #define __COMMON_EXPORT __declspec(dllexport)  
  3. #else  
  4. #define __COMMON_EXPORT __declspec(dllimport)  
  5. #endif    

这种方法对于强引用来说,在编译CommonDll.dll时候,在预处理器里定义了宏__COMMON,这样就会导出对应的函数和类

当引用CommonDll.lib时候,没有定义__Common,__COMMON_EXPORT就成了dllimport,它就会把lib导出的函数导入

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值