To get memory from another process.

Dennis dkorpel at gmail.com
Thu Apr 9 18:56:31 UTC 2020


On Thursday, 9 April 2020 at 17:23:19 UTC, Quantium wrote:
> Ok. For training example, we're using Windows 10 Por. We can 
> use WinAPI. Are there any D libs to use WinAPI?

I have used the Windows API to read/write into a different 
process before. Here is some example code in case it's useful: (I 
removed some stuff without recompiling so it may have some errors)

```
version(Windows):
pragma(lib, "Kernel32.lib");
pragma(lib, "Psapi.lib");

struct WinProcess
{
     import core.sys.windows.winbase: OpenProcess, 
ReadProcessMemory, WriteProcessMemory, CloseHandle;
     import core.sys.windows.windows : PROCESS_VM_READ, 
PROCESS_VM_WRITE,
         PROCESS_QUERY_INFORMATION, PROCESS_VM_OPERATION, HANDLE;

     import std.bitmanip;
     import std.exception: enforce;

     int processId = -1; /// Id of the process this is attached to
     HANDLE processHandle = null; /// Windows handle of the process

     this(int processId) {
         this.processId = processId;

         const access = PROCESS_VM_READ | PROCESS_QUERY_INFORMATION
             | PROCESS_VM_WRITE | PROCESS_VM_OPERATION;
         this.processHandle = OpenProcess(access, false, 
processId);
         enforce(processHandle, "could not open process");
     }

     import std.traits: isNumeric;

     void write(T)(void* address, T value) if (isNumeric!T) {
         enforce(processHandle != null, "not attached to a process 
yet");
         size_t bytesWritten = 0;
         ubyte[T.sizeof] buffer;
         auto b = buffer[];
         b.write(value, 0);
         WriteProcessMemory(processHandle, address, cast(void*) 
buffer, buffer.sizeof, &bytesWritten);
         enforce(bytesWritten == T.sizeof, "could not write all 
bytes");
     }

     T read(T)(void* address) if (isNumeric!T) {
         enforce(processHandle != null, "not attached to a process 
yet");
         size_t bytesRead = 0;
         ubyte[T.sizeof] buffer;

         ReadProcessMemory(processHandle, address, cast(void*) 
buffer, buffer.sizeof, &bytesRead);

         enforce(bytesRead == T.sizeof, "could not read all 
bytes");

         auto b = buffer[]; // lvalue
         return b.read!T;
     }
}
```



More information about the Digitalmars-d-learn mailing list