温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

dll的弱引用和强引用

发布时间:2020-07-23 17:54:19 来源:网络 阅读:281 作者:xiesiyuana 栏目:开发技术

先描述下dll的创建方法


Test.h和Test.cpp

#pragma  once  #ifdef __COMMON #define __COMMON_EXPORT __declspec(dllexport) #else #define __COMMON_EXPORT __declspec(dllimport) #endif	   extern "C" __COMMON_EXPORT int __cdecl testFunc1(int a,int b);  class __COMMON_EXPORT  MyClass{ public: 	int addFunc(int a,int b); };

Test.cpp

#include "test.h"  int testFunc2(int a,int b){ 	return a+b; }   int  testFunc1(int a,int b){ 	return testFunc2(a,b); }   int MyClass::addFunc(int a,int b){ 	return a+b; }

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


使用方法,新建工程

#include <iostream> #include <Windows.h> #include <WinBase.h>  #include "../CommonDll/test.h" using namespace std;  #pragma comment(lib,"CommonDll")   int main(){  	//弱引用dll,弱引用dll不能使用导出的类 //	HMODULE module=LoadLibraryA("CommonDll.dll"); //	typedef int (*func)(int,int); //	func f=(func)GetProcAddress(module,"testFunc1");  	//强引用dll 	int a=testFunc1(2,5); 	cout<<a<<endl; 	MyClass cat; 	cout<<cat.addFunc(6,7)<<endl; } 

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

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


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



#ifdef __COMMON #define __COMMON_EXPORT __declspec(dllexport) #else #define __COMMON_EXPORT __declspec(dllimport) #endif	

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

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


查看更多



向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI