srounet / Pymem

A python library for windows, providing the needed functions to start working on your own with memory editing.
MIT License
307 stars 44 forks source link

Vectors support #71

Closed OpsecGuy closed 2 years ago

OpsecGuy commented 2 years ago

Hi, just wanted to suggest to add support for writing and reading a Vectors (2/3) and that's a 1 thing I sadly missing.

qb-0 commented 2 years ago

Not tested but should work

import struct
from pymem.memory import read_bytes, write_bytes

def read_vec3(handle, address):
    bytes = read_bytes(handle, address, struct.calcsize("3f"))
    bytes = struct.unpack("3f", bytes)
    return {"x": bytes[0], "y": bytes[1], "z": bytes[2]}

def read_vec2(handle, address):
    bytes = read_bytes(handle, address, struct.calcsize("2f"))
    bytes = struct.unpack("2f", bytes)
    return {"x": bytes[0], "y": bytes[1]}

def write_vec3(handle, address, value):
    value = struct.pack("3f", *value.values())
    length = struct.calcsize("3f")
    res = write_bytes(handle, address, value, length)
    return res

def write_vec2(handle, address, value):
    value = struct.pack("2f", *value.values())
    length = struct.calcsize("2f")
    res = write_bytes(handle, address, value, length)
    return res
OpsecGuy commented 2 years ago

Hey @qb-0 thank you for your contribution. I also have a question if you ever tried to write whole structure with Pymem. How could I achieve that?

qb-0 commented 2 years ago

Guess something like that could work

import ctypes
import struct
from pymem.memory import write_bytes

class MyStructure(ctypes.Structure):
    _fields_ = [
        ("field1_float", ctypes.c_float),
        ("field2_int", ctypes.c_int32),
    ]

newStruct = MyStructure(1.0, 2)
value = bytearray(newStruct)
length = ctypes.sizeof(newStruct)
res = write_bytes(handle, address, value, length)