Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //calllib.cpp
- #include <iostream>
- #ifdef __cplusplus
- extern "C" {
- #endif
- void hello() {
- std::cout << "hello" << '\n';
- }
- #ifdef __cplusplus
- }
- #endif
- //compile :
- //g++ -c -Wall -Werror -fPIC calllib.c
- //g++ -shared -o libcalllib.so calllib.o
- //mylib.cpp
- #include <dlfcn.h>
- #include <iostream>
- using namespace std;
- int main() {
- cout << "C++ dlopen demo\n\n";
- // open the library
- cout << "Opening hello.so...\n";
- void* handle = dlopen("./libcalllib.so", RTLD_LAZY);
- if (!handle) {
- cerr << "Cannot open library: " << dlerror() << '\n';
- return 1;
- }
- // load the symbol
- cout << "Loading symbol hello...\n";
- typedef void (*hello_t)();
- // reset errors
- dlerror();
- hello_t hello = (hello_t) dlsym(handle, "hello");
- const char *dlsym_error = dlerror();
- if (dlsym_error) {
- cerr << "Cannot load symbol 'hello': " << dlsym_error <<
- '\n';
- dlclose(handle);
- return 1;
- }
- // use it to do the calculation
- cout << "Calling hello...\n";
- hello();
- // close the library
- cout << "Closing library...\n";
- dlclose(handle);
- }
- //compile :
- //g++ mylib.cpp -ldl -o mylib
- //and then ./mylib to execute
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement