OpenTTD Source 20241224-master-gee860a5c8e
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
19static 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, static_cast<DWORD>(std::size(buffer)), nullptr) == 0) {
26 return fmt::format("Unknown error {}", error_code);
27 }
28
29 return FS2OTTD(buffer);
30}
31
32void *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
43{
44 HMODULE handle = static_cast<HMODULE>(this->handle);
45
46 ::FreeLibrary(handle);
47}
48
49void *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}
std::optional< std::string > error
The last error that occurred, if set.
void * OpenLibrary(const std::string &filename)
Open the library with the given filename.
void * handle
Handle to the library.
void * GetSymbol(const std::string &symbol_name)
Get a symbol from the library.
void CloseLibrary()
Close the library.
std::wstring OTTD2FS(const std::string &name)
Convert from OpenTTD's encoding to a wide string.
Definition win32.cpp:354
std::string FS2OTTD(const std::wstring &name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:337