Importing explicitly created class template from dll

Being a dll newbie, I have to ask about omnipotent SO about something.

Let's say I explicitly create a template class as follows:

template class __declspec(dllexport) B<int>; 

How to use this template template again?

I tried adding the code below to my .cpp file, where I want to use B

 template class __declspec(dllimport) B<int>; 
+7
c ++ dll templates
source share
2 answers

When you completely create a template, you have a full type. It is no different from other types. You need to include the header for B , as well as link compile time with the lib file or dynamically load the DLL to reference the definition.

Have you read this article: http://support.microsoft.com/kb/168958 ?

Here is a quick overview of what I tested (and it worked):


Create a dummy dll project

  • Using the Win32 Console application wizard to generate dll headers / source files: template_export_test
  • Added the following:

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

file: template_export_test.cpp


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

Create a test application

  • Use the wizard to create a Win32 Console application called: driver
  • Edit the Linker project settings for this project:
    • Add to Linker> General> Additional Library Directories: path to template_export_test.lib
    • Add to Linker> Input> Additional Dependencies: template_export_test.lib
  • Include template_export_test.h in the main cpp file

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

  • Compile and go!
+4
source share

It seems that even if the template is obviously obsolete, problems can occur that lead to runtime errors. Take a look at this interesting article on C4251 (especially the "Conclusion").

0
source share

All Articles