This repository has been archived by the owner on Jan 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 46
/
memory.h
85 lines (71 loc) · 1.97 KB
/
memory.h
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
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <TlHelp32.h>
#include <string_view>
class Memory
{
private:
std::uintptr_t processId = 0;
void* processHandle = nullptr;
public:
// Constructor that finds the process id
// and opens a handle
Memory(std::string_view processName) noexcept
{
::PROCESSENTRY32 entry = { };
entry.dwSize = sizeof(::PROCESSENTRY32);
const HANDLE snapShot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
while (::Process32Next(snapShot, &entry))
{
if (!processName.compare(entry.szExeFile))
{
processId = entry.th32ProcessID;
processHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
break;
}
}
// Free handle
if (snapShot)
::CloseHandle(snapShot);
}
// Destructor that frees the opened handle
~Memory()
{
if (processHandle)
::CloseHandle(processHandle);
}
// Returns the base address of a module by name
std::uintptr_t GetModuleAddress(std::string_view moduleName) const noexcept
{
::MODULEENTRY32 entry = { };
entry.dwSize = sizeof(::MODULEENTRY32);
const HANDLE snapShot = ::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, processId);
std::uintptr_t result = 0;
while (::Module32Next(snapShot, &entry))
{
if (!moduleName.compare(entry.szModule))
{
result = reinterpret_cast<std::uintptr_t>(entry.modBaseAddr);
break;
}
}
if (snapShot)
::CloseHandle(snapShot);
return result;
}
// Read process memory
template <typename T>
const T Read(const std::uintptr_t address) const noexcept
{
T value = { };
::ReadProcessMemory(processHandle, reinterpret_cast<const void*>(address), &value, sizeof(T), NULL);
return value;
}
// Write process memory
template <typename T>
void Write(const std::uintptr_t address, const T& value) const noexcept
{
::WriteProcessMemory(processHandle, reinterpret_cast<void*>(address), &value, sizeof(T), NULL);
}
};