| 1 | #ifndef SHAREDOBJ_H |
| 2 | #define SHAREDOBJ_H |
| 3 | |
| 4 | #include <stdio.h> |
| 5 | #include <stdlib.h> |
| 6 | #include <string.h> |
| 7 | #include <dlfcn.h> |
| 8 | #include <errno.h> |
| 9 | |
| 10 | // A wrapper around a shared object. |
| 11 | // |
| 12 | // Responsible for opening, accessing and closing a shared object. |
| 13 | // |
| 14 | |
| 15 | class sharedObj { |
| 16 | public: |
| 17 | |
| 18 | sharedObj(char *p) { |
| 19 | path = new char [strlen(p) + 1]; |
| 20 | strcpy(path, p); |
| 21 | |
| 22 | handle = dlopen(path, RTLD_NOW); |
| 23 | if (handle == 0L) { |
| 24 | fprintf(stderr, "ERROR: Failed to open shared object '%s'\n%s\n", path, dlerror()); |
| 25 | exit(1); |
| 26 | } |
| 27 | }; |
| 28 | |
| 29 | ~sharedObj() { |
| 30 | if (dlclose(handle)) { |
| 31 | fprintf(stderr, "WARNING: Failed to close shared object '%s'\n%s\n", path, dlerror()); |
| 32 | } |
| 33 | delete [] path; |
| 34 | }; |
| 35 | |
| 36 | bool exists(char *name) { |
| 37 | void *ptr = 0L; |
| 38 | |
| 39 | errno = 0; |
| 40 | ptr = dlsym(handle, name); |
| 41 | if (errno) { |
| 42 | fprintf(stderr, "ERROR: Failed to find symbol '%s' in shared object '%s'\n%s\n", name, path, dlerror()); |
| 43 | exit(1); |
| 44 | } |
| 45 | |
| 46 | return(ptr != 0L); |
| 47 | } |
| 48 | |
| 49 | void *get(char const *name) { |
| 50 | void *ptr = 0L; |
| 51 | |
| 52 | errno = 0; |
| 53 | ptr = dlsym(handle, name); |
| 54 | if (errno) { |
| 55 | fprintf(stderr, "ERROR: Failed to find symbol '%s' in shared object '%s'\n%s\n", name, path, dlerror()); |
| 56 | exit(1); |
| 57 | } |
| 58 | if (ptr == 0L) { |
| 59 | fprintf(stderr, "ERROR: Symbol '%s' not present in shared object '%s'\n", name, path); |
| 60 | exit(1); |
| 61 | } |
| 62 | |
| 63 | return(ptr); |
| 64 | }; |
| 65 | |
| 66 | private: |
| 67 | char *path; |
| 68 | void *handle; |
| 69 | }; |
| 70 | |
| 71 | |
| 72 | #endif // SHAREDOBJ_H |