C++ 获取生成 DLL 文件的相对路径并确保移动后有效
在 C++ 项目中生成 DLL 文件后,可以使用以下方法获取生成的 DLL 文件的相对路径:
- 获取当前可执行文件的路径:可以使用
GetModuleFileName函数获取当前可执行文件的路径。
#include <windows.h>
#include <iostream>
int main() {
char buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);
std::string fullPath(buffer);
std::cout << "Full path of executable: " << fullPath << std::endl;
// 获取可执行文件所在目录
std::string directory = fullPath.substr(0, fullPath.find_last_of("\/"));
std::cout << "Directory of executable: " << directory << std::endl;
// 生成DLL文件的相对路径
std::string dllPath = directory + "\example.dll";
std::cout << "Relative path of DLL: " << dllPath << std::endl;
return 0;
}
- 获取当前工作目录:可以使用
GetCurrentDirectory函数获取当前工作目录。
#include <windows.h>
#include <iostream>
int main() {
char buffer[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buffer);
std::string currentDirectory(buffer);
std::cout << "Current working directory: " << currentDirectory << std::endl;
// 生成DLL文件的相对路径
std::string dllPath = currentDirectory + "\example.dll";
std::cout << "Relative path of DLL: " << dllPath << std::endl;
return 0;
}
请注意,无论使用哪种方法获取生成的 DLL 文件的相对路径,都需要确保 DLL 文件与可执行文件在同一个目录下,否则移动 DLL 文件后可能会导致无法加载。
原文地址: http://www.cveoy.top/t/topic/qtW1 著作权归作者所有。请勿转载和采集!