Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting a class from a C++ dll?

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 .

like image 653
Rakesh Agarwal Avatar asked Mar 13 '26 13:03

Rakesh Agarwal


2 Answers

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

like image 62
dirkgently Avatar answered Mar 16 '26 01:03

dirkgently


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.

like image 30
Ignas Limanauskas Avatar answered Mar 16 '26 03:03

Ignas Limanauskas