看了许多资料,大部分都是通过__declspec(dllexport) 修饰符进行导出的。
通过.def文件导出函数和类都可以实现,但是导出模板函数和模板类却没有找到,但是没关系。
例子:
dll_test.h
#ifndef DLL_TEST_H
#define DLL_TEST_H
#define DLL_EXPORT __declspec(dllexport)
#include<string>
using namespace std;
template<typename Dtype> class Operation
{
public:
virtual Dtype getResult(Dtype a, Dtype b) = 0;
virtual void destorySelf() { this->~Operation(); }
virtual ~Operation() {};
};
template<typename Dtype> class OperationSub :public Operation<Dtype>
{
public:
Dtype getResult(Dtype a, Dtype b);
};
template<typename Dtype> class OperationMul : public Operation<Dtype>
{
public:
Dtype getResult(Dtype a, Dtype b);
};
//导出工厂函数
template<typename Dtype> Operation<Dtype> * createOperator(string oper);
template<> DLL_EXPORT Operation<float> * createOperator(string oper); //模板特化声明
template<> DLL_EXPORT Operation<double> * createOperator(string oper); //模板特化声明
#endif
dll_test.cpp
#include"dll_test.h"
template<typename Dtype> Dtype OperationSub<Dtype>::getResult(Dtype a, Dtype b) { return (a - b); }
template<typename Dtype> Dtype OperationMul<Dtype>::getResult(Dtype a, Dtype b) { return (a * b); }
template<typename Dtype> Operation<Dtype> * createOperator (string oper)
{
if (strcmp(oper.c_str(), "-")== 0)
{
return new OperationSub<Dtype>();
}
else if (strcmp(oper.c_str(), "*") == 0)
{
return new OperationMul<Dtype>();
}
}
// 模板特化 float
template<> DLL_EXPORT Operation<float> * createOperator(string oper)
{
if (strcmp(oper.c_str(), "-") == 0)
{
return new OperationSub<float>();
}
else if (strcmp(oper.c_str(), "*") == 0)
{
return new OperationMul<float>();
}
}
// 模板特化 double
template<> DLL_EXPORT Operation<double> * createOperator(string oper)
{
if (strcmp(oper.c_str(), "-") == 0)
{
return new OperationSub<double>();
}
else if (strcmp(oper.c_str(), "*") == 0)
{
return new OperationMul<double>();
}
}
测试函数:
将上面的代码编译生成动态库dll,将文件.h,lib,dll添加到测试函数所在的工程。
test.cpp
#include"dll_test.h"
#include<string>
#include<iostream>
//#pragma comment(lib,"dll_test.lib")
int main()
{
Operation<float> *foper = createOperator<float>("-");
Operation<double> *doper = createOperator<double>("*");
float fresult = foper->getResult(10, 5);
double dresult = doper->getResult(10, 5);
cout << fresult << endl;
cout << dresult << endl;
}
参考文献:
1. http://forums.codeguru.com/showthread.php?364061-How-to-export-c-class-in-DLL-using-DEF-file
2. https://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL [HowTo: Export C++ classes from a DLL]
3. http://www.mingw.org/wiki/exporting_a_class_from_a_dll_for_multiple_instantiations