linux dlopen:加载时可以"通知"库吗?

jld*_*ont 13 linux shared-libraries dlopen

有没有办法让共享库在加载时"通知"?

换句话说,假设我在共享库上使用dlopen,是否有一个在共享库上自动调用(如果存在)的函数(例如main?)

nos*_*nos 22

库应使用gcc __attribute __((构造函数))和__attribute __((析构函数))函数属性导出初始化和清理例程.有关这些信息,请参阅gcc信息页面.构造函数例程在dlopen返回之前执行(如果在加载时加载库,则在main()启动之前执行).析构函数例程在dlclose返回之前执行(如果在加载时加载库,则在exit()或完成main()之后执行).这些函数的C原型是:

 void __attribute__ ((constructor))  my_init(void);  
 void __attribute__  ((destructor)) my_fini(void);
Run Code Online (Sandbox Code Playgroud)

摘自http://tldp.org/HOWTO/Program-Library-HOWTO/index.html

也就是说,您只需将__attribute __((构造函数))添加到要在加载共享库时调用的函数.上面的docuemtn还指出旧的_ini和_fini函数被认为是过时的.


Mic*_*yan 17

是.打开库时,会发生所有静态构造...因此,如果使用C++,则可以执行以下操作:

// mylibrary.cpp
namespace
{
    class dynamic_library_load_unload_handler
    {
         public:
              dynamic_library_load_unload_handler(){
                    // Code to execute when the library is loaded
              }
              ~dynamic_library_load_unload_handler(){
                    // Code to execute when the library is unloaded
              }
    } dynamic_library_load_unload_handler_hook;
}

__attribute__ ((constructor))给出的解决方案不同,这将是便携式的.但请注意,如果您有多个这样的对象,则无法保证构造/销毁顺序.