dlopen、dlsym的简单使用

一、dlopen、dlsym我所理解的是通过dlopen可以动态加载一个so,通过dlsym可以获得该so中某接口的地址,从而实现使用该so中接口的功能。

二、代码如下:

mylib.cpp

#include <stdio.h>
#include <stdlib.h>

/*
 *  c++编译后的文件会把函数名改名(为了实现重载功能)
 *  用extern "C"声明后,就会使用c的方式进行编译,编译后的文件中仍然是定义的函数名
 */
extern "C"
{
    void feng(void)
    {
        printf("111111\n");
    }
}

g++ -shared -fPIC -o mylib.so mylib.cpp 

dlopen_test.cpp

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

void(*pMytest)(void );

int main(void) {

    void *handle = NULL;
    char *myso = "./mylib.so";
    dlerror();
    if((handle = dlopen(myso, RTLD_NOW)) == NULL) {
        printf("dlopen - %sn", dlerror());
        exit(-1);
    }
     
    printf("success\n");
    
    pMytest = (void(*)(void))dlsym(handle, "feng");
    
    printf("error:%s\n", dlerror());
    printf("success end\n");
    pMytest();
    return 0;
}

 g++ -o dlopen_test dlopen_test.cpp -ldl -rdynamic

运行可得到:1111111

注意so中的函数要用到extern "C",否则运行./dlopen_test会报undefined symbol dlsym的错误,因为c++编译后的文件会把函数名改名(为了实现重载功能),用extern "C"声明后,就会使用c的方式进行编译,编译后的文件中仍然是定义的函数名,可以通过nm来看so中函数的名称。

如果不加extern "C“


加上后:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值