Wednesday, December 8, 2010

Dynamic Lib using dlopen and dlsym

dlopen system call loads dynamic library and returns handle to dynamic library.  If dlopen() fails it returns NULL
dlsym takes the library handle returnd by dlopen and symbol name as input, and  returns the address where that symbol is loaded. If the symbol is not found, dlsym returns NULL
dlerror returns NULL if no errors have occurred since initialization or since it was last called. (Calling dlerror() twice consecutively, will always result in the second call returning NULL.)

#include <stdio.h>
#include <dlfcn.h>

typedef void *(*func_t)(hooks *);

int main()
    // declare handle variable for dynamic library
    void *handle;
    double (*cosine)(double);

    // open the dynamic library
    handle = dlopen ("", RTLD_LAZY);
    if (!handle) {
        fprintf (stderr, "%s\n", dlerror());

    func_t initializer_fn = (func_t)dlsym(handle, "initializer");
    if (initializer_fn) {
           // call function

    // Initialize cosine with function pointer of "cos".
   cosine = dlsym(handle, "cos");
   // call "cos" function using function pointer
   fprintf (stderr, "%f\n", (*cosine)(2.0));

    return 0;
} // end of main

// functions defined in library file
void initializer(hooks *libifc)

No comments:

Post a Comment