Linux equivalent of DllMain

杀马特。学长 韩版系。学妹 提交于 2019-11-30 13:40:06

问题


In *nix .so libraries, is there an entry point that's invoked by the system when the library is loaded and unloaded?

On a more practical note: if the .so was written in C++ and it contains global objects with constructors and destructors, and it's loaded from a language that has no notion of construction/destruction, are the global objects properly constructed/destructed?


回答1:


  1. No, there is no equivalent to DllMain.

  2. For JNI libraries, e.g. on Android, there may be a special entry JNI_OnLoad which is intended to fill JNI function table.

  3. GCC defines special attribute constructor to allow some code to run on shared library load.

  4. C++ guarantees that the constructors for global and static objects will be performed, no matter if the code that loaded the .so was aware of these classes, or had notion of construction.

    Same holds for destructors, but there may be unhappy circumstances when at least some destructors have no chance to run - e.g. when there is a sigfault and exceptions are disabled.




回答2:


You can use the __attribute__((constructor)) and __attribute__((destructor)) to execute code on load and unload of the shared library.




回答3:


The technique used is a little different, but the construction/destruction of global objects is more or less built into the dynamic loader. (Even under Windows, there's no need to go through DllMain. The global objects will be constructed/destructed correctly anyway.)



来源:https://stackoverflow.com/questions/12463718/linux-equivalent-of-dllmain

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