从DLL实例化模板类

C++ instantiate template class from DLL

本文关键字:实例化 DLL      更新时间:2023-10-16

我尝试制作一个包含:

的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