从DLL实例化模板类
C++ instantiate template class from DLL
我尝试制作一个包含:
的DLL基模板类,只有虚析构函数而没有属性(我称之为MatrixInterface)
一个具有构造函数、析构函数、操作符和属性的派生类 (矩阵类)
返回基类指针指向新的派生对象的函数:
#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
template<class T>
MatrixInterface<T> DLL_EXPORT * CreateMatrixInstance(unsigned int n,unsigned int m)
{
return new matrix<T>(n,m);
}
我想用这个函数在我的程序中实例化矩阵类,但是我不能给这个函数分配一个函数指针,我不明白为什么。我可以通过这种方式加载任何非模板函数。
#include <windows.h>
#include <iostream>
using namespace std;
template<class T>
class MatrixInterface
{
public:
virtual ~MatrixInterface(void);
};
typedef MatrixInterface<int>* (*Fptr)(unsigned int,unsigned int);
int main(int argc, char* argv[])
{
Fptr p;
MatrixInterface<int> *x;
char path[]="basicmatrix.dll";
HINSTANCE hDll = LoadLibrary(path);
cout<<(char*)path<<endl;
if(hDll)
{
cout<<"Library opened succesfully!"<<endl;
p = (Fptr)GetProcAddress(hDll,"CreateMatrixInstance");
if(p) {
cout<<"working!n";
x=p(7,8);
cout<<"MatrixCreated"<<endl;
delete x;
} else {
cout<<"Failed loading function CreateMatrixInstancen";
}
}
else
{
cout<<"Failed loading library "<<(char*)path<<endl;
}
system("pause");
FreeLibrary(hDll);
return 0;
}
基类同时存在于DLL和可执行文件中。
由于某些原因,Visual Studio无法打开DLL(使用MSVC或MinGW编译)。我用MinGW编译了这个程序,它加载了。dll文件。
你能告诉我我的代码有什么问题吗?
模板只在编译时解析!它们在两个不同的编译单元中是不同的类型。(这就是为什么将std::string
作为参数导出函数非常危险的原因)。
因此,你应该显式地将模板实例化为你将要使用/允许使用的类型。
在您的exportimport.h
文件中,应该有您将在dll中公开的所有类型的模板实例化。即MatrixInterface<int>
。
你应该写:
template class MatrixInterface<int>;
,以便暴露一个且仅一个类型。在c++ 11中,' class template Example
参见此处的文档参考:https://en.cppreference.com/w/cpp/language/class_template#Class_template_instantiation
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- 如何在 C++ 中从 dll 实例化类?
- DLL 中的实例化类在 QT 的 LoadLibrary 中引发 127 错误
- 如果在 DLL/Lib 中定义了对象,是否可以在客户端中实例化对象?
- Java从DLL实例化C++类
- 类和函数模板实例化的Visual Studio dll导出问题
- 如何在c++ dll中实例化一个类,使它在函数调用之间保持内存
- 跨DLL边界的c++类实例化
- 跨DLL的c++成员函数显式模板实例化
- 为什么要使用静态字符缓冲区来实例化从DLL加载的C++类
- 从DLL实例化模板类