views:

410

answers:

6

How do I expose a class from a dll ?

The application importing the dll should be able to create the objects of the class and also he should be able to call into the member functions of the class .

Is it similar to exposing C type functions using _declspec(dllexport) ?

And also when I built the dll ( which only contains class definition in a header file and its member function definitions in a cpp file ) , no corresponding lib file is created .

A: 

Look at Def Files, in additional first link from there is Using __declspec(dllexport)

abatishchev
+2  A: 

Here. Remember you cannot use this exported class using LoadLibrary()/GetProcAddress().

dirkgently
+1  A: 

Is it similar to exposing C type functions using _declspec(dllexport) ?

Yes. And the __declspec can be applied to the class.

no corresponding lib file is created

IIRC this is the default, but you can override default linker options.

Richard
A: 

Googling for "class dllexport" resulted in this page from MSDN as the first result.

The page seems to indicate just having __declspec(dllexport) is all you need to do.

SoapBox
+1  A: 

Check this question on SO: Exporting a C++ class from a DLL

Igor Oks
+1  A: 

The definition of at least one public method in the exported class must have _declspec(dllexport) prefix for lib file to be created. If none of the methods have this prefix, only the declaration (i.e. header file) will available, but the class will be impossible to instantiate (exported constructor is necessary for this). If at least one method has _declspec(dllexport) prefix, then compiler will understand that dll users must be able to link to this dll. OS loads such dlls as soon as exe linking to them is loaded.

You may consider a "factory" approach to your problem. Symbian OS, for example, implements such approach with polymorphic dlls. To do this you have to:

  1. Declare (i.e. header file) and define (i.e. cpp file) the class in your dll. No need for anything else.

  2. Create a "factory" function in your dll, which would make an instance to your class and return pointer to it. This function must have _declspec(dllexport) prefix.

  3. Share your header file and lib file with your users.

  4. Users include the header file and link with the lib file.

  5. Users call the factory function to instantiate the class (i.e. make the object), and then use it as a normal class.

The 5 steps above work like charm in Symbian OS. You would have to try it yourself on your platform and post the results. I, frankly, have not tried it on Windows.

Ignas Limanauskas
infact we can declare the whole class as _declspec(dllexport) , which would allow class to be instantiated and also allow calling into member functions . ( as given by link in the answers above ) .
Rakesh Agarwal