Skip to content

Instantly share code, notes, and snippets.

@saucecode
Created December 30, 2016 17:44
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 saucecode/3fad8e81f6320b509bdff27fb7bdd2cc to your computer and use it in GitHub Desktop.
Save saucecode/3fad8e81f6320b509bdff27fb7bdd2cc to your computer and use it in GitHub Desktop.
dlopen example
g++ -fPIC -c hello.cpp
g++ -shared -o hello.so hello.o
g++ main.cpp -ldl
#include <iostream>
extern "C" int hello(){
std::cout << "dicks dicks dicks!\n";
return 42;
}
#include <iostream>
#include <dlfcn.h>
using namespace std;
int main(){
void *handle = dlopen("./hello.so", RTLD_LAZY);
if(!handle){
cout << "Failed to open library hello.so\n";
return 1;
}
cout << "Loading symbol...\n";
typedef int (*hello_t)();
dlerror();
hello_t hello = (hello_t) dlsym(handle, "hello");
const char *dlsym_error = dlerror();
if(dlsym_error){
cout << "Cannot load symbol hello\n";
dlclose(handle);
return 1;
}
cout << "Calling function...\n";
int x = hello();
cout << "Got: " << x << "\n";
dlclose(handle);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment