Skip to content
Snippets Groups Projects
LibraryLoader.h 1.44 KiB
Newer Older
  • Learn to ignore specific revisions
  • #ifndef _CLI_LIBRARY_LOADER_H_
    #define _CLI_LIBRARY_LOADER_H_
    
    #include <command/Command.h>
    #include <environment/Environment.h>
    
    #include <dlfcn.h>
    
    #include <experimental/filesystem>
    #include <alib/list>
    
    #include <exception/CommonException.h>
    
    namespace cli {
    
    class LibraryLoader {
    	class Library {
    		std::string m_path;
    		void * m_handle;
    
    	public:
    		Library ( const std::string & path ) : m_path ( path ), m_handle ( NULL ) {
    
    		}
    
    		Library ( const Library & ) = delete;
    
    		Library ( Library && other ) : m_path ( std::move ( other.m_path ) ), m_handle ( other.m_handle ) {
    			other.m_handle = NULL;
    		}
    
    		Library & operator = ( const Library & ) = delete;
    		Library & operator = ( Library && other ) = delete;
    
    		~Library ( ) {
    			unload ( );
    		}
    
    		void load ( ) {
    			if ( ! loaded ( ) )
    				m_handle = dlopen ( m_path.c_str ( ), RTLD_NOW );
    			if ( ! loaded ( ) )
    				throw exception::CommonException ( std::string ( dlerror ( ) ) );
    		}
    
    		void unload ( ) {
    			if ( loaded ( ) ) {
    				dlclose ( m_handle );
    				m_handle = NULL;
    			}
    		}
    
    		const std::string & path ( ) const {
    			return m_path;
    		}
    
    		bool loaded ( ) const {
    			return m_handle != NULL;
    		}
    
    	};
    
    	static std::list < Library >::iterator find ( const std::string name );
    
    	static std::list < Library > libraries;
    
    public:
    	static void load ( const std::string & name );
    
    	static void unload ( const std::string & name );
    
    };
    
    } /* namespace cli */
    
    #endif /* _CLI_LIBRARY_LOADER_H_ */