Can I access to symbols of the host process from a

2019-05-10 21:37发布

问题:

In my scenario I want a plugin, which is a shared object loaded in runtime, to access symbols from the “host application” so I can add any functionality to my application.

I have tried but have not found any way to do this and I have no clue on whether this is possible or not. So, can I do this somehow or is there any alternative that applications that use plugins use?

I am on Fedora 15, Linux 2.6.4. However, I hope the solution will be cross-platform.

回答1:

There are three main approaches:

  1. Pass a structure of function pointers to the DLL from the application, giving access to whatever symbols you want to share. This is the most portable method, but is kind of a pain to create all the function pointers. Something like:

    // In shared header
    struct app_vtable {
      void (*appFoo)();
    };
    
    // In plugin:
    const app_vtable *vt;
    void set_vtable(const app_vtable *vt_) {
      vt = vt_;
    }
    
    void bar() {
      vt->appFoo();
    }
    
    // In application:
    void foo();
    const app_vtable vt = { foo };
    
    void loadplugin() {
      void *plugin = dlopen("plugin.so", RTLD_LAZY);
      void (*pset_vtable)(const app_vtable *) = dlsym(plugin, "set_vtable");
    
      pset_vtable(&vt);
    
      void (*pbar)() = dlsym(plugin, "bar");
      pbar();
    }
    
  2. Move your application into a library, and have the executable simply link in this library and call an entry point in it. Then your plugins can link the same library and access its symbols easily. This is also quite portable, but can result in some performance loss due to the need to use position-independent code in your main app library (although you may be able to get away with a fixed mapping in this case, depending on your architecture).

  3. On Linux only (and possible other ELF platforms) you can use -rdynamic to export symbols from the application executable directly. However this isn't very portable to other platforms - in particular, these is no equivalent to this on Windows.