1、新建一个Win32 DLL 工程
添加头文件到工程中,编写自定义DLL导出类:
#ifndef DLLCLASS_H_
#define DLLCLASS_H_
#include <iostream>
using namespace std;
#define DLL_EXPORT _declspec(dllexport)
const float PI=3.1415926;//或者C语言的#define PI 3.1415926
inline float GetSquare(const float& n){ return n*n;}
inline float GetCubic(const float& n){ return n*n*n;}
class DLL_EXPORT CBall//DLL封装球
{
public://接口
CBall(float f=1.0);
~ CBall();
void ChangeRadius(const float& value);//改变球的半径
float GetArea()const;//计算球面积
float GetVolume()const;//计算球体积
private:
float m_fRadius;//球半径
};
#endif;
添加源文件到工程中,实现DLL类的功能:
#include "stdafx.h"
#include "DllClass.h"
CBall::CBall(float f):m_fRadius(f)
{
}
CBall::~CBall()
{
}
void CBall::ChangeRadius(const float& value)
{
m_fRadius=value;
}
float CBall::GetArea() const
{
return 4*PI*GetSquare(m_fRadius);
}
float CBall::GetVolume() const
{
return 4/3.0*PI*GetCubic(m_fRadius);
}
2、新建一个win32控制台应用程序:
准备工作:将DLL工程中生成的后缀名为lib的文件复制到的当前工程的CPP\H文件所在文件夹下,将后缀名为dll的文件复制到生成的exe程序的Debug文件夹下
#include "stdafx.h"
#include "DllClass.h"
#pragma comment(lib,"Win32_Dll.lib")//连接到DLL中
using std::cout;
using std::endl;
int _tmain(int argc, _TCHAR* argv[])
{
CBall b;
cout<<"球的面积是:"<<b.GetArea()<<endl;;
cout<<"体积是:"<<b.GetVolume()<<endl;
return 0;
}
一个很简单的DLL开发小实例,希望可以抛砖引玉