Outils pour utilisateurs

Outils du site


gcc_lib_dynamque

Librairies dynamiques avec GCC

(Un equivalent des DLL de Windoz)
C'est la librairie libdl et ses fonctions dlxxx qui permettent cela.

Creer une librairie simple:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static int lib_load = 0;

unsigned int my_inc( unsigned int *value )
{
   if ( value )
   {
       (*value)++;
       return( (*value) );
   }

   return( 0 );
}

int my_stat( void )
{
   return( lib_load );
}

void __attribute__ ((constructor)) onload( void )
{
   lib_load++;
}

void __attribute__ ((destructor)) onunload( void )
{
   lib_load--;
}

Pour compiler:

$ gcc -g -Wall -shared -fPIC mylibtest.c -o mylibtest.so
A savoir:

Tout ce qui n'est pas static sera visible.
onload et onunload sont juste la pour montrer la possibilite d'executer du code au chargement et déchargement de la lib (mais il paraît que ce n'est pas 'portable')

Démonstration du chargement
#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>

int main( int argc, char *argv[] )
{
   void *hlib;
   int ( *my_stat )( void );
   unsigned int (*my_inc)( unsigned int * );

   if ( ! ( hlib=dlopen("./mylibtest.so", RTLD_LAZY ) ) )
   {
      printf("error: %s\n",dlerror());
      return EXIT_FAILURE;
   }

   if ( ! (my_stat = ((int(*)(void))dlsym(hlib,"my_stat")) ) )
   {
	printf("error: %s\n",dlerror());
	return EXIT_FAILURE;
   }

   printf("my stat= %d\n",my_stat());

   if ( ! (my_inc = ((unsigned int(*)(unsigned int *))dlsym(hlib,"my_inc")) ) )
   {
	printf("error: %s\n",dlerror());
	return EXIT_FAILURE;
   }

   unsigned int v = 500;
   printf("v= %u\n",my_inc(&v));

   dlclose( hlib );

   return( EXIT_SUCCESS );
}

Compiler:

$ gcc -g -Wall -o mytest mytest.c -ldl

A l'execution:

$ ./mytest
my stat= 1
v= 501

Et voila pour les premiers tests…

gcc_lib_dynamque.txt · Dernière modification : 2007/03/28 13:37 de thierry