3
\$\begingroup\$

I have created this memory writer helper to ease the write into memory process and I want your suggestions regarding it. I am very new to C++ but have 6 years knowledge of .NET languages like VB and C#.

#include <wtypes.h>

class MemoryWriter {
private:
    USHORT _currentIndex;
    LPVOID _targetAddress;
    template<typename T>
    static void editMemory(DWORD address, T data)
    {
        DWORD oldProtection;
        VirtualProtect((LPVOID)address, sizeof(T), PAGE_EXECUTE_READWRITE, &oldProtection);
        *((T*)address) = data;
        VirtualProtect((LPVOID)address, sizeof(T), PAGE_EXECUTE_READWRITE, NULL);
    }
public:
    MemoryWriter(DWORD address) {
        _currentIndex = 0;
        _targetAddress = (LPVOID)address;
    }
    template<typename T>
    void write(T data)
    {
        editMemory<T>(((DWORD)_targetAddress + _currentIndex), data);
        _currentIndex += sizeof(T);
    }
    template<typename T>
    void write(LPVOID address, T data)
    {
        editMemory<T>((DWORD)address, data);
        _currentIndex = (DWORD)address;
    }
    void reset(LPVOID newAddress = NULL)
    {
        _currentIndex = 0;

        if (newAddress)
            _targetAddress = newAddress;
    }
};
\$\endgroup\$
2
\$\begingroup\$

A general physical layout guideline: Put all public members, functions as well as variables, first, followed by protected members, and private members at the end. You want users to see public members first, followed by protected members. Hopefully, they don't have to see private members at all.

I added white spaces around functions to make them more readable.

class MemoryWriter {

   public:

      MemoryWriter(DWORD address) {
         _currentIndex = 0;
         _targetAddress = (LPVOID)address;
      }

      template<typename T>
         void write(T data)
         {
            editMemory<T>(((DWORD)_targetAddress + _currentIndex), data);
            _currentIndex += sizeof(T);
         }

      template<typename T>
         void write(LPVOID address, T data)
         {
            editMemory<T>((DWORD)address, data);
            _currentIndex = (DWORD)address;
         }

      void reset(LPVOID newAddress = NULL)
      {
         _currentIndex = 0;

         if (newAddress)
            _targetAddress = newAddress;
      }

   protected:

   private:

      USHORT _currentIndex;
      LPVOID _targetAddress;

      template<typename T>
         static void editMemory(DWORD address, T data)
         {
            DWORD oldProtection;
            VirtualProtect((LPVOID)address, sizeof(T), PAGE_EXECUTE_READWRITE, &oldProtection);
            *((T*)address) = data;
            VirtualProtect((LPVOID)address, sizeof(T), PAGE_EXECUTE_READWRITE, NULL);
         }
};
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.