前言
有时导出dll的时候既想用到整个类又想保持多态
一、直接导出整个类
示例:头文件
#ifdef AITWapper_EXP //根据项目是导入导出预定义
#define AITWapper_DLL __declspec(dllexport)
#else
#define AITWapper_DLL __declspec(dllimport)
#endif
//直接在类头加宏
class AITWapper_DLL WrapperByIdea/*:public WrapperBase*/
{
public:
WrapperByIdea();
double GetWaveLength();
private:
};
cpp文件
WrapperByIdea::WrapperByIdea()
{
}
double WrapperByIdea::GetWaveLength()
{
return 0.1;
}
这种方式能用到整个类的函数,但是没法多态
\n
二、用一个函数导出类并保持多态
1、头文件代码如下(示例):
#include "WrapperBase.h"//包含基类的头文件
#ifdef AITWapper_EXP
//这种方式要加extern “C”
#define AITWapper_DLL extern "C" __declspec(dllexport)
#else
#define AITWapper_DLL extern "C" __declspec(dllimport)
#endif
class WrapperByIdea:public WrapperBase
{
public:
WrapperByIdea();
~WrapperByIdea();
double GetWaveLength();
static WrapperByIdea * instance;
private:
};
AITWapper_DLL WrapperByIdea* CreateWrapper();
2.cpp代码如下(示例):
WrapperByIdea * WrapperByIdea::instance = nullptr;//初始化静态成员对象
AITWapper_DLL WrapperByIdea* CreateWrapper()
{
if(WrapperByIdea::instance == nullptr)
{
WrapperByIdea::instance = new WrapperByIdea;
}
//使每次都返回同一个对象(静态),根据需求而定可以直接返回new 对象
return WrapperByIdea::instance;
}
WrapperByIdea::WrapperByIdea()
{
}
double WrapperByIdea::GetWaveLength()
{
return 1;
}
第二种用的时候可以先转回基类的指针,就能调用dll的函数了
初学轻喷~