yyqng

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

调用栈:main() --> libsosrc.so中的soFunc--> main.out中的callBySo

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

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

typedef int(*Func)();

int main()
{
    const char* const so_path = "libsosrc.so";
    void* handle = dlopen(so_path, RTLD_LAZY);
    Func func = (Func)dlsym(handle, "soFunc");
    func();
    dlclose(handle);
    return 0;
}

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

链接选项-rdynamic将所有非静态函数加到动态符号表中

readelf -Ds main.out

Symbol table of `.gnu.hash' for image:
Num Buc: Value Size Type Bind Vis Ndx Name
7 0: 0000000000601048 0 NOTYPE GLOBAL DEFAULT 24 __data_start
8 0: 000000000040084d 16 FUNC GLOBAL DEFAULT 13 _Z8callBySov
......

g++ sosrc.cpp -fPIC -shared -g -o libsosrc.so

#include<stdio.h>

#ifdef __cplusplus
extern "C" {
#endif

void soFunc();

#ifdef __cplusplus
}
#endif

extern void callBySo();

void soFunc()
{
    printf("soFunc\n");
    callBySo();
}

 

posted on 2023-05-09 07:06  zziii  阅读(37)  评论(0编辑  收藏  举报