Created
November 26, 2019 11:02
-
-
Save untodesu/57eb731548bb3edc608b39faa5be1971 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include "./dll.hh" | |
| using namespace std; | |
| //Implementation for WINNT | |
| #if defined(_WIN32) | |
| #include <Windows.h> | |
| //Copy std::string to wstring | |
| static void string_to_wstring(const string &source, wstring &destination) | |
| { | |
| destination.clear(); | |
| for(size_t i = 0; i < source.size(); i++) { | |
| destination += source[i]; | |
| } | |
| } | |
| //Constructor | |
| dll::dll(const string &filename) : m_Handle(nullptr) | |
| { | |
| wstring w_filename; | |
| string_to_wstring(filename, w_filename); | |
| m_Handle = (void *)LoadLibrary(w_filename.c_str()); | |
| if(m_Handle == nullptr) { | |
| int error = GetLastError(); | |
| fprintf(stderr, "Couldn't load DLL through WINAPI.\nError code: %d\n", error); | |
| } | |
| } | |
| //Destructor | |
| dll::~dll() | |
| { | |
| if(m_Handle != nullptr) { | |
| FreeLibrary((HMODULE)m_Handle); | |
| } | |
| } | |
| //Get symbol | |
| void * dll::get_sym(const string &sym) | |
| { | |
| if(m_Handle) { | |
| void * data = GetProcAddress((HMODULE)m_Handle, sym.c_str()); | |
| return data; | |
| } | |
| return nullptr; | |
| } | |
| //Implementation for POSIX | |
| #elif defined(__unix__) | |
| #include <dlfcn.h> | |
| //Constructor | |
| dll::dll(const string &filename) : m_Handle(nullptr) | |
| { | |
| m_Handle = dlopen(filename.c_str(), RTLD_LAZY); | |
| if(m_Handle == nullptr) { | |
| fprintf(stderr, "Couldn't load SO through POSIX API.\n%s\n", dlerror()); | |
| } | |
| } | |
| //Destructor | |
| dll::~dll() | |
| { | |
| if(m_Handle != nullptr) { | |
| dlclose(m_Handle); | |
| } | |
| } | |
| //Get symbol | |
| void * dll::get_sym(const string &sym) | |
| { | |
| if(m_Handle) { | |
| void * data = dlsym(m_Handle, sym.c_str()); | |
| return data; | |
| } | |
| return nullptr; | |
| } | |
| #endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #ifndef _DLL_HH | |
| #define _DLL_HH | |
| #include <string> | |
| //A DLL | |
| class dll { | |
| private: | |
| void *m_Handle; | |
| public: | |
| dll(const std::string &filename); | |
| ~dll(); | |
| void * get_sym(const std::string &sym); | |
| }; | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment