OpenTTD Source 20241224-master-gf74b0cf984
library_loader.h
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#ifndef LIBRARY_LOADER_H
11#define LIBRARY_LOADER_H
12
14public:
20 class Function {
21 public:
22 explicit Function(void *p) : p(p) {}
23
24 template <typename T, typename = std::enable_if_t<std::is_function_v<T>>>
25 operator T *() const
26 {
27 return reinterpret_cast<T *>(this->p);
28 }
29
30 private:
31 void *p;
32 };
33
37 explicit LibraryLoader(const std::string &filename)
38 {
39 this->handle = this->OpenLibrary(filename);
40 }
41
46 {
47 if (this->handle != nullptr) {
48 this->CloseLibrary();
49 }
50 }
51
57 bool HasError()
58 {
59 return this->error.has_value();
60 }
61
67 std::string GetLastError()
68 {
69 return this->error.value_or("No error");
70 }
71
78 Function GetFunction(const std::string &symbol_name)
79 {
80 if (this->error.has_value()) return Function(nullptr);
81 return Function(this->GetSymbol(symbol_name));
82 }
83
84private:
92 void *OpenLibrary(const std::string &filename);
93
97 void CloseLibrary();
98
106 void *GetSymbol(const std::string &symbol_name);
107
108 std::optional<std::string> error = {};
109 void *handle = nullptr;
110};
111
112#endif /* LIBRARY_LOADER_H */
A function loaded from a library.
std::string GetLastError()
Get the last error that occurred while loading the library or a function.
bool HasError()
Check whether an error occurred while loading the library or a function.
std::optional< std::string > error
The last error that occurred, if set.
Function GetFunction(const std::string &symbol_name)
Get a function from a loaded library.
void * OpenLibrary(const std::string &filename)
Open the library with the given filename.
void * handle
Handle to the library.
~LibraryLoader()
Close the library.
LibraryLoader(const std::string &filename)
Load a library with the given filename.
void * GetSymbol(const std::string &symbol_name)
Get a symbol from the library.
void CloseLibrary()
Close the library.