Created
July 8, 2014 17:50
-
-
Save Justasic/4a750607d3a12c4b2667 to your computer and use it in GitHub Desktop.
An example class which shows how you can associate a shared object with a class in linux.
This file contains 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
/* This file is public domain although credit would be nice :) */ | |
#include <unistd.h> | |
#include <cstdio> | |
#include <iostream> | |
#include <cstdlib> | |
#include <string> | |
#include <dlfcn.h> | |
#include <cassert> | |
class DynamicLibrary | |
{ | |
protected: | |
void *handle; | |
std::string name; | |
public: | |
DynamicLibrary(const std::string &str) : handle(nullptr), name(str) | |
{ | |
assert(!str.empty()); | |
this->handle = dlopen(str.c_str(), RTLD_LAZY); | |
if (!this->handle) | |
{ | |
fprintf(stderr, "Failed to open module %s: %s\n", str.c_str(), dlerror()); | |
return; | |
} | |
} | |
~DynamicLibrary() | |
{ | |
if (this->handle) | |
dlclose(this->handle); | |
} | |
template<typename T> T ResolveSymbol(const std::string &str) | |
{ | |
// Union-cast to get around C++ warnings. | |
union { | |
T func; | |
void *ptr; | |
} fn; | |
fn.ptr = dlsym(this->handle, str.c_str()); | |
if (!fn.ptr) | |
{ | |
fprintf(stderr, "Failed to resolve symbol %s: %s\n", str.c_str(), dlerror()); | |
return T(); | |
} | |
return fn.func; | |
} | |
std::string GetName() const | |
{ | |
return this->name; | |
} | |
}; | |
int main(int argc, char **argv) | |
{ | |
DynamicLibrary dl("/tmp/test.so"); | |
printf("Hello %s!\n", dl.ResolveSymbol<const char *(*)(void)>("hello")()); | |
return EXIT_FAILURE; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment