c++ - 从 dll 中导入显式实例化的模板类

标签 c++ dll templates

作为一个 dll 新手,我必须向全能的 SO 询问一些事情。

假设我像这样显式实例化一个模板类:

template class __declspec(dllexport) B<int>;

如何再次使用导入这个模板类?

我已经尝试在我想使用 B 的 .cpp 文件中添加下面的代码

template class __declspec(dllimport) B<int>;

最佳答案

当你完全实例化一个模板时——你就有了一个完整的类型。它与任何其他类型没有什么不同。您需要包含 B 的 header 以及编译时链接到 lib 文件或动态加载 dll 以链接到定义。

你读过这篇文章吗:http://support.microsoft.com/kb/168958

以下是我测试过(并且有效)的简要总结:


创建一个虚拟 DLL 项目

  • 使用 Win32 控制台应用程序向导生成名为的 dll 头文件/源文件:template_export_test
  • 添加了以下内容:

文件:template_export_test.h


#ifndef EXP_STL
#define EXP_STL
#endif 

#ifdef EXP_STL
#    define DECLSPECIFIER __declspec(dllexport)
#    define EXPIMP_TEMPLATE
#else
#    define DECLSPECIFIER __declspec(dllimport)
#    define EXPIMP_TEMPLATE extern
#endif

EXPIMP_TEMPLATE template class DECLSPECIFIER CdllTest<int>;

文件:template_export_test.cpp


template<class T>
CdllTest<T>::CdllTest(T t)
: _t(t)
{
    std::cout << _t << ": init\n";
}

创建测试应用

  • 使用向导创建一个名为:driver
  • 的 Win32 控制台应用程序
  • 编辑此项目的链接器项目设置:
    • 添加到链接器 > 常规 > 其他库目录:template_export_test.lib 的路径
    • 添加到链接器 > 输入 > 附加依赖项:template_export_test.lib
  • 在主 cpp 文件中包含 template_export_test.h

#include "c:\Documents and Settings\...\template_export_test.h"
using namespace std;

int main(int argc, char** argv) {
    CdllTest<int> c(12);
}

  • 编译并运行!

关于c++ - 从 dll 中导入显式实例化的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/666628/

相关文章:

c++ - 如何初始化句柄

c++ - OpenGL:如何只更新纹理的一部分?

c# - 为什么类库 (dll) 不生成 lib 文件?

.net - Visual Studio 引用和版本控制 - 它是如何工作的?

c++ - 为 std::string 释放内存的异常(尝试在 UE4 中使用 YOLO/Darknet)

c++ - 返回类型 Vector

c++ - 静态声明二维数组 C++ 作为类的数据成员

c++ - 如何默认初始化静态类模板变量

c++ - 如何修复涉及概念和 friend 的 C++20 编译错误?

c++ - 使用 auto C++ 检索存储的元组的值