Created
April 8, 2020 19:45
-
-
Save smx-smx/a1c397f61e30d4ffc79373bffbc49210 to your computer and use it in GitHub Desktop.
Wrapper to work with global variables and arbitrary pointers (e.g from another process)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <stdint.h> | |
#include <type_traits> | |
// use this for the [] operator (since we can't overload .) to work on globals without using the -> pointer operator | |
// example: BYVAL(gMyVar).foo | |
#define BYVAL(ptr) (*(&(ptr))) | |
template <typename T> | |
class Pointer | |
{ | |
private: | |
T *ptr; | |
public: | |
using Tderef = typename std::remove_pointer<T>::type; | |
Pointer(uintptr_t address) : ptr((T *)address){} | |
// seamlessy dereference the pointer if we're assigning | |
operator T() { | |
return *ptr; | |
} | |
template <typename Tderef, typename = typename std::enable_if<!std::is_function<Tderef>::value>::type> | |
// dereference Pointer<char *> | |
Tderef operator*() { | |
return (Tderef)(*ptr); | |
} | |
Pointer<Tderef> operator[](int i) { | |
T base = *ptr; | |
uintptr_t next = ((uintptr_t)base) + (i * sizeof(Tderef)); | |
return Pointer<Tderef>(next); | |
} | |
T operator->() { | |
return *ptr; | |
} | |
T* operator&() { | |
return ptr; | |
} | |
T operator=(T value) { | |
*ptr = value; | |
return *ptr; | |
} | |
T operator+=(T value) { | |
*ptr += value; | |
return *ptr; | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment