Created
December 18, 2018 06:42
-
-
Save howardlau1999/2233f19060b636b4d99755ccee0a085d to your computer and use it in GitHub Desktop.
Linux dlfcn
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
// g++ -rdynamic -o main main.c -ldl | |
#include <dlfcn.h> | |
#include <sys/stat.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
#include <iostream> | |
using namespace std; | |
typedef int (*calc_func)(int, int); | |
const char *LIB_PATH = "./libctest.so"; | |
int main() { | |
ino_t so_ino = -1; | |
void *handle = nullptr; | |
char *error = nullptr; | |
for (;;) { | |
string function_name; | |
cout << "What function (type `quit` to exit): "; | |
cin >> function_name; | |
if (function_name == "quit") break; | |
struct stat attr; | |
if (stat(LIB_PATH, &attr) == 0 && attr.st_ino != so_ino) { | |
if (handle) { | |
dlclose(handle); | |
} | |
handle = dlopen(LIB_PATH, RTLD_LAZY); | |
if (!handle) { | |
cerr << dlerror() << endl; | |
exit(EXIT_FAILURE); | |
} | |
calc_func func = reinterpret_cast<calc_func>( | |
dlsym(handle, function_name.c_str())); | |
if (error = dlerror()) { | |
cerr << error << endl; | |
continue; | |
} else { | |
int a, b; | |
cout << "Input two numbers: "; | |
cin >> a >> b; | |
cout << func(a, b) << endl; | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment