C++dll导出类的方式__declspec(dllexport)


前言

有时导出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的函数了


初学轻喷~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值