dlopen, dlsym,dlclose

本文介绍了一个C++程序如何通过动态链接库(.so文件)加载并调用其中的函数。具体展示了如何使用g++编译器创建动态库,如何在主程序中通过dlopen、dlsym等函数进行动态库的加载和函数地址的获取,并最终调用该函数。此过程涵盖了动态库的创建、加载、函数调用及错误处理。

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

#include <iostream>
#include <stdio.h>

void addVector(int *src, int *dst, int *dstCnt, int srcCnt)
{
    int *pDstTmp = dst + *dstCnt;

    for(int i = 0; i < srcCnt; i++)
    {   
        *pDstTmp++ = *(src+i);
        (*dstCnt)++;
    }   

    return ;
}

 g++ -fPIC --shared -o libvector.so vector.cpp

 objdump -S libvector.so -D

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

int main()
{
    void *handle;
    void (*addVector)(int *src, int *dst, int *dstCnt, int srcCnt) ;
    char *error;
    int a[10]={1,2};
    int b[3]={1,2,3};
    int dstCnt = 2;
    int srcCnt = 3;

    handle = dlopen("./libvector.so", RTLD_LAZY);
    if(!handle)
    {   
        printf("libvetor.so load failed\n");

        return -1;
    }   
    printf("libvetor.so load success\n");
    addVector = (void(*)(int *, int*,int *, int)) dlsym(handle, "_Z9addVectorPiS_S_i");
    if((error = dlerror()) != NULL)
      fprintf(stderr, "%s\n", error);
    addVector(b,a, &dstCnt, srcCnt);

    for(int i = 0; i < dstCnt; i++)
    {   
        printf("%d,", a[i]);
    }   
    printf("\n");

    return 0;
}

g++  -rdynamic   -o a.out ./main.cpp  -ldl

 选项 -rdynamic 用来通知链接器将所有符号添加到动态符号表中
(目的是能够通过使用 dlopen 来实现向后跟踪)
-rdynamic
Pass the flag ‘-export-dynamic’ to the ELF linker, on targets that support
it. This instructs the linker to add all symbols, not only used ones, to the
dynamic symbol table. This option is needed for some uses of dlopen or to
allow obtaining backtraces from within a program.

root@opzoon-All-Series:/data_1/songqing/for_test/ldOperate/demo# ./a.out
libvetor.so load success
1,2,1,2,3,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值