You need to code:
// file ds.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
void hello ()
{
printf ("hello world
");
}
int main (int argc, char **argv)
{
char *buf = "hello";
void *hndl = dlopen (NULL, RTLD_LAZY);
if (!hndl) { fprintf(stderr, "dlopen failed: %s
", dlerror());
exit (EXIT_FAILURE); };
void (*fptr) (void) = dlsym (hndl, buf);
if (fptr != NULL)
fptr ();
else
fprintf(stderr, "dlsym %s failed: %s
", buf, dlerror());
dlclose (hndl);
}
Read carefully dlopen(3), always check the success of the dlopen
& dlsym
functions there, and use dlerror
on failure.
and compile the above ds.c
file with
gcc -std=c99 -Wall -rdynamic ds.c -o ds -ldl
Don't forget the -Wall
to get all warnings and the -rdynamic
flag (to be able to dlsym
your own symbols which should go into the dynamic table).
On my Debian/Sid/x86-64 system (with gcc
version 4.8.2, and libc6
version 2.17-93 providing the -ldl
, kernel 3.11.6 compiled by me, binutils
package 2.23.90 providing ld
), the execution of ./ds
gives the expected output:
% ./ds
hello world
and even:
% ltrace ./ds
__libc_start_main(0x4009b3, 1, 0x7fff1d0088b8, 0x400a50, 0x400ae0 <unfinished ...>
dlopen(NULL, 1) = 0x7f1e06c9e1e8
dlsym(0x7f1e06c9e1e8, "hello") = 0x004009a0
puts("hello world"hello world
) = 12
dlclose(0x7f1e06c9e1e8) = 0
+++ exited (status 0) +++
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…