1

I have a program that calls dlopen (with RTLD_NOW) to dynamically load a library whose full path is specified during run time, but is not known when the program is first executed. The specified library was dynamically linked against ANOTHER .so file whose location also is not known until after the program is started, but is known before dlopen is called. Any thoughts on how I can get this scenario to work? Thanks!

4

1 回答 1

0

将其传递给第一个动态加载的库中的方法

三.c:

#include <stdio.h>

void
doit()
{
   printf("Success\n");
}

二.c:

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

void go(const char* location)
{
   void *handle;
   void (*doit)(void);
   char *error;

   handle = dlopen(location, RTLD_LAZY);
   if (!handle) {
      fprintf(stderr, "%s\n", dlerror());
      exit(EXIT_FAILURE);
   }

   dlerror();

   *(void **) (&doit) = dlsym(handle, "doit");

   if ((error = dlerror()) != NULL)  {
      fprintf(stderr, "%s\n", error);
      exit(EXIT_FAILURE);
   }

   (*doit)();
   dlclose(handle);
}

主.c:

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

int
main(int argc, char **argv)
{
   void *handle;
   void (*go)(const char*);
   char *error;

   handle = dlopen("/tmp/two.so", RTLD_NOW);
   if (!handle) {
      fprintf(stderr, "%s\n", dlerror());
      return EXIT_FAILURE;
   }

   dlerror();

   const char* location = "/tmp/three.so";
   *(void **) (&go) = dlsym(handle, "go");

   if ((error = dlerror()) != NULL)  {
      fprintf(stderr, "%s\n", error);
      return EXIT_FAILURE;
   }

   (*go)(location);
   dlclose(handle);

   return EXIT_SUCCESS;
}

结果:

svengali ~ % gcc -o /tmp/two.so two.c -shared -rdynamic -fpic
svengali ~ % gcc -o /tmp/three.so three.c -shared -rdynamic -fpic
svengali ~ % gcc -rdynamic -o go main.c -ldl
svengali ~ % go
Success
svengali ~ % 
于 2013-05-27T21:50:07.300 回答