在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

 

posted @   lsgxeva  阅读(948)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示