如何在运行时检索dylib的路径?

时间:2022-04-20 06:04:34

On OS X, how can code in a dylib find the path it was loaded from, at runtime?

在OS X上,dylib中的代码如何在运行时找到它所加载的路径?

Coming from a Windows background, I'm used being able to call GetModuleFileName(dllHandle,...).

来自Windows背景,我用来调用GetModuleFileName(dllHandle,...)。

There exists NSGetExecutablePath() which will give me the path of the executable for the current process. Is there an equivalent to give me the current dylib path?

存在NSGetExecutablePath(),它将为我提供当前进程的可执行文件的路径。有没有相当于给我当前的dylib路径?

1 个解决方案

#1


11  

Use dladdr(3). Given a memory address, dladdr() outputs a structure that has, amongst other data, the path of the library containing the address. For example, inside your library:

使用dladdr(3)。给定一个内存地址,dladdr()输出一个结构,除其他数据外,该结构包含包含地址的库的路径。例如,在您的库中:

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

void test(void) {
    Dl_info info;
    if (dladdr(test, &info)) {
        printf("Loaded from path = %s\n", info.dli_fname);
    }
}

#1


11  

Use dladdr(3). Given a memory address, dladdr() outputs a structure that has, amongst other data, the path of the library containing the address. For example, inside your library:

使用dladdr(3)。给定一个内存地址,dladdr()输出一个结构,除其他数据外,该结构包含包含地址的库的路径。例如,在您的库中:

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

void test(void) {
    Dl_info info;
    if (dladdr(test, &info)) {
        printf("Loaded from path = %s\n", info.dli_fname);
    }
}