在linux上实现DllMain + 共享库创建方法

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

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

 

posted @ 2013-07-07 09:10  D3猎人  阅读(1923)  评论(0编辑  收藏  举报