现在的位置: 首页 > 综合 > 正文

dll的弱引用和强引用

2013年07月12日 ⁄ 综合 ⁄ 共 1295字 ⁄ 字号 评论关闭

先描述下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导出的函数导入

【上篇】
【下篇】

抱歉!评论已关闭.