通过偏移量从字节数组获取int

时间:2018-07-21 15:28:06

标签: c++ arrays memory byte chunks

我是C ++的新手。无法通过偏移量从字节数组获取整数。

当我直接从内存中读取所有内容时,一切正常,我得到100-这是正确的值

int base = 0x100;
int offset = 0x256;

int easy = memory->ReadMemory<int>(base + offset); // easy = 100

但是,如果我尝试获取一大块字节并从中读取,就会出现问题

template<class T>
T FromBuffer(uint8_t* buffer, size_t offset)
{
    T t_buf = 0;
    memcpy(&t_buf, buffer + offset, sizeof(T));
    return t_buf;
}

uint8_t* ReadBytes(DWORD Address, int Size)
{
    auto arr = new uint8_t[Size];
    ReadProcessMemory(TargetProcess, (LPVOID)Address, arr, sizeof(arr), 0);
    return arr;
}

auto bytes = memory->ReadBytes(base, 2500);
int hard = *((unsigned int *)&bytes[offset]); // hard = -842150451
uint32_t hard2 = memory->FromBuffer<uint32_t>(bytes, offset); // hard2 = 3452816845

使用C#,就很容易

int hard = BitConverter.ToInt32(bytes, offset);

1 个答案:

答案 0 :(得分:1)

将这种类型的C#代码转换为C ++没有任何意义,您被迫在C#中做一些古怪的事情,因为进行这种类型的操作不是C#的本意。

您不需要创建动态缓冲区,也不需要执行任何向导。只要做:

template <class T>
T RPM(void* addr)
{
    T t;
    ReadProcessMemory(handle, addr, &t, sizeof(t), nullptr);
    return t;
}

int RPM(addr + offset);