MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
dl.cpp
Go to the documentation of this file.
1#include "mim/util/dl.h"
2
3#include "mim/util/dbg.h"
4
5#ifdef _WIN32
6# include <windows.h>
7#else
8# include <dlfcn.h>
9#endif
10
11namespace mim::dl {
12
13void* open(const char* file) {
14#ifdef _WIN32
15 if (HMODULE handle = LoadLibraryA(file)) {
16 return static_cast<void*>(handle);
17 } else {
18 error("could not load plugin '{}' due to error '{}'\n"
19 "see https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes\n",
20 file, GetLastError());
21 }
22#else
23 if (void* handle = dlopen(file, RTLD_NOW))
24 return handle;
25 else if (auto err = dlerror())
26 error("could not load plugin '{}' due to error '{}'\n", file, err);
27 else
28 error("could not load plugin '{}'\n", file);
29#endif
30}
31
32void* get(void* handle, const char* symbol) {
33#ifdef _WIN32
34 if (auto addr = GetProcAddress(static_cast<HMODULE>(handle), symbol)) {
35 return reinterpret_cast<void*>(addr);
36 } else {
37 error("could not find symbol '{}' in plugin due to error '{}'\n"
38 "see (https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes)\n",
39 symbol, GetLastError());
40 }
41#else
42 dlerror(); // clear error state
43 void* addr = dlsym(handle, symbol);
44 if (auto err = dlerror())
45 error("could not find symbol '{}' in plugin due to error '{}' \n", symbol, err);
46 else
47 return addr;
48#endif
49}
50
51void close(void* handle) {
52#ifdef _WIN32
53 if (!FreeLibrary(static_cast<HMODULE>(handle))) error("FreeLibrary() failed\n");
54#else
55 if (auto err = dlclose(handle)) error("dlclose() failed with error code '{}'\n", err);
56#endif
57}
58
59} // namespace mim::dl
Definition dl.h:6
void * get(void *handle, const char *symbol_name)
Definition dl.cpp:32
void close(void *handle)
Definition dl.cpp:51
void * open(const char *filename)
Definition dl.cpp:13
void error(std::format_string< Args... > fmt, Args &&... args)
Wraps std::format to throw T with a formatted message.
Definition dbg.h:17