最近编写C++动态链接库模块,模块内有一些类需要被外部用户调用,这种情况下可以采用接口或者导出类实现这个功能。
如果导出类中没有任何其他的类对象作为成员,则直接导出类就可以用了,不过这种用法需要将类的头文件公开,调用者需要引用头文件才能调用导出类的功能,例如我们定义了一个点类,头文件(PointClass.h)内容
#pragma once
class _declspec(dllexport) Point
{
public:
Point();
Point(double x,double y);
~Point();
double x, y;
double distToOrg();
};
源文件内容
#include
#include "pointClass.h"
Point::Point()
{
x = 0;
y = 0;
}
Point::Point(double x, double y)
{
this->x = x;
this->y = y;
}
Point::~Point()
{
}
double Point::distToOrg()
{
return pow(x * x + y * y, 0.5);
}
该类的使用,main函数如下:
#include
#include
#include
#include "PointClass.h"
using namespace std;
int main()
{
//采用内部没有类对象成员的导出类
srand((unsigned)time(0));
double x = rand();
double y = rand();
Point pt(x,y);
cout << "point coord x=" << pt.x << " y=" << pt.y <<" distToOrg="<< pt.distToOrg()<< endl;
system("break");
}
可以编译,运行结果如下,可以看出导出类可以正常使用,其成员变量及函数均可使用。
也可以用接口实现上述功能,定义接口:
#pragma once
//IPoint.h
class _declspec(dllexport) IPoint
{
virtual double getX() = 0;
virtual double getY() = 0;
virtual void setX(double _x) = 0;
virtual void setY(double _y) = 0;
virtual double distToOrg() = 0;
};
int _declspec(dllexport)_stdcall pointFactory(void** _pReturn);
重新写PointClass.h,这时不需要将其声明为导出类,而是继承了接口,使用时可以只公开接口的头文件即可
#pragma once
#include "IPoint.h"
class Point:public IPoint
{
public:
Point();
Point(double x,double y);
~Point();
double getX();
double getY();
void setX(double _x);
void setY(double _y);
double x, y;
double distToOrg();
};
源文件内容
#include
#include "pointClass.h"
Point::Point()
{
x = 0;
y = 0;
}
Point::Point(double x, double y)
{
this->x = x;
this->y = y;
}
Point::~Point()
{
}
double Point::getX()
{
return x;
}
double Point::getY()
{
return y;
}
void Point::setX(double _x)
{
x = _x;
}
void Point::setY(double _y)
{
y = _y;
}
double Point::distToOrg()
{
return pow(x * x + y * y, 0.5);
}
int _declspec(dllexport)_stdcall pointFactory(void** _pReturn)
{
Point* pPoint = new Point;
*_pReturn = (void*)pPoint;
if (pPoint == NULL) return 0;
return 1;
}
pointFactory函数是为了创建一个Point对象,因为接口是虚类,不能直接生成接口对象,这里用pointFactory函数创建一个Point对象将其地址返回给接口的指针,使用接口时main函数如下:
#include
#include
#include
#include "IPoint.h"
using namespace std;
int main()
{
//采用接口
srand((unsigned)time(0));
double x = rand();
double y = rand();
IPoint* pt;
if (pointFactory((void**)&pt))
{
pt->setX(x);
pt->setY(y);
cout << "point coord x=" << pt->getX() << " y=" << pt->getY() << " distToOrg=" << pt->distToOrg() << endl;
system("break");
}
}