DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

之前尝试在so库内调用getpwd()来获取当前路径,但是实际上获取到的是调用so库的可执行程序的所在路径,因此改用dladdr()做一些间接处理来获取。

#include <dlfcn.h>
#include <string.h>
#include <string>
char* GetModuleCurPath(char* sCurPath)
{
       std::string wdir;
       Dl_info dl_info;
       dladdr((void*)GetModuleCurPath, &dl_info);
       
       std::string path(dl_info.dli_fname);
       wdir = path.substr(0, path.find_last_of('/') + 1);
       strcpy(sCurPath, wdir.c_str());
       
       return  sCurPath;
}

在so库内使用此函数,可以获取到当前so库所在目录(注:如果库放在可执行程序同级目录或子目录下调用,则得到路径是相对于可执行程序,否则得到从根目录起的绝对路径)。

posted on 2023-01-31 14:38  DoubleLi  阅读(838)  评论(0编辑  收藏  举报