gpt4 book ai didi

c++ - 如何获取给定给dlopen的相对路径对应的绝对库文件名?

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

在我的程序中有如下代码

/* libname may be a relative path */
void loadLib(char const *libname) {
void *handle = dlopen(libname);
/* ... */
dlclose(handle);
}

/* .. */中,我需要读取内存映射文件/proc/self/maps,找到所在的虚拟内存地址>libname 被映射到,我还需要打开库以找到其中的某些部分。为此,我需要 dlopen 通过在各个地方(例如,在 ldconfig 缓存文件中)搜索找到的绝对名称。我怎样才能收到该文件名?


这就是我最终得到的结果(是的,这是 C++ 代码,尽管如此,C 标记对于这个问题还是有意义的,因为 dlopen 与 C++ 和 C 以及我的问题一起使用符合两者的条件,POSIX 指定它用于 C。)。

   boost::shared_ptr<void> dl;
if(void *handle = dlopen(libfile, RTLD_LAZY)) {
dl.reset(handle, &dlclose);
} else {
printdlerr();
return -1;
}

/* update sofile to be an absolute file name */
{
struct link_map *map;
dlinfo(dl.get(), RTLD_DI_LINKMAP, &map);
if(!map) {
return -1;
}
char *real = realpath(map->l_name, NULL);
if(!real)
return -1;
sofile.reset(real, &free);
}

libfile 是相对/纯文件名。该 map 将产生一个非普通文件名(即不是 foo.so 但可能是 ./foo.so)。之后我使用 realpath 来获取最终的绝对路径名。效果很好!

最佳答案

你可以用

... dlinfo(handle, RTLD_DI_LINKMAP, p)
p->l_name ...

其中 p 是 Link_map 类型**

有关详细信息,请参阅 man dlinfo

关于c++ - 如何获取给定给dlopen的相对路径对应的绝对库文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6676525/

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