从dll导入显式实例化的模板类

Nai*_*ler 7 c++ dll templates

作为一个dll新手,我不得不向全能的SO询问一些事情.

假设我显式实例化了这样的模板类:

template class __declspec(dllexport) B<int>;
Run Code Online (Sandbox Code Playgroud)

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

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

template class __declspec(dllimport) B<int>;
Run Code Online (Sandbox Code Playgroud)

dir*_*tly 5

完全实例化模板时 - 您有一个完整的类型.它与任何其他类型没有什么不同.您需要包含头文件B以及编译时链接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>;
Run Code Online (Sandbox Code Playgroud)

文件: template_export_test.cpp


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

创建测试应用程序

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

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

int main(int argc, char** argv) {
    CdllTest<int> c(12);
}
Run Code Online (Sandbox Code Playgroud)
  • 编译然后去!