-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathDynamicLibrary.h
124 lines (115 loc) · 3.01 KB
/
DynamicLibrary.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#pragma once
#include <filesystem>
#include <map>
#include <string>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#undef NOMINMAX
#else
#include <dlfcn.h>
#endif
class DynamicLibrary
{
private:
static DynamicLibrary* getInstance()
{
static DynamicLibrary dl;
return &dl;
}
DynamicLibrary(DynamicLibrary&) = delete;
DynamicLibrary& operator=(DynamicLibrary&) = delete;
private:
DynamicLibrary()
{
}
//free loaded dynamic libraries automatically when destruction
~DynamicLibrary()
{
for (auto dl : dynamic_libraries_)
{
if (dl.second)
{
#ifdef _WIN32
FreeLibrary(dl.second);
#else
dlclose(dl.second);
#endif
}
}
}
private:
#ifdef _WIN32
std::map<std::string, HMODULE> dynamic_libraries_;
#else
std::map<std::string, void*> dynamic_libraries_;
#endif
public:
static void* loadDynamicLibrary(std::string library_name)
{
if (library_name.find(".") == std::string::npos)
{
#ifdef _WIN32
library_name = library_name + ".dll";
#else
library_name = "lib" + library_name + ".so";
#endif
}
auto dl = getInstance();
if (dl->dynamic_libraries_.count(library_name) == 0)
{
if (library_name.find_first_of("/\\") != std::string::npos)
{
library_name = std::filesystem::absolute(library_name).string();
}
#ifdef _WIN32
auto hlib = LoadLibraryA(library_name.c_str());
#else
auto hlib = dlopen(library_name.c_str(), RTLD_LAZY);
#endif
dl->dynamic_libraries_[library_name] = hlib;
//if (hlib)
//{
// fprintf(stdout, "Loaded dynamic library %s\n", library_name.c_str());
//}
//else
//{
// fprintf(stdout, "Failed to load dynamic library %s\n", library_name.c_str());
//}
}
return dl->dynamic_libraries_[library_name];
}
static void* getFunction(const std::string& library_name, const std::string& function_name)
{
auto dl = getInstance()->loadDynamicLibrary(library_name);
void* func = nullptr;
if (dl)
{
#ifdef _WIN32
func = GetProcAddress((HINSTANCE)dl, function_name.c_str());
#else
func = dlsym(dl, function_name.c_str());
#endif
//fprintf(stdout, "Loaded function %s\n", function_name.c_str());
}
else
{
//fprintf(stdout, "Failed to load function %s\n", function_name.c_str());
}
return func;
}
static void freeDynamicLibrary(const std::string& library_name)
{
auto dl = getInstance();
if (dl->dynamic_libraries_.count(library_name) > 0)
{
auto hlib = dl->dynamic_libraries_[library_name];
#ifdef _WIN32
FreeLibrary(hlib);
#else
dlclose(hlib);
#endif
dl->dynamic_libraries_.erase(library_name);
}
}
};