1.打开VC6.0,选择【文件】--【新建】--【工程】--【Win32 Dynamic-LinkLibrary】
工程名称(自定):【MyDll】
位置(自定,这里我选择的是E盘下的Test文件夹):【E:\Test\】
---【确定】--【一个空的DLL工程(E)】--【完成】--【确定】
2.【文件】--【新建】--【C/C++ Header File】
文件名:MyDll
位置(默认):【E:\TEST\MyDll】
在MyDll.h中的代码如下:
extern "C" __declspec(dllexport) int add(int x, int y);
extern "C" __declspec(dllexport) int sub(int a, int b);
3.【文件】--【新建】--【C/C++ Source File】
文件名:MyDll
位置(默认):【E:\TEST\MyDll】
在MyDll.cpp中的代码入下:
#include "MyDll.h"
int add(int x, int y)
{
return x+y;
}
int sub(int a, int b)
{
return a-b;
}
4.【编译】--【组建】
在E:\Test\MyDll就包含了MyDll.h等其他文件
在E:\Test\MyDll\Debug就包含了MyDll.h、MyDll.lib等其他文件
5.【文件】--【关闭工作区间】
现在Dll文件生成了,如何调用呢?
有两种调用:隐式链接和显示链接
隐式链接:
6.【文件】--【新建】--【Win32 Console Application】
工程名称:DllTest
位置:E:\TEST\DllTest
【确定】--【一个简单的工程】--【完成】--【确定】--【组建】
在【工作区】--选择【FileView】
展开【Source Files】--双击【DllTest.cpp】
DllTest.cpp中的代码如下:
#include "stdafx.h"
#include "MyDll.h"
#include "iostream"
using namespace std;
#pragma comment(lib,"MyDll.lib")
int main(int argc, char* argv[])
{
cout<<add(2,3)<<endl;
cout<<sub(5,2)<<endl;
return 0;
}
7.把MyDll.dll、MyDll.h、MyDll.lib这三个文件放到E:\Test\DllTest的目录下
8.【组建】--【执行】
结果:
5
3
9.现在做显示链接
【文件】--【关闭工作区间】
【文件】--【新建】--【Win32 Console Application】
工程名称:DllTest2
位置:E:\TEST\DllTest2
【确定】--【一个简单的工程】--【完成】--【确定】--【组建】
在【工作区】--选择【FileView】
展开【Source Files】--双击【DllTest2.cpp】
DllTest2.cpp中的代码如下:
#include "stdafx.h"
#include "iostream"
#include "windows.h"
using namespace std;
int main(int argc, char* argv[])
{
HINSTANCE hDll = NULL;
hDll = LoadLibrary("MyDll.dll");
if(hDll == NULL)
{
MessageBox(NULL,"Dll加载失败","提示",1);
return 0;
}
typedef int (*FUN)(int , int );
FUN f = NULL;
f = (FUN)GetProcAddress(hDll,"sub");
if(hDll == NULL)
{
MessageBox(NULL,"Dll加载失败","提示",1);
return 0;
}
cout<<f(3,2)<<endl;
return 0;
}
10.把MyDll.dll放到E:\Test\DllTest2目录下
【编译】--【组建】--【执行】
结果为:
1
也可以把
f = (FUN)GetProcAddress(hDll,"sub");中的sub改为add
结果就为5