C ++从DLL中实例化模板类 [英] C++ instantiate template class from DLL
问题描述
我试图制作一个DLL,它包含:
I tried to make a DLL that contains:
基本模板类,只有一个虚拟析构函数,没有属性(我将其命名为MatrixInterface )
base template class, only with a virtual destructor and no attributes (I called it MatrixInterface)
一个派生类与构造函数,析构函数,运算符=和属性(矩阵类)
a derived class with constructors, destructor, operator= and attributes (matrix class)
一个返回一个基类指针到一个新派生对象的函数:
a function that returns a base class pointer to a new derived object:
#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);
}
我想在我的程序中使用这个功能来调整矩阵类,但是不能为这个函数分配一个函数指针,我不明白为什么。我可以这样加载任何不是模板函数的函数。
I wanted to instatiate the matrix class in my program using this function, but I cannot assign a function pointer to this function and I don't understand why. I can load any function that is not a template function this way.
#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 CreateMatrixInstance\n";
}
}
else
{
cout<<"Failed loading library "<<(char*)path<<endl;
}
system("pause");
FreeLibrary(hDll);
return 0;
}
基类存在于DLL和可执行文件中。
the base class is present in both DLL and executable file.
由于某些原因,Visual Studio无法打开DLL(使用MSVC或MinGW编译)。我用MinGW编译程序,它加载了.dll文件。
For some reason, Visual Studio cannot open the DLL (compiled with MSVC or MinGW). I compiled the program with MinGW and it loads the .dll file.
你能告诉我我的代码?
推荐答案
模板仅在编译时解决!而在两个不同的编译单元中它们将是不同的类型。 (这就是为什么使用std :: string作为参数导出函数非常危险的原因)。
Templates are resolved at compile time only ! And they are going to be different types in two different compile units. (This is the reason why it's really dangerous to export functions with std::string as parameters).
作为一个共同点,你应该明确地将模板化为你所使用的类型将要使用/允许使用。
As a consquence you should explicitely instanciate the templates to the types that you are going to use / allow to be used.
在exportimport.h文件中,应该会在您的dll中显示所有类型的模板实例。即 MatrixInterface< int>
。
In you exportimport.h file, there should be template instanciation of all the types you are going to expose in your dll. Namely MatrixInterface<int>
.
你应该写类模板MatrixInterface< int> ;;
公开一种类型。
you should write class template MatrixInterface<int>;
to expose one and only one type.
查看显式模板实例
这篇关于C ++从DLL中实例化模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!