Skip to content

Commit

Permalink
init module
Browse files Browse the repository at this point in the history
  • Loading branch information
K1ngst0m committed Oct 26, 2023
1 parent 64ba2e8 commit 11f26a7
Show file tree
Hide file tree
Showing 2 changed files with 118 additions and 0 deletions.
75 changes: 75 additions & 0 deletions engine/module/module.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#include "module.h"
#include "common/logger.h"
#include <stdexcept>

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#else
#include <dlfcn.h>
#endif

namespace aph
{
Module::Module(const char* path)
{
#ifdef _WIN32
m_module = LoadLibrary(path);
if(!m_module)
CM_LOG_ERR("Failed to load dynamic library.\n");
#else
m_dylib = dlopen(path, RTLD_NOW);
if(!m_dylib)
CM_LOG_ERR("Failed to load dynamic library.\n");
#endif
}

Module::Module(Module&& other) noexcept
{
*this = std::move(other);
}

Module& Module::operator=(Module&& other) noexcept
{
close();
#ifdef _WIN32
m_module = other.m_module;
other.m_module = nullptr;
#else
m_dylib = other.m_dylib;
other.m_dylib = nullptr;
#endif
return *this;
}

void Module::close()
{
#ifdef _WIN32
if(m_module)
FreeLibrary(m_module);
m_module = nullptr;
#else
if(m_dylib)
dlclose(m_dylib);
m_dylib = nullptr;
#endif
}

Module::~Module()
{
close();
}

void* Module::getSymbolInternal(const char* symbol)
{
#ifdef _WIN32
if(m_module)
return (void*)GetProcAddress(m_module, symbol);
else
return nullptr;
#else
if(m_dylib)
return dlsym(m_dylib, symbol);
return nullptr;
#endif
}
} // namespace aph
43 changes: 43 additions & 0 deletions engine/module/module.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#ifndef MODULE_H_
#define MODULE_H_

namespace aph
{
class Module
{
public:
Module() = default;
explicit Module(const char* path);
~Module();

Module(Module&& other) noexcept;
Module& operator=(Module&& other) noexcept;

template <typename Func>
Func getSymbol(const char* symbol)
{
return reinterpret_cast<Func>(getSymbolInternal(symbol));
}

explicit operator bool() const
{
#if _WIN32
return m_module != nullptr;
#else
return m_dylib != nullptr;
#endif
}

private:
#if _WIN32
HMODULE m_module = nullptr;
#else
void* m_dylib = nullptr;
#endif

void* getSymbolInternal(const char* symbol);
void close();
};
} // namespace aph

#endif // MODULE_H_

0 comments on commit 11f26a7

Please sign in to comment.