Wednesday, March 17, 2010

GetModuleFileName() on OS X.

So, you want to know the path to your module.  On Windows, it's easy: you call GetModuleFileName() and pass NULL for the HMODULE.

But what if you're trying to do it on OS X?

#include <dlfcn.h>
std::string GetModuleFileNameOSX() {
  Dl_info module_info;
  if (dladdr(reinterpret_cast<void*>(GetModuleFileNameOSX), &module_info) == 0) {
    // Failed to find the symbol we asked for.
    return std::string();
  }
  return std::string(module_info.dli_fname);
}

For the first param to dladdr, you can pass any symbol you know will be in your module. In theory, something similar should work on linux, but I haven't tried.

No comments: