1 前言
实现一个含有加减乘除运算的动态链接库。工具:VS2010。
2 实现过程
A.新建一个dll工程,文件->新建->项目,
B.选择Win32下的Win32项目,并命名工程名为MathDll,如下图所示
C.确定后,其他默认,在应用程序设置界面选择DLL选项,并选择为空项目,如下图所示,然后完成。
D.在工程文件内新增头文件和源文件,如math.h和math.cpp。
E.代码实现
//math.h
#ifndef _DLL_MATH_DLL_H
#define _DLL_MATH_DLL_H
#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif
extern "C"
{
DECLDIR double Plus(double a,double b);
DECLDIR double Minus(double a,double b);
DECLDIR double Multiply(double a, double b);
DECLDIR double Divide(double a, double b);
DECLDIR void DllName(void);
};
#endif
//math.cpp
#include <iostream>
#include <Windows.h>
#define DLL_EXPORT
#include "math.h"
extern "C"
{
DECLDIR double Plus(double a,double b)
{
return a + b;
}
DECLDIR double Minus(double a,double b)
{
return a - b;
}
DECLDIR double Multiply(double a,double b)
{
return a * b;
}
DECLDIR double Divide(double a,double b)
{
return a / b;
}
DECLDIR void DllName(void)
{
std::cout<<"MathDll"<<std::endl;
}
};
F.编译后,在对应工程目录下存在MathDll.dll文件了。
3 测试动态链接库
A.将MathDll.dll拷贝到D盘根目录下备用。
B.新建一个win32控制台程序,文件->新建->项目,如下图所示,给工程起名为TestMathDll,一直默认确定到工程建立。
C.代码实现
// TestMathDll.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;
//定义指针函数
typedef double(*PlusFunc)(double,double);
typedef double(*MinusFunc)(double,double);
typedef double(*MultiplyFunc)(double,double);
typedef double(*DivideFunc)(double,double);
typedef void(*NameFunc)(void);
int _tmain(int argc, _TCHAR* argv[])
{
//载入动态库
HINSTANCE hInstance = LoadLibrary(L"D:\\MathDll.dll");
if (hInstance == NULL)
{
cout<<"Load MathDll.dll failed."<<endl;
FreeLibrary(hInstance);
}else{
cout<<"Load MathDll.dll successed."<<endl;
}
double a = 2.0, b = 3.0;
//
PlusFunc _plusFunc = (PlusFunc)GetProcAddress(hInstance,"Plus");
if (_plusFunc == NULL)
{
cout<<"Load Plus function failed."<<endl;
}
else
{
cout<<a<<" + "<<b<<" = "<<_plusFunc(a,b)<<endl;
}
MinusFunc _minusFunc = (MinusFunc)GetProcAddress(hInstance,"Minus");
if (_minusFunc == NULL)
{
cout<<"Load Minus function failed."<<endl;
}
else
{
cout<<a<<" - "<<b<<" = "<<_minusFunc(a,b)<<endl;
}
MultiplyFunc _multiplyFunc = (MultiplyFunc)GetProcAddress(hInstance,"Multiply");
if (_multiplyFunc == NULL)
{
cout<<"Load Multiply function failed."<<endl;
}
else
{
cout<<a<<" * "<<b<<" = "<<_multiplyFunc(a,b)<<endl;
}
DivideFunc _divideFunc = (DivideFunc)GetProcAddress(hInstance,"Divide");
if (_divideFunc == NULL)
{
cout<<"Load Divide function failed."<<endl;
}
else
{
cout<<a<<" / "<<b<<" = "<<_divideFunc(a,b)<<endl;
}
NameFunc _dllName = (NameFunc)GetProcAddress(hInstance,"DllName");
if (_dllName == NULL)
{
cout<<"Load DllName function failed."<<endl;
}
else
{
cout<<"The Dll's name is ";
_dllName();
}
FreeLibrary(hInstance);
system("pause");
return 0;
}
D.运行结果如下图所示: