dlopen函数使用示例

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值