OpenTTD Source: src/os/windows/library_loader_win.cpp Source File

OpenTTD Source 14.0-beta1

library_loader_win.cpp
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 #include "../../stdafx.h"
11
12 #include <windows.h>
13
14 #include "../../library_loader.h"
15 #include "../../3rdparty/fmt/format.h"
16
17 #include "../../safeguards.h"
18
19 static std::string GetLoadError()
20 {
21 auto error_code = GetLastError();
22
23 wchar_t buffer[512];
24 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code,
25 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, lengthof(buffer), nullptr) == 0) {
26 return fmt::format("Unknown error {}", error_code);
27 }
28
29 return FS2OTTD(buffer);
30 }
31
32 void *LibraryLoader::OpenLibrary(const std::string &filename)
33 {
34 void *h = ::LoadLibraryW(OTTD2FS(filename).c_str());
35 if (h == nullptr) {
36 this->error = GetLoadError();
37 }
38
39 return h;
40 }
41
42 void LibraryLoader::CloseLibrary()
43 {
44 HMODULE handle = static_cast<HMODULE>(this->handle);
45
46 ::FreeLibrary(handle);
47 }
48
49 void *LibraryLoader::GetSymbol(const std::string &symbol_name)
50 {
51 HMODULE handle = static_cast<HMODULE>(this->handle);
52
53 void *p = reinterpret_cast<void *>(::GetProcAddress(handle, symbol_name.c_str()));
54 if (p == nullptr) {
55 this->error = GetLoadError();
56 }
57
58 return p;
59 }
LibraryLoader::OpenLibrary
void * OpenLibrary(const std::string &filename)
Open the library with the given filename.
Definition: library_loader_unix.cpp:39
FS2OTTD
std::string FS2OTTD(const std::wstring &name)
Convert to OpenTTD's encoding from a wide string.
Definition: win32.cpp:462
LibraryLoader::error
std::optional< std::string > error
The last error that occurred, if set.
Definition: library_loader.h:108
LibraryLoader::handle
void * handle
Handle to the library.
Definition: library_loader.h:109
LibraryLoader::CloseLibrary
void CloseLibrary()
Close the library.
Definition: library_loader_unix.cpp:49
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:300
LibraryLoader::GetSymbol
void * GetSymbol(const std::string &symbol_name)
Get a symbol from the library.
Definition: library_loader_unix.cpp:54
OTTD2FS
std::wstring OTTD2FS(const std::string &name)
Convert from OpenTTD's encoding to a wide string.
Definition: win32.cpp:479