---
title: "DLL 的编写与调用(入门)"
author: "ileson"
date: "2012-02-20T01:05:29Z"
tags: []
categories: ["编程语言"]
slug: "dll"
draft: false
lastmod: "2014-05-18T10:26:06Z"
id: 1412336
url: "https://ileson.iteye.com/blog/1412336"
---

一直调用别人写的动态库，也不知道到底是什么是动态主库，今天没事自己用VC6.0写个（纯粹练手，高手就不要看了），心得：Code wins arguments.代码胜于雄辩！---FaceBook
非常简单：一、新建动态库；二、调用自己写的动态库（两种方式）；

一、vc6新建一个动态链接库工程(FirstDemo)
    1、头文件（FD.h）

```C++
    /*声明接口函数*/
extern "C" _declspec(dllexport) int Sum(int a,int b);//加法
extern "C" _declspec(dllexport) int Max(int a,int b);//取最大值
```

    2、Cpp文件（FD.cpp）
  

```C++

 #include "FD.h"
/*实现接口函数*/
extern "C" _declspec(dllexport) int Sum(int a,int b){
	return a+b;
}
extern "C" _declspec(dllexport) int Max(int a,int b){
	if(a>b) return a;
	else return b;
} 
```

二、vc6新建一个测试生成的FirstDemo.dll 的Win32 Console Application工程（TestDll）
    /*两种方式测试*/
    1、头文件（YSDY.h）---隐式调用 测试

```C++
    /**
 *隐式链接方式调用dll,首先将xxx.dll和 xxx.lib文件放到Debug 文件夹下。然后#pragma comment(lib,"./Debug/xxx.lib")
 *此方式特点：在程序一开始执行的时候，就将dll文件全部加载到程序中，不会释放。所以......
 */
#pragma comment(lib, "./Debug/FirstDemo.lib")
int testYS();
```

    2、Cpp文件（YSDY.cpp）---隐式调用 cpp

```C++
#include <windows.h>
#include <iostream.h>
/*隐式链接方式调用dll中方法，不要忘记声明dll中的函数*/
extern "C" _declspec(dllimport) int Sum(int a,int b);
int testYS(){
	int c=Sum(4,8);//调用处。
	cout<<c<<endl;
	return 0;
}
```

    3、头文件（XSDY.h）---显示调用 测试

```C++
int test();
```

    4、Cpp文件（XSDY.cpp）---显示调用 cpp

```C++
#include <iostream.h>
#include <windows.h>

/**
 *对dll中的函数进行显式调用
 *推荐使用这种方式 调用dll
 */
int test(){
	typedef int(*pSum)(int a,int b);//函数指针类型 pSum
	pSum sum=NULL;
	HINSTANCE hDLL=NULL;
	hDLL=LoadLibrary("FirstDemo.dll");//加载动态库文件FirstDemo.dll ,得到动态库句柄
	sum=(pSum)GetProcAddress(hDLL,"Sum");  //得到函数句柄（指针）
	if(sum){
		int A=sum(2,7);
		cout<<A<<endl;

	}
	FreeLibrary(hDLL);//卸载FirstDemo.dll文件；
	return 0;
}
```

    5、入口main

```C++
#include <windows.h>
#include <iostream.h>
#include "XSDY.h"
#include "YSDY.h"

/**
 *工程入口函数
 */
void main(void){
	test();//dll中方法显示调用
	testYS();//隐式链接
}
```



代码：在附件里有两个工程：第一个是dll工程，第二个是调用dll的测试工程。
太晚了，睡觉了。。。。