, , (.. switch). SO ( gcc -std=c99 -Wall -rdynamic ds.c -o ds -ldl, ds.c): ( , , ..: , ).
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
void hello ()
{
printf ("hello world\n");
}
int main (int argc, char **argv)
{
char *buf = "hello";
void *hndl = dlopen (NULL, RTLD_LAZY);
if (!hndl) { fprintf(stderr, "dlopen failed: %s\n", dlerror());
exit (EXIT_FAILURE); };
void (*fptr) (void) = dlsym (hndl, buf);
if (fptr != NULL)
fptr ();
else
fprintf(stderr, "dlsym %s failed: %s\n", buf, dlerror());
dlclose (hndl);
}
, /. , , - , - , , . , , , .
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
void foo1(void);
void foo2(void);
void foo3(void);
int main (int argc, char **argv)
{
void *hndl = dlopen (NULL, RTLD_LAZY);
if (!hndl) { fprintf(stderr, "dlopen failed: %s\n", dlerror());
exit (EXIT_FAILURE); };
for (int i = 0; i < argc; i++) {
void (*fptr) (void) = dlsym(hndl, argv[i]);
if (fptr != NULL)
fptr();
else
fprintf(stderr, "dlsym %s failed: %s\n", argv[i], dlerror());
}
dlclose (hndl);
return 0;
}
void foo1()
{
printf("hello world\n");
}
void foo2()
{
printf("Mello world\n");
}
void foo3()
{
printf("Jello world\n");
}
./ds foo1 foo2 foo3 foo1
dlsym ./ds failed: ./ds: undefined symbol: ./ds
hello world
Mello world
Jello world
hello world