Created
December 30, 2016 17:44
-
-
Save saucecode/3fad8e81f6320b509bdff27fb7bdd2cc to your computer and use it in GitHub Desktop.
dlopen example
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++ -fPIC -c hello.cpp | |
g++ -shared -o hello.so hello.o | |
g++ main.cpp -ldl |
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
#include <iostream> | |
extern "C" int hello(){ | |
std::cout << "dicks dicks dicks!\n"; | |
return 42; | |
} |
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
#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