首页 > 解决方案 > Get int from byte array by offset

问题描述

I am new to C++. Can't get int from byte array by offset.

When i read directly from memory all works fine and i am gettings 100 - this is correct value

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

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

But if i try to get a chunk of bytes and read from them, here problem comes

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

With C# it would easy like this

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

标签: c++arraysmemorybytechunks

解决方案


将这种类型的 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);

推荐阅读