dlopen函数使用示例

4 篇文章 0 订阅
3 篇文章 0 订阅

cat dlopen.c

#include <stdio.h>
#include <dlfcn.h>

int main(int argc, char *argv)
{
        int index = -1;
        void *handle;
        int (*get_index)(int);
        int ret = -1;

		// 获取handle
        handle = dlopen("./liba.so", RTLD_NOW);
        if (handle == NULL) {
                printf("dlopen error!:%s\n", dlerror());
                return -1;
        }

		//获取函数,get_card_index为so中的实现函数,get_index指向该函数;
        get_index = dlsym(handle, "get_card_index");
        if (get_index == NULL) {
                printf("dlsym error!\n");
                dlclose(handle);
                return -1;
        }

        ret = get_index(index);
        printf("ret:%d\n", ret);

		// 关闭该handle
		dlclose(handle);
        return 0;
}

cat test.c

int get_card_index(int num)
{
        return 123;
}

cat test.h

int get_car_index(int num);

编译和执行过程

syli@lishengyu-pc:~/work/tmp$ gcc -fPIC -shared -o liba.so test.c
syli@lishengyu-pc:~/work/tmp$ gcc dlopen.c -ldl
syli@lishengyu-pc:~/work/tmp$ ./a.out 
ret:123
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
dlopen函数是一个用于动态加载共享库的函数,它可以在运行时加载共享库并返回一个句柄,以便在程序中使用共享库中的函数dlopen函数的原型如下: ```c void *dlopen(const char *filename, int flag); ``` 要设置回调函数,你需要先加载共享库,然后使用dlsym函数获取共享库中的函数指针,最后将回调函数作为参数传递给获取到的函数指针。 下面是一个示例代码,演示了如何使用dlopen设置回调函数: ```c #include <stdio.h> #include <dlfcn.h> // 定义回调函数 typedef void (*CallbackFunc)(const char *); int main() { // 加载共享库 void *handle = dlopen("libexample.so", RTLD_LAZY); if (handle == NULL) { fprintf(stderr, "Failed to load shared library: %s\n", dlerror()); return 1; } // 获取共享库中的函数指针 CallbackFunc callback = (CallbackFunc)dlsym(handle, "callback"); if (callback == NULL) { fprintf(stderr, "Failed to get function pointer: %s\n", dlerror()); dlclose(handle); return 1; } // 调用回调函数 callback("Hello, world!"); // 关闭共享库 dlclose(handle); return 0; } ``` 在上面的示例代码中,我们首先使用dlopen函数加载了一个名为libexample.so的共享库。然后,使用dlsym函数获取了共享库中名为callback的函数指针,并将其转换为CallbackFunc类型。最后,我们调用了回调函数callback,并传递了一个字符串参数。 请注意,上述示例代码中的共享库文件名为libexample.so,你需要根据实际情况修改为你要加载的共享库文件名。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值