dlopen 和函数属性 __attribute__((constructor))& __attribute__((destructor))

本文介绍如何使用__attribute__((constructor))和__attribute__((destructor))在共享对象加载和卸载时执行特定函数。通过GCC编译器支持的属性,可以在dlopen前调用初始化函数,在dlclose前调用清理函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Shared objects may export functions using the

__attribute__((constructor)) and __attribute__((destructor))
function attributes.  Constructor functions are executed before
dlopen() returns, and destructor functions are executed before
dlclose() returns.  A shared object may export multiple
constructors and destructors, and priorities can be associated
with each function to determine the order in which they are
executed.  See the gcc info pages (under "Function attributes")
for further information.

函数设置__attribute__((constructor))属性,在dlopen时,会先调用该方法。

设置__attribute__((destructor))属性,在dlclose时会调用该方法。

demo

下面举例

// test.c
#include <stdio.h>

__attribute__((constructor)) void test_init() {
    printf("hello world\n");
}

__attribute__((destructor)) void test_fini() {
    printf("bye world\n");
}

void test() {
    printf("test\n");
}

gcc -fPIC -shared test.c -o  libtest.so
#include <stdio.h>
#include <dlfcn.h>

typedef void(*testFunc)();
int main() {
    void *handle = dlopen("./libtest.so", RTLD_LAZY);
    if (handle == NULL) {
        printf("handle is null, %s\n", dlerror());
    }
    printf("----------\n");
    testFunc f = (testFunc)dlsym(handle, "test");
    if (f == NULL) {
        printf("f is null\n");
    }

    f();
    dlclose(handle);
    return 0;
}
gcc main.c -ldl -O0 -g

执行可执行文件,在dlopen时执行test_init方法,最后在dlclose执行test_fini方法。

// a.out
hello world
----------
test
bye world
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值