Domanda

I've the following problem: I've created a DLL in C++ with a template class definition like this:

 template <class T>
 class myClass {
    public:
    //! Constructor
    myClass(int size = 10);

    //! Destructor
    ~myClass();

    someAttributes ... ;
    }

I want to export it so I've defined as follows:

   template class __declspec(dllexport) myClass<double>;

because - I've read - in Visual C++ you can't export template but only their explicit inizialization. This way all works fine and I'm able to import the DLL in a new Visual C++ code. Now: Do I have to export an explicit instantiation for every type I need (myClass, myClass, etc)? Or is there a better way - less naive - to do that? How can I import my template class in a VB.NET project? Is there a way? Or do I've to create a marshaling structure and then convert it in my template class at runtime?

Thank you all!

È stato utile?

Soluzione

You will have to export an explicit type instantiation of your template for every type you wish to use. Moreover, you might have to call each method that you want to use explicitly from your C++ code at least once in order to have the object code for it included in the library.

The reason for this is, that template code is not code that will be compiled readily into your object files (or dll). The compiler will generate the required (and usually only the required) code on compilation time of your program. If your C++ code never uses a template class, the compiler simply will ignore the template at all. The same is true for methods of your template class. If you do not use it, the compiler is allowed to ignore it.

The bottom line is: using template code for libraries that are intended to be used from other languages is usually a not so good idea...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top