Can I access to symbols of the host process from a shared object loaded in runtime? Any alternative?

流过昼夜 提交于 2019-12-06 01:39:34

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!