如何在C++ DLL文件外放置配置文件以实现参数灵活修改
问题解答
DLL与配置文件同目录默认无法直接访问的原因
你当前代码使用相对路径"config.txt"加载文件,C++中相对路径的基准是调用DLL的宿主进程的工作目录,而非DLL文件自身所在的目录。如果宿主进程的启动目录和DLL存放目录不一致,就算把配置文件和DLL放在同目录也会读取失败。可行解决方案
修改加载逻辑,先获取当前DLL自身所在的绝对路径,再拼接配置文件名,就能稳定读取同目录下的外部配置文件。Windows平台下修改后代码如下:
#include <windows.h> #include <fstream> #include <sstream> #include <string> using namespace std; struct Config { string baseurl; }; // 获取当前DLL所在目录 string getDllDirectory() { char dllPath[MAX_PATH] = {0}; // 替换下方参数为你自己的DLL文件名,也可直接使用DLLMain入口收到的hModule参数 HMODULE hModule = GetModuleHandleA("你的DLL文件名.dll"); if (hModule != NULL) { GetModuleFileNameA(hModule, dllPath, MAX_PATH); string pathStr(dllPath); size_t pos = pathStr.find_last_of("\\/"); if (pos != string::npos) { return pathStr.substr(0, pos + 1); } } return ""; } void loadConfig(Config& config) { string configPath = getDllDirectory() + "config.txt"; ifstream fin(configPath); // 可选逻辑:外部配置不存在时 fallback 读取内置配置,兼容原有逻辑 if (!fin.is_open()) { // 此处填入原有读取内置配置的代码即可 return; } string line; while (getline(fin, line)) { size_t equalPos = line.find("="); if (equalPos == string::npos) continue; if (line.find("baseurl") != string::npos) { istringstream sin(line.substr(equalPos + 1)); sin >> config.baseurl; } } } // 调用方式保持不变 Config config; loadConfig(config);
- 优化建议
- 可新增配置文件格式校验、异常处理逻辑,避免配置写错导致程序运行异常
- 跨平台场景下,Linux/macOS 可使用
dladdr接口获取动态库(so文件)路径,逻辑与上述Windows版本一致
内容的提问来源于stack exchange,提问作者Lance
相关产品推荐
相关产品推荐

