C/C++ Programming Pearls

dlopen.c
/*
   program: dlopen.c
   dependences: plugin.so

   description: This program is an example of dlopen
   
   compiling this program:
gcc -o plugin.so -shared plugin.c
gcc -ldl -o dlopen dlopen.c

   output:
   $./dlopen
in function one.
in function two.
in function three.


*/

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

main(int argc, char **argv)
{
  void *hndl;
  void (*fptr)(void);
  
  hndl = dlopen("./plugin.so",RTLD_LAZY);
  if ( hndl == NULL ){
    fprintf(stderr,"%: dlopen failure: %s\n",argv[0],dlerror());
    exit(1);
  }

  fptr = (void(*)(void)) dlsym(hndl,"one");
  if ( fptr == NULL) {
    fprintf(stderr, "%s: dlsym failure calling one: %s\n",argv[0],dlerror());
    exit(2);
  }
  fptr();

  fptr = (void(*)(void)) dlsym(hndl,"two");
  if ( fptr == NULL) {
    fprintf(stderr, "%s: dlsym failure calling two: %s\n",argv[0],dlerror());
    exit(3);
  }
  fptr();

  fptr = (void(*)(void)) dlsym(hndl,"three");
  if ( fptr == NULL) {
    fprintf(stderr, "%s: dlsym failure calling three: %s\n",argv[0],dlerror());
    exit(4);
  }
  fptr();

  dlclose(hndl);
}

plugin.c
/*
   program: plugin.c
   dependences: dlopen.c

   description: This prgram gets call by dlopen.

*/

#include <stdio.h>

void one(void)
{
  printf("in function one.\n");
}

void two(void)
{
  printf("in function two.\n");
}

void three(void)
{
  printf("in function three.\n");
}

SourceForge.net Logo