-
Notifications
You must be signed in to change notification settings - Fork 1
/
dynamicro.h
109 lines (84 loc) · 2 KB
/
dynamicro.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
#ifndef _DYNAMICRO_H_
#define _DYNAMICRO_H_
#include <string>
#include <map>
#include <functional>
#include <type_traits>
#include <utility>
#if defined(__unix__)
#include <dlfcn.h>
#include <iostream>
#elif defined(_WIN32)
#include <Windows.h>
#endif
class Dynamicro {
public:
Dynamicro() : m_hMod(nullptr) {
}
~Dynamicro() {
unload();
}
inline bool load(const std::string& dllPath)
{
#ifdef WIN32
m_hMod = LoadLibraryA(dllPath.data());
#elif defined (__GNUC__) && defined(__unix__)
m_hMod = dlopen(dllPath.data(), RTLD_NOW);
dlerror();
#endif // WIN32
if (m_hMod == nullptr)
{
printf("load library failed\n");
return false;
}
return true;
}
inline bool unload()
{
if (m_hMod == nullptr)
return true;
#ifdef WIN32
auto b = FreeLibrary(m_hMod);
#elif defined (__GNUC__) && defined(__unix__)
auto b = dlclose(m_hMod);
#endif // WIN32
if (!b)
return false;
m_hMod = nullptr;
return true;
}
template<typename T>
std::function<T> get(const std::string &funcName) {
auto it = m_map.find(funcName);
if (it == m_map.end()) {
#ifdef _WIN32
GetProcAddress(m_hMod, funcName.c_str());
#elif __unix__
dlsym(m_hMod, funcName.data());
#endif // WIN32
if (!m_hMod)
return nullptr;
m_map.insert({ funcName, m_hMod });
it = m_map.find(funcName);
}
return std::function<T>((T *)(it->second));
};
template<typename T, typename... Args>
typename std::result_of<std::function<T>(Args...)>::type exec(const std::string &funcName, Args &&... args) {
auto f = get<T>(funcName);
if (f == nullptr) {
throw std::exception(("can not find this function: " + funcName).c_str());
}
return f(std::forward<Args>(args)...);
};
private:
#ifdef _WIN32
using moduleType = HMODULE;
using addressType = FARPROC;
#elif __unix__
using moduleType = void *;
#endif // WIN32
moduleType m_hMod;
std::map<std::string, moduleType> m_map;
};
#endif // !_DYNAMICRO_H_