14

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

Coming from a Windows background, I'm used being able to call 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?

snowcrash09
  • 4,694
  • 27
  • 45

1 Answers1

17

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:

#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);
    }
}