Skip to content

Instantly share code, notes, and snippets.

@howardlau1999
Created December 18, 2018 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save howardlau1999/2233f19060b636b4d99755ccee0a085d to your computer and use it in GitHub Desktop.
Save howardlau1999/2233f19060b636b4d99755ccee0a085d to your computer and use it in GitHub Desktop.
Linux dlfcn
// 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;
}
// g++ -fPIC -shared shared_sum.cpp -o libctest.so
#include <iostream>
extern "C" {
int add(int a, int b) { return a * b; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment