gpt4 book ai didi

linux - 动态加载时的库路径?

转载 作者:IT王子 更新时间:2023-10-29 00:27:05 24 4
gpt4 key购买 nike

如何从库本身获取共享库的路径?

换句话说,假设库 X 是使用 dlopen() 加载的,我如何才能从库本身中访问用于加载所述库的路径?

请注意,我不能让首先加载库的代理将此参数交给我。

更新:这是处理静态变量的方法:

std::string wdir;

namespace {
class dynamic_library_load_unload_handler {
public:
dynamic_library_load_unload_handler(){
Dl_info dl_info;
dladdr((void *) NP_Initialize, &dl_info);

std::string path(dl_info.dli_fname);
wdir = path.substr( 0, path.find_last_of( '/' ) +1 );
}
~dynamic_library_load_unload_handler(){
// Code to execute when the library is unloaded
}
} dynamic_library_load_unload_handler_hook;
}

最佳答案

动态链接器实际上会搜索几个地方来找到每个动态库。这些包括(来自 man ld.so):

  • 环境变量 LD_LIBRARY_PATH 给出的路径
  • 烘焙到二进制文件中的路径将库加载到 DT_RUNPATH 条目下
  • 缓存文件/etc/ld.so.cache
  • /lib 和/usr/lib

如果您想获取特定共享库的路径,我会推荐dladdr 函数。从手册页:

The function dladdr() takes a function pointer and tries to resolve name and file where it is located. Information is stored in the Dl_info structure:

typedef struct {
const char *dli_fname; /* Pathname of shared object that
contains address */
void *dli_fbase; /* Address at which shared object
is loaded */
const char *dli_sname; /* Name of nearest symbol with address
lower than addr */
void *dli_saddr; /* Exact address of symbol named
in dli_sname */
} Dl_info;

If no symbol matching addr could be found, then dli_sname and dli_saddr are set to NULL.

dladdr() returns 0 on error, and non-zero on success.

所以你只要给它一个函数指针,它就会给你提供它的文件的名称和一堆其他信息。因此,例如,您可以让库中的构造函数自行调用它以找出库的完整路径:

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

__attribute__((constructor))
void on_load(void) {
Dl_info dl_info;
dladdr((void *)on_load, &dl_info);
fprintf(stderr, "module %s loaded\n", dl_info.dli_fname);
}

此函数也适用于具有相同语义的 OS X。

关于linux - 动态加载时的库路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1681060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com