C++ 从 DLL 实例化模板类

标签 c++ templates dll function-pointers

我试图制作一个包含以下内容的 DLL:

基本模板类,只有一个虚拟析构函数,没有属性(我称之为 MatrixInterface)

具有构造函数、析构函数、operator= 和属性的派生类(矩阵类)

返回指向新派生对象的基类指针的函数:

#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 CreateMatrixInstance\n";
        }
    }
    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>;

以便公开一种且仅一种类型。比照。 What does `class template Example<int>;` statement mean with C++11?

请参阅此处的文档引用:https://en.cppreference.com/w/cpp/language/class_template#Class_template_instantiation

关于C++ 从 DLL 实例化模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14138360/

相关文章:

c# - 无法加载DLL : The specified module could not be found

c++ - 运算符的不明确重载

templates - Google Go 文本模板中范围最后一个元素的特殊情况处理

c++ - 基类模板中的从属名称查找

c++ - 为什么 C++ 允许但忽略将 const 应用于函数类型?

c# - 运行时可调用包装类未注册

c++ - 将左值传递给右值

c++ - 使用迭代器构造 QVector 对象

C++ bind第二题

c++ - 如何追踪使用过的DLL(是不是所谓的DLL hell ?)