VC动态链接库的编写与调用

VC下的非MFC动态链接库学习demo,包括动态调用和静态调用。两者的区别是动态调用依赖win API接口加载dll、获取地址、释放dll句柄。而静态调用是直接调用dll里面的东西。

git地址:http://git.oschina.net/kanakdillon/VC_Dll.git

VC中动态连接库的调用有两种方法,一种是显示链接调用,另外一种是隐式链接调用。

先编写DLL,MyDll.h代码:

#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif

MYDLL_API int Max(int a, int b);
MYDLL_API int Min(int a, int b);
MyDll.cpp:
#include "MyDll.h"

int Max(int a, int b) {
	if(a>b)
		return a;
	else
		return b;
}

int Min(int a, int b) {
	if(a>b)
		return b;
	else
		return a;
}
MyDll.def:
LIBRARY

EXPORTS
	Max
	Min
编写显示链接测试,TestDll.cpp:
//DLL显式链接
#include "iostream"
#include "Windows.h"
using namespace std;
typedef int(*LPFNDLLFUNC)(int, int); //定义一个函数指针类型 类型为int

int main(){

	LPFNDLLFUNC lpfnDllFunc;
	//初始化一个句柄指向目标dll
	HINSTANCE hInst = LoadLibrary("..\\Debug\\VC_Dll.dll");

	if(hInst == NULL)
		cout<<"erro!";
	else
		cout<<"加载成功!";
	//获取dll的函数

	lpfnDllFunc = (LPFNDLLFUNC)GetProcAddress(hInst, "Max");

	if(hInst == NULL)
		cout<<"erro!";
	else {
		int result;
		result = lpfnDllFunc(1, 2);
		cout<<result<<endl;
	}
	//释放句柄
	FreeLibrary(hInst);
	return 0;
}
编写隐式链接测试,CallDll.cpp
//DLL隐式链接
#include "iostream"

using namespace std;

#pragma comment(lib, "..\\Debug\\VC_Dll.lib")
//如果DLL使用的是def文件,要删除TestDll.h文件中关键字extern "C",这个卡了有几个钟!!
//extern "C" _declspec(dllimport) int Max(int a, int b);
_declspec(dllimport) int Max(int a, int b);

int main() {
	int result = Max(2, 3);
	cout<<result<<endl;
	return 0;
}

你可能感兴趣的:(VC动态链接库的编写与调用)