Advertisement
obernardovieira

Run-Time Call Library (Linux)

Mar 6th, 2014
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. //calllib.cpp
  2.  
  3. #include <iostream>
  4.  
  5. #ifdef __cplusplus
  6. extern "C" {
  7. #endif
  8.  
  9.     void hello() {
  10.         std::cout << "hello" << '\n';
  11.     }
  12.  
  13. #ifdef __cplusplus
  14. }
  15. #endif
  16.  
  17. //compile :
  18. //g++ -c -Wall -Werror -fPIC calllib.c
  19. //g++ -shared -o libcalllib.so calllib.o
  20.  
  21.  
  22. //mylib.cpp
  23.  
  24. #include <dlfcn.h>
  25. #include <iostream>
  26.  
  27. using namespace std;
  28.  
  29. int main() {
  30.  
  31.     cout << "C++ dlopen demo\n\n";
  32.  
  33.     // open the library
  34.     cout << "Opening hello.so...\n";
  35.     void* handle = dlopen("./libcalllib.so", RTLD_LAZY);
  36.    
  37.     if (!handle) {
  38.         cerr << "Cannot open library: " << dlerror() << '\n';
  39.         return 1;
  40.     }
  41.    
  42.     // load the symbol
  43.     cout << "Loading symbol hello...\n";
  44.     typedef void (*hello_t)();
  45.  
  46.     // reset errors
  47.     dlerror();
  48.     hello_t hello = (hello_t) dlsym(handle, "hello");
  49.     const char *dlsym_error = dlerror();
  50.     if (dlsym_error) {
  51.         cerr << "Cannot load symbol 'hello': " << dlsym_error <<
  52.             '\n';
  53.         dlclose(handle);
  54.         return 1;
  55.     }
  56.    
  57.     // use it to do the calculation
  58.     cout << "Calling hello...\n";
  59.     hello();
  60.    
  61.     // close the library
  62.     cout << "Closing library...\n";
  63.     dlclose(handle);
  64. }
  65.  
  66. //compile :
  67. //g++ mylib.cpp -ldl -o mylib
  68.  
  69. //and then ./mylib to execute
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement