UraniumCompute 0.1.0
A GPU accelerated parallel task scheduler
DynamicLibrary.h
1#pragma once
2#include <UnCompute/Base/PlatformInclude.h>
3#include <UnCompute/Memory/Memory.h>
4
5#if UN_WINDOWS
6# define UN_LoadLibrary(name) LoadLibraryA(name)
7# define UN_GetFunctionAddress(handle, name) reinterpret_cast<void*>(GetProcAddress(static_cast<HMODULE>(handle), name))
8# define UN_FreeLibrary(handle) FreeLibrary(static_cast<HMODULE>(handle))
9#else
10# define UN_LoadLibrary(name) dlopen(name, RTLD_LAZY)
11# define UN_GetFunctionAddress(handle, name) dlsym(handle, name)
12# define UN_FreeLibrary(handle) dlclose(handle)
13#endif
14
15namespace UN
16{
18 class DynamicLibrary : public Object<IObject>
19 {
20 void* m_NativeHandle = nullptr;
21
22 void* GetFunctionImpl(const char* functionName);
23
24 public:
25 inline DynamicLibrary() = default;
26 ~DynamicLibrary() override;
27
28 DynamicLibrary(const DynamicLibrary&) = delete;
29 DynamicLibrary& operator=(const DynamicLibrary&) = delete;
31 DynamicLibrary& operator=(DynamicLibrary&&) = delete;
32
38 ResultCode Init(std::string_view name);
39
41 void Unload();
42
51 template<class FPtr>
52 inline ResultCode GetFunction(const char* functionName, FPtr* pResult)
53 {
54 void* proc = GetFunctionImpl(functionName);
55
56 if (proc)
57 {
58 *pResult = reinterpret_cast<FPtr>(proc);
59 return ResultCode::Success;
60 }
61
62 return ResultCode::Fail;
63 }
64
65 inline static ResultCode Create(DynamicLibrary** ppLibrary)
66 {
67 *ppLibrary = AllocateObject<DynamicLibrary>();
68 (*ppLibrary)->AddRef();
69 return ResultCode::Success;
70 }
71 };
72
73 inline ResultCode DynamicLibrary::Init(std::string_view name)
74 {
75 std::string fullName(name);
76 fullName += UN_DLL_EXTENSION;
77 m_NativeHandle = UN_LoadLibrary(fullName.c_str());
78
79 UN_Error(m_NativeHandle, "Library '{}{}' was not loaded due to an error", name, UN_DLL_EXTENSION);
80 return m_NativeHandle ? ResultCode::Success : ResultCode::Fail;
81 }
82
83 inline void* DynamicLibrary::GetFunctionImpl(const char* functionName)
84 {
85 return UN_GetFunctionAddress(m_NativeHandle, functionName);
86 }
87
88 inline DynamicLibrary::~DynamicLibrary()
89 {
90 Unload();
91 }
92
94 {
95 if (m_NativeHandle == nullptr)
96 {
97 return;
98 }
99
100 UNLOG_Info("Unloading dynamic library at {}...", m_NativeHandle);
101 UN_FreeLibrary(m_NativeHandle);
102 m_NativeHandle = nullptr;
103 }
104} // namespace UN
A class for loading and unloading DLLs.
Definition: DynamicLibrary.h:19
void Unload()
Unload the library.
Definition: DynamicLibrary.h:93
ResultCode GetFunction(const char *functionName, FPtr *pResult)
Load a function entry point from the DLL.
Definition: DynamicLibrary.h:52
ResultCode Init(std::string_view name)
Load a library with specified name.
Definition: DynamicLibrary.h:73
Base class for dynamic reference counted objects.
Definition: Object.h:51