有没有办法让共享库在加载时“通知”?
换句话说,假设我在共享库上使用 dlopen ,是否有一个在共享库上自动调用(如果存在)的函数(例如main?)
答案 0 :(得分:22)
库应该导出初始化 和使用gcc的清理例程 __attribute __((构造函数))和__attribute __((析构函数))函数属性。请参阅gcc信息页面 有关这些的信息。构造函数 例程在dlopen之前执行 返回(或在main()开始之前 如果库在加载时加载 时间)。析构函数例程 在dlclose返回之前执行(或 在exit()或完成main()之后 如果库在加载时加载 时间)。这些C原型 功能是:
void __attribute__ ((constructor)) my_init(void);
void __attribute__ ((destructor)) my_fini(void);
取自http://tldp.org/HOWTO/Program-Library-HOWTO/index.html
也就是说,您只需将__attribute __((构造函数))添加到要在加载共享库时调用的函数。上面的docuemtn还指出旧的_ini和_fini函数被认为是过时的。
答案 1 :(得分: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))
解决方案不同,这将是可移植的。但请注意,如果您有多个这样的对象,则无法保证构造/销毁顺序。
答案 2 :(得分:0)
至少在Linux上,至少在其他一些Unix系统上,如果动态打开了一个名为_init
的全局函数,如果它存在,将由动态链接器调用。