1.getmodulepath.h
#ifndef GETMODULEPATH
#define GETMODULEPATH
#include <wtypes.h>
#include <string>
/**
* @class getmodulepath
* @brief 这个类用来获取当前模块的绝对路径
*/
class GetModulePath
{
public:
static HMODULE GetModuleHandleFromAddress(void* address);
static bool IsModuleHandleValid(HMODULE module_handle);
static HMODULE GetCurrentModuleHandle();
static std::wstring GetModulePathName(HMODULE module_handle);
static bool IsFilePathSeparator(const wchar_t separator);
static bool FilePathApartDirectory(const std::wstring &filepath_in, std::wstring &directory_out);
static std::wstring GetModuleDirectory(HMODULE module_handle);
static std::wstring GetCurrentModuleDirectory();
};
#endif // GETMODULEPATH
2.getmodulepath.cpp
#include "getmodulepath.h"
const wchar_t kEndChar = L'\0';
const wchar_t kFilePathSeparators[] = L"\\/";
HMODULE GetModulePath::GetModuleHandleFromAddress(void *address)
{
MEMORY_BASIC_INFORMATION mbi;
DWORD result = ::VirtualQuery(address, &mbi, sizeof(mbi));
if (result != sizeof(mbi))
{
return static_cast<HMODULE>(0);
}
return static_cast<HMODULE>(mbi.AllocationBase);
}
bool GetModulePath::IsModuleHandleValid(HMODULE module_handle)
{
if (!module_handle)
{
return false;
}
return module_handle == GetModuleHandleFromAddress(module_handle);
}
HMODULE GetModulePath::GetCurrentModuleHandle()
{
return GetModuleHandleFromAddress((void*)GetCurrentModuleHandle);
}
std::wstring GetModulePath::GetModulePathName(HMODULE module_handle)
{
std::wstring mod_path;
if (IsModuleHandleValid(module_handle))
{
mod_path.resize(MAX_PATH);
mod_path.resize(::GetModuleFileNameW(module_handle, &mod_path[0], mod_path.size()));
}
return mod_path;
}
bool GetModulePath::IsFilePathSeparator(const wchar_t separator)
{
if (separator == kEndChar)
{
return false;
}
size_t len = sizeof(kFilePathSeparators) / sizeof(wchar_t);
for (size_t i = 0; i < len; i++)
{
if (separator == kFilePathSeparators[i])
{
return true;
}
}
return false;
}
bool GetModulePath::FilePathApartDirectory(const std::wstring &filepath_in, std::wstring &directory_out)
{
size_t index = filepath_in.size() - 1;
if (index <= 0 || filepath_in.size() == 0)
{
return false;
}
for (; index != 0; index--)
{
if (IsFilePathSeparator(filepath_in[index]))
{
if (index == filepath_in.size() - 1)
{
directory_out = filepath_in;
}
else
{
directory_out = filepath_in.substr(0, index + 1);
}
return true;
}
}
return false;
}
std::wstring GetModulePath::GetModuleDirectory(HMODULE module_handle)
{
std::wstring module_directory;
if (IsModuleHandleValid(module_handle))
{
if (FilePathApartDirectory(GetModulePathName(module_handle), module_directory))
{
return module_directory;
}
}
return L"";
}
std::wstring GetModulePath::GetCurrentModuleDirectory()
{
return GetModuleDirectory(GetCurrentModuleHandle());
}
3.使用示例
std::wstring dir = GetModulePath::GetCurrentModuleDirectory();