用c++写一个dll 用于获取程序数据目录
以下是一个获取程序数据目录的示例C++ DLL代码:
#include <Windows.h>
extern "C" __declspec(dllexport) void GetAppDataPath(char* path)
{
// 获取当前进程句柄
HMODULE hModule = GetModuleHandle(NULL);
// 获取程序数据目录路径
SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, path);
// 添加程序名称到路径末尾
strcat_s(path, MAX_PATH, "\\MyApp");
// 创建目录
CreateDirectoryA(path, NULL);
}
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
该DLL中的GetAppDataPath函数将获取当前进程的程序数据目录路径,将其存储在传递的path参数中,并在路径中添加程序名称。最后,它将创建该目录(如果它不存在)。
要使用该DLL,请将其编译为DLL文件,并在主程序中调用LoadLibrary函数加载该DLL。然后,使用GetProcAddress函数检索GetAppDataPath函数的地址,并将其作为函数指针调用。例如:
#include <Windows.h>
#include <iostream>
typedef void (*GetAppDataPathFunc)(char*);
int main()
{
// 加载DLL
HMODULE hDll = LoadLibraryA("MyDll.dll");
if (hDll == NULL)
{
std::cout << "Failed to load DLL." << std::endl;
return 1;
}
// 获取函数指针
GetAppDataPathFunc getAppDataPath = (GetAppDataPathFunc)GetProcAddress(hDll, "GetAppDataPath");
if (getAppDataPath == NULL)
{
std::cout << "Failed to get function address." << std::endl;
FreeLibrary(hDll);
return 1;
}
// 调用函数
char path[MAX_PATH];
getAppDataPath(path);
std::cout << "App data path: " << path << std::endl;
// 卸载DLL
FreeLibrary(hDll);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/b3j3 著作权归作者所有。请勿转载和采集!