-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibraryloader.h
More file actions
47 lines (43 loc) · 1.26 KB
/
libraryloader.h
File metadata and controls
47 lines (43 loc) · 1.26 KB
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
#pragma once
#ifdef _WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#include <stdexcept>
#include <string>
class LibraryLoader {
public:
LibraryLoader(const char *libraryName) {
#ifdef _WIN32
handle = reinterpret_cast<size_t>(LoadLibraryA(libraryName));
if (handle == 0)
throw std::runtime_error("Error loading library: " + std::to_string(GetLastError()));
#else
handle = reinterpret_cast<size_t>(dlopen(libraryName, RTLD_LAZY));
if (handle == 0)
throw std::runtime_error("Error loading library: " + std::string(dlerror()));
#endif
}
// 获取符号地址
void *getSymbol(const char *symbolName) {
if (handle == 0) throw std::runtime_error("Library not loaded");
#ifdef _WIN32
void *symbol=(void *)GetProcAddress(reinterpret_cast<HMODULE>(handle), symbolName);
#else
void *symbol=dlsym(reinterpret_cast<void*>(handle), symbolName);
#endif
return symbol;
}
~LibraryLoader() {
if (handle != 0) {
#ifdef _WIN32
FreeLibrary(reinterpret_cast<HMODULE>(handle));
#else
dlclose(reinterpret_cast<void*>(handle));
#endif
}
handle = 0;
}
size_t handle; // 库句柄
};