VC++动态链接库(DLL)编程深入浅出(二)

来源:互联网 发布:地球数据 编辑:程序博客网 时间:2024/05/10 16:46

#ifdef DLL_FILE

class _declspec(dllexport)circle //导出类circle

#else

class _declspec(dllimport)circle //导入类circle

#endif

{

public:

void SetCentre(const point ¢rePoint);

void SetRadius(float r);

float GetGirth();

float GetArea();

circle();

private:

float radius;

point centre;

};

#endif


//文件名:circle.cpp,circle类的实现

#ifndef DLL_FILE

#define DLL_FILE

#endif

#include "circle.h"

#define PI 3.1415926

//circle类的构造函数

circle::circle()

{

centre = point(0, 0);

radius = 0;

}

//得到圆的面积

float circle::GetArea()

{

return PI *radius * radius;

}

//得到圆的周长

float circle::GetGirth()

{

return 2 *PI * radius;

}

//设置圆心坐标

void circle::SetCentre(const point ¢rePoint)

{

centre = centrePoint;

}

//设置圆的半径

void circle::SetRadius(float r)

{

radius = r;

}

  类的引用:
#include "../circle.h"  //包含类声明头文件

#pragma comment(lib,"dllTest.lib");


int main(int argc, char *argv[])

{

circle c;

point p(2.0, 2.0);

c.SetCentre(p);

c.SetRadius(1.0);

printf("area:%f girth:%f", c.GetArea(), c.GetGirth());


return 0;

}

  从上述源代码可以看出,由于在DLL的类实现代码中定义了宏DLL_FILE,故在DLL的实现中所包含的类声明实际上为:
class _declspec(dllexport) point //导出类point

{

}

  和
class _declspec(dllexport) circle //导出类circle

{

}

  而在应用工程中没有定义DLL_FILE,故其包含point.h和circle.h后引入的类声明为:
class _declspec(dllimport) point //导入类point

{

}

  和
class _declspec(dllimport) circle //导入类circle

{

}

  不错,正是通过DLL中的
class _declspec(dllexport) class_name //导出类circle 

{

}

  与应用程序中的
class _declspec(dllimport) class_name //导入类

{

}

  匹对来完成类的导出和导入的!

  我们往往通过在类的声明头文件中用一个宏来决定使其编译为class _declspec(dllexport) class_name还是class _declspec(dllimport) class_name版本,这样就不再需要两个头文件。本程序中使用的是:
#ifdef DLL_FILE

class _declspec(dllexport) class_name //导出类

#else

class _declspec(dllimport) class_name //导入类

#endif

  实际上,在MFC DLL的讲解中,您将看到比这更简便的方法,而此处仅仅是为了说明_declspec(dllexport)与_declspec(dllimport)匹对的问题。

  由此可见,应用工程中几乎可以看到DLL中的一切,包括函数、变量以及类,这就是DLL所要提供的强大能力。只要DLL释放这些接口,应用程序使用它就将如同使用本工程中的程序一样!

  本章虽以VC++为平台讲解非MFC DLL,但是这些普遍的概念在其它语言及开发环境中也是相同的,其思维方式可以直接过渡。

  接下来,我们将要研究MFC规则DLL(待续...)

 
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 租车感觉违章了 怎么办 武汉驾照扣12分怎么办 驾驶证照片泡水不清楚怎么办 驾驶证过了180天怎么办 天津有公司执照怎么办落户 温州车在上海年审手续怎么办 广东小高考考了d怎么办 深圳开摩托抓到怎么办 深圳车卖了车牌怎么办 a1驾照时期过了怎么办 b1驾照扣了12分怎么办 北京的驾照换证怎么办 b2汽车驾驶证年审过期几天怎么办 上海驾照到期人在外地怎么办 交警开的罚单交不了怎么办 珠海交警微信交罚单扣分怎么办 驾驶证违法罚款单子没有了怎么办 转账密码输错3次怎么办 汽车违章扣6分怎么办 汽车扣了72分年检怎么办 汽车扣了50分怎么办 汽车扣了15分怎么办 汽车扣了27分怎么办 汽车扣了40分怎么办 行驶证掉了怎么办 异地 高速上没带驾驶证行驶证怎么办 身份证驾驶证行驶证都丢了怎么办 驾驶证年审过期一个月怎么办 柴油车辆年检尾气不合格怎么办 驾驶证过期了5天怎么办 过了审车时间怎么办 骑车没带行驶证怎么办 轿车行驶证丢了怎么办 车子没年检被扣怎么办 上海车辆年检过期了怎么办 行驶证过期十天怎么办 行驶证盖章满了怎么办 驾照c证扣12分怎么办 两年小车忘年审怎么办 4年车检过期了怎么办 车检过期了1周怎么办