Using interface to export class from dll

10,698

If you want your EXE to allocate a new "Class" object, the EXE code has to know the Class type. If you want to keep the Class type unknown from the EXE, one solution may be to export from your DLL a factory function, which will construct a Class object and return it as an IClass pointer.

See How to implement the factory pattern in C++ correctly

Share:
10,698

Related videos on Youtube

leon22
Author by

leon22

Updated on October 09, 2022

Comments

  • leon22
    leon22 over 1 year

    IClass (My interface):

    #ifndef _ICLASS_H
    #define _ICLASS_H
    
    #include <sstream>
    
    namespace Test
    {
        class __declspec(dllexport) IClass
        {
        public:     
            virtual ~IClass() {}                
    
            virtual bool Init(const std::string &path) = 0;     
        };
    }
    
    #endif
    

    Class.h

    #ifndef _CLASS_H
    #define _CLASS_H
    
    #include "IClass.h"
    #include <memory>
    #include <sstream>
    #include <stdio.h>
    
    namespace Test
    {
        class Class: public IClass
        {
        public:
            Class();
            ~Class();               
    
            bool Init(const std::string &path);         
        };
    }
    
    #endif
    

    Class.cpp

    #include "Class.h"
    
    namespace Test
    {
        Class::Class()
        {       
        }
    
        bool Class::Init(const std::string &path)
        {
            try
            {
                // do stuff
    
                return true;
            }
            catch(std::exception &exp)
            {
                return false;
            }
        }   
    }
    

    main (in exe, dll linked implicitly)

    #include "IClass.h"
    
    using namespace Test;
    
    int main(int argc, char* argv[])
    {
        std::shared_ptr<IClass> test = std::make_shared<Class>(); // error: unreferenced Class
    
        test->Init(std::string("C:\\Temp"));
    }
    

    At the moment Class is not declared

    -> if I include Class.h to main following error occurs: LNK2019: unresolved external symbol: add class __declspec(dllexport) Class : public IClass resolve this linker issue, but is it ok to do it this way?

    -> I also can't do this: std::shared_ptr<IClass> test = std::make_shared<IClass>(); (because it's not allowed to create an object of abstract class)

    How can I solve this issue and is this best practise?