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 ("libm.so", RTLD_LAZY);
    if (!handle) {
        fprintf (stderr, "%s\n", dlerror());
        exit(1);
    }

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

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

   dlclose(handle);
    return 0;
} // end of main

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

No comments:

Post a Comment