代码之家  ›  专栏  ›  技术社区  ›  Nailer

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

  •  7
  • Nailer  · 技术社区  · 17 年前

    假设我显式实例化一个模板类,如下所示:

    template class __declspec(dllexport) B<int>;
    

    template class __declspec(dllimport) B<int>;
    
    2 回复  |  直到 17 年前
        1
  •  5
  •   dirkgently    17 年前

    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>;
    

    文件: template_export_test.cpp


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

    • driver
    • 编辑此项目的链接器项目设置:
      • 添加到链接器>一般>其他库目录:路径 template_export_test.lib
      • template_export_test.lib
    • template_export_test。英语字母表的第8个字母

    #include "c:\Documents and Settings\...\template_export_test.h"
    using namespace std;
    
    int main(int argc, char** argv) {
        CdllTest<int> c(12);
    }
    

    • 编译并开始!
        2
  •  0
  •   mats    17 年前

    看起来,即使明确地安装了模板,也可能会出现导致运行时错误的问题。 this interesting article to C4251 (尤其是“结论”)。