-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModPath.hpp
More file actions
97 lines (90 loc) · 3.1 KB
/
ModPath.hpp
File metadata and controls
97 lines (90 loc) · 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#pragma once
#include "framework.h"
#include "stdio.h"
#include <filesystem>
#include <string>
#ifndef MODPATH_HPP
#define MODPATH_HPP
namespace ModPath
{
template<class T>
inline T GetModulePath(HMODULE hModule)
{
static constexpr auto INITIAL_BUFFER_SIZE = MAX_PATH;
static constexpr auto MAX_ITERATIONS = 7;
if constexpr (std::is_same_v<T, std::filesystem::path>)
{
std::u16string ret;
std::filesystem::path pathret;
auto bufferSize = INITIAL_BUFFER_SIZE;
for (size_t iterations = 0; iterations < MAX_ITERATIONS; ++iterations)
{
ret.resize(bufferSize);
size_t charsReturned = 0;
charsReturned = GetModuleFileNameW(hModule, (LPWSTR)&ret[0], bufferSize);
if (charsReturned < ret.length())
{
ret.resize(charsReturned);
pathret = ret;
return pathret;
}
else
{
bufferSize *= 2;
}
}
}
else
{
T ret;
auto bufferSize = INITIAL_BUFFER_SIZE;
for (size_t iterations = 0; iterations < MAX_ITERATIONS; ++iterations)
{
ret.resize(bufferSize);
size_t charsReturned = 0;
if constexpr (std::is_same_v<T, std::string>)
charsReturned = GetModuleFileNameA(hModule, &ret[0], bufferSize);
else
charsReturned = GetModuleFileNameW(hModule, &ret[0], bufferSize);
if (charsReturned < ret.length())
{
ret.resize(charsReturned);
return ret;
}
else
{
bufferSize *= 2;
}
}
}
return T();
}
template<class T>
inline T GetThisModulePath()
{
HMODULE hm = NULL;
GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)&DllMain, &hm);
T r = GetModulePath<T>(hm);
if constexpr (std::is_same_v<T, std::filesystem::path>)
return r;
else if constexpr (std::is_same_v<T, std::string>)
r = r.substr(0, r.find_last_of("/\\") + 1);
else
r = r.substr(0, r.find_last_of(L"/\\") + 1);
return r;
}
template<class T>
inline T GetThisModuleName()
{
HMODULE hm = NULL;
GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)&DllMain, &hm);
const T moduleFileName = GetModulePath<T>(hm);
if constexpr (std::is_same_v<T, std::filesystem::path>)
return moduleFileName.filename();
else if constexpr (std::is_same_v<T, std::string>)
return moduleFileName.substr(moduleFileName.find_last_of("/\\") + 1);
else
return moduleFileName.substr(moduleFileName.find_last_of(L"/\\") + 1);
}
}
#endif