c++winapireadprocessmemory

How to use winapi ReadProcessMemory with vector to read buffer from another process?


std::byte *ReadBytes(PVOID address, SIZE_T length)
{
    std::byte *buffer = new std::byte[length];
    std::cout << "length" << sizeof(buffer) << std::endl;

    ReadProcessMemory(this->processHandle, address, buffer, length, NULL);

    return buffer;
};

I'm trying to read memory regions of a process into std::byte array, but with code above, I can't get the length of buffer outside, so I want to change the type of buffer to std::vector<std::byte> or use some other methods. How can I do this?


Solution

  • Since C++11, std::vector::data will provide a pointer to the backing array. If you're using older tools without support for C++ 11, &buffer[0] probably works, I've never seen it not work, but is not guaranteed by the Standard.

    Looking at the code again, if you've got std::byte, C++11 support is not an issue.

    So...

    std::vector<std::byte> ReadBytes(PVOID address, SIZE_T length)
    {
        std::vector<std::byte> buffer(length);
        std::cout << "length" << buffer.size() << std::endl;
    
        ReadProcessMemory(this->processHandle, address, buffer.data(), length, NULL);
    
        return buffer;
    };