在linux上實現DllMain + 共享庫創建方法


在linux上實現DllMain + 共享庫創建方法

https://www.cnblogs.com/D3Hunter/archive/2013/07/07/3175770.html

http://tdistler.com/2007/10/05/implementing-dllmain-in-a-linux-shared-librar

 

DllMain可以在dll加載到進程、線程時調用,可以做些初始化、清理的工作

但在linux上沒有專門的函數,可以使用gcc擴張屬性__attribute__((constructor)) and __attribute__((destructor))來實現

類似於全局類變量,其構造函數及析構函數會在加載時自動調用。

上述方法不能實現線程attach、detach,但對一般程序足夠了

void __attribute__ ((constructor)) my_load(void);
void __attribute__ ((destructor)) my_unload(void);
 
// Called when the library is loaded and before dlopen() returns
void my_load(void)
{
    // Add initialization code…
}
 
// Called when the library is unloaded and before dlclose()
// returns
void my_unload(void)
{
    // Add clean-up code…
}

需要注意的是,該共享庫不能使用-nostartfiles 和 -nostdlib 進行編譯,否則構造、析構函數不會調用

共享庫創建方法:

代碼要編譯成PIC代碼,使用-fPIC,鏈接時指定為動態庫 -shared

 

============ End

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM