Cogs.Core
Module.h
1#pragma once
2
3#include "../FoundationBase.h"
4
5#if defined( _WIN32 )
6 #include <WinSock2.h>
7 #undef GetObject
8#endif
9
10#include <string>
11
12namespace Cogs {
23 class COGSFOUNDATION_API Module {
24 public:
25 enum class LoadStatus {
26 Unloaded,
27 Loaded,
28 Failed,
29 };
30
31 LoadStatus status = LoadStatus::Unloaded;
32 void* handle = nullptr;
33
34 virtual ~Module() = default;
35 virtual void initPtrs() {}
36
37 static void load( const std::string & path, LoadStatus & status, void*& handle );
38 static void unload(void* handle);
39
46 template<typename T = Module>
47 static T load( const std::string & path ) {
48 T instance;
49
50 load( path, instance.status, instance.handle );
51
52 if( instance.status == LoadStatus::Loaded ) {
53 instance.initPtrs();
54 }
55 return instance;
56 }
57
58 template<typename T>
59 void getProcAddress( T & ptr, const char* procName ) {
60 ptr = reinterpret_cast< T >( getProcAddress( procName ) );
61 }
62
63 void* getProcAddress( const char* procName );
64 static void* getProcAddress( void* handle, const char* procName );
65
66 bool operator ==( const Module & rhs ) const { return ( status == rhs.status ) && ( handle == rhs.handle ); }
67
68 protected:
69 template<typename RET, typename FN, typename... ARGS>
70 RET Call(FN* fn, ARGS... args) const {
71 if (fn) {
72 return (*fn)(args...);
73 }
74 return RET();
75 }
76 };
77
113 template<typename API> class ModuleAPI : public Module {
114 public:
115 ModuleAPI() = default;
116
117 ModuleAPI(void* h, const void* apiPtr) {
118 status = LoadStatus::Loaded;
119 handle = h;
120 api = static_cast<const API*>(apiPtr);
121 }
122
123 ModuleAPI(const std::string& moduleName) {
124 *this = load<ModuleAPI>(moduleName);
125 }
126
127 API* operator ->() {
128 return const_cast<API*>(api); // Cast away const because C++ reasons. :(
129 }
130
131 virtual void initPtrs() override {
132 const void* (*fn)() = reinterpret_cast<const void* (*)()>(getProcAddress(handle, "getPublicAPI"));
133
134 if (fn) {
135 api = static_cast<const API*>(fn());
136 }
137 }
138
139 private:
140 const API* api = nullptr;
141 };
142}
Helper class for shared libraries that implement the getPublicAPI function and provide a structure of...
Definition: Module.h:113
Base class for managing libraries dynamically loaded at runtime.
Definition: Module.h:23
static T load(const std::string &path)
Loads the named shared library.
Definition: Module.h:47
Contains all Cogs related functionality.
Definition: FieldSetter.h:23