bactria  0.0.1
The bactria library is a header-only C++14 library for profiling and tracing.
Win32.hpp
Go to the documentation of this file.
1 /* Copyright 2021 Jan Stephan
2  *
3  * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
4  * the European Commission - subsequent versions of the EUPL (the “Licence”).
5  * You may not use this work except in compliance with the Licence.
6  * You may obtain a copy of the Licence at:
7  *
8  * http://ec.europa.eu/idabc/eupl.html
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the Licence is distributed on an “AS IS” basis, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * Licence permissions and limitations under the Licence.
14  */
15 
23 #ifdef _WIN32
24 
25 # include <windows.h>
26 
27 # include <cstdio>
28 # include <string>
29 # include <system_error>
30 
31 namespace bactria
32 {
33  namespace system
34  {
41  // HMODULE <- HINSTANCE <- HANDLE <- PVOID <- void*
42  using plugin_handle_t = HMODULE;
43 
52  [[nodiscard]] auto make_last_error_string() -> std::string
53  {
54  const auto code = std::error_code{GetLastError(), std::system_category()};
55  return code.message();
56  }
57 
69  [[nodiscard]] auto open_plugin(const char* path) -> plugin_handle_t
70  {
71  auto handle = LoadLibrary(path);
72  if(handle != nullptr)
73  return handle;
74 
75  throw std::runtime_error{make_last_error_string()};
76  }
77 
91  template<typename Sig>
92  auto load_func(plugin_handle_t handle, Sig& ptr, const char* name) -> void
93  {
94  if(ptr == nullptr)
95  {
96  ptr = reinterpret_cast<Sig>(GetProcAddress(handle, name));
97  if(ptr == nullptr)
98  throw std::runtime_error{make_last_error_string()};
99  }
100  }
101 
111  auto close_plugin(plugin_handle_t handle) noexcept -> void
112  {
113  if(handle == nullptr)
114  return;
115 
116  auto err = FreeLibrary(handle);
117  if(err == 0)
118  {
119  auto errstr = make_last_error_string();
120  if(!errstr.empty())
121  std::fprintf(stderr, "WARNING: Error while closing plugin library: %s\n", errstr.c_str());
122  else
123  std::fprintf(stderr, "WARNING: Unknown error while closing plugin library.\n");
124  }
125  }
126  } // namespace system
127 } // namespace bactria
128 
129 #endif // _WIN32
bactria::system::load_func
auto load_func(plugin_handle_t handle, Sig &ptr, const char *name)
The POSIX-specific function loader.
Definition: POSIX.hpp:80
bactria::system::open_plugin
auto open_plugin(const char *path)
The POSIX-specific plugin loader.
Definition: POSIX.hpp:57
bactria::system::plugin_handle_t
void * plugin_handle_t
The POSIX-specific handle type.
Definition: POSIX.hpp:44
bactria::system::close_plugin
auto close_plugin(plugin_handle_t handle) noexcept
The POSIX-specific plugin unloader.
Definition: POSIX.hpp:99