Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / library_loader.h
bloba6cc8285cfb148ebd0c4917dc8e840ea11bd33d5
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 */
8 /** @file library_loader.h Functions/types related to loading libraries dynamically. */
10 #ifndef LIBRARY_LOADER_H
11 #define LIBRARY_LOADER_H
13 class LibraryLoader {
14 public:
15 /**
16 * A function loaded from a library.
18 * Will automatically cast to the correct function pointer type on retrieval.
20 class Function {
21 public:
22 explicit Function(void *p) : p(p) {}
24 template <typename T, typename = std::enable_if_t<std::is_function_v<T>>>
25 operator T *() const
27 return reinterpret_cast<T *>(this->p);
30 private:
31 void *p;
34 /**
35 * Load a library with the given filename.
37 explicit LibraryLoader(const std::string &filename)
39 this->handle = this->OpenLibrary(filename);
42 /**
43 * Close the library.
45 ~LibraryLoader()
47 if (this->handle != nullptr) {
48 this->CloseLibrary();
52 /**
53 * Check whether an error occurred while loading the library or a function.
55 * @return Whether an error occurred.
57 bool HasError()
59 return this->error.has_value();
62 /**
63 * Get the last error that occurred while loading the library or a function.
65 * @return The error message.
67 std::string GetLastError()
69 return this->error.value_or("No error");
72 /**
73 * Get a function from a loaded library.
75 * @param symbol_name The name of the function to get.
76 * @return The function. Check HasError() before using.
78 Function GetFunction(const std::string &symbol_name)
80 if (this->error.has_value()) return Function(nullptr);
81 return Function(this->GetSymbol(symbol_name));
84 private:
85 /**
86 * Open the library with the given filename.
88 * Should set error if any error occurred.
90 * @param filename The filename of the library to open.
92 void *OpenLibrary(const std::string &filename);
94 /**
95 * Close the library.
97 void CloseLibrary();
99 /**
100 * Get a symbol from the library.
102 * Should set error if any error occurred.
104 * @param symbol_name The name of the symbol to get.
106 void *GetSymbol(const std::string &symbol_name);
108 std::optional<std::string> error = {}; ///< The last error that occurred, if set.
109 void *handle = nullptr; ///< Handle to the library.
112 #endif /* LIBRARY_LOADER_H */