Skip to content

Instantly share code, notes, and snippets.

@mwicat
Created July 25, 2012 13:10
Show Gist options
  • Select an option

  • Save mwicat/3176112 to your computer and use it in GitHub Desktop.

Select an option

Save mwicat/3176112 to your computer and use it in GitHub Desktop.
Run main function from shared library
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv)
{
void *imglib;
int (*extopenimage)(int, char**);
int imghandle;
imglib = dlopen("/usr/lib/apache2/mpm-prefork/apache2", RTLD_LAZY);
if ( imglib != NULL ) {
/* extopenimage = (int (*)(const char *))dlsym(imglib,...)
"man dlopen" says that C99 standard leaves casting from
"void *" to a function pointer undefined. The following is the
POSIX.1-2003 workaround found in man */
*(void **)(&extopenimage) = dlsym(imglib, "main");
/* the following works with gcc, gives no warning even with
-Wall -std=c99 -pedantic options... :D */
/* extopenimage = dlsym(imglib, "openimage"); */
imghandle = extopenimage(argc, argv);
} else {
printf("fail\n");
}
printf("opened with handle %d\n", imghandle);
/* ... */
if (imglib != NULL ) dlclose(imglib);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment