-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathModuleLoader.cpp
More file actions
66 lines (61 loc) · 1.56 KB
/
Copy pathModuleLoader.cpp
File metadata and controls
66 lines (61 loc) · 1.56 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "ModuleLoader.h"
#include "Logger.h"
#include <iostream>
#include <functional>
#if _WIN32
#include <Windows.h>
#elif __linux__
#include <dlfcn.h>
#endif
namespace sh::core
{
auto ModuleLoader::Load(const std::filesystem::path& moduleDir) -> std::optional<Plugin>
{
#if _WIN32
HMODULE handle = LoadLibraryExW(moduleDir.wstring().c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (handle == nullptr)
{
SH_ERROR_FORMAT("Error load module: {}", moduleDir.u8string());
return {};
}
std::function<void()> fnInit{ GetProcAddress(handle, "Init") };
if (fnInit)
fnInit();
std::function<Plugin()> fnGetPluginInfo = reinterpret_cast<Plugin(*)()>(GetProcAddress(handle, "GetPluginInfo"));
Plugin plugin{};
if (fnGetPluginInfo)
{
plugin = fnGetPluginInfo();
}
#elif __linux__
void* handle = dlopen(moduleDir.c_str(), RTLD_LAZY);
if (!handle) {
SH_ERROR_FORMAT("Error load module: {}", moduleDir.u8string());
return {};
}
std::function<void()> fnInit{ reinterpret_cast<void*(*)()>(dlsym(handle, "Init")) };
fnInit();
Plugin(*fnGetPluginInfo)() = (Plugin(*)())dlsym(handle, "GetPluginInfo");
Plugin plugin{};
if (fnGetPluginInfo)
{
plugin = fnGetPluginInfo();
}
#endif
plugin.handle = handle;
plugin.path = moduleDir;
return plugin;
}
SH_CORE_API void ModuleLoader::Clean(const Plugin& plugin)
{
if (plugin.handle == nullptr)
return;
#if _WIN32
auto result = FreeLibrary(reinterpret_cast<HMODULE>(plugin.handle));
assert(result);
#elif __linux__
auto result = dlclose(plugin.handle);
assert(result);
#endif
}
}