问了一个问题Call CloseHandle on handle that is a function parameter?
在有人编辑了代码之后,我对其进行了更新,以发现代码不再按预期工作。
intptr_t readMem(HANDLE processHandle, intptr_t address, int sizeToReadBytes) { intptr_t memValue = 0; bool success = ReadProcessMemory(processHandle, (LPVOID)address, memValue, sizeToReadBytes, NULL); if (!success) std::wcout << "Memory read failed on address: " << std::hex << address << "\n"; return memValue; }
在第
行ReadProcessMemory(processHandle, (LPVOID)address, memValue, sizeToReadBytes, NULL);
memValue
不会在没有(LPVOID)
或(LPCVOID)
强制转换的情况下进行编译,但是对于它们,代码不再读取内存(或者使用{在函数的情况下写入) {1}}
最初(现在我已经在我的小程序中将其更改回来)它使用引用WriteProcessMemory
并且工作正常。
我的问题是:
这应该有用吗? 或者编辑是否正确,我的程序的其余部分可能是错误的?
如果需要,我可以提供更多代码,只是不确定哪些比特并且不想比我更多地阻塞屏幕...还应该回滚编辑吗?
答案 0 :(得分:0)
ReadProcessMemory()
的第三个参数是调用进程中的内存地址,函数将读取的数据写入。但是,您没有传递内存地址。在原始问题的第三个修订版中显示的代码中,您将未初始化的整数变量的值输入到内存指针中。所以函数会尝试写入随机存储器。现在你已经删除了类型转换,所以代码甚至不应该再编译了。
您的readMem()
功能设计不正确。您需要更改它以便:
调用者分配所需大小的内存,然后该函数只是填充内存:
bool readMem(HANDLE processHandle, intptr_t address, void *memValue, int sizeToReadBytes)
{
bool success = ReadProcessMemory(processHandle, (LPVOID)address, memValue, sizeToReadBytes, NULL);
if (!success)
std::wcout << "Memory read failed on address: " << std::hex << address << "\n";
return success;
}
intptr_t memValue = 0;
readMem(processHandle, address, &memValue, sizeof(memValue));
该函数分配内存并将其返回给调用者:
void* readMem(HANDLE processHandle, intptr_t address, int sizeToReadBytes)
{
uint8_t memValue = new uint8_t[sizeToReadBytes];
bool success = ReadProcessMemory(processHandle, (LPVOID)address, memValue, sizeToReadBytes, NULL);
if (!success) {
std::wcout << "Memory read failed on address: " << std::hex << address << "\n";
delete [] memValue;
memValue = NULL;
}
return memValue;
}
intptr_t *memValue = (intptr_t*) readMem(processHandle, address, sizeof(intptr_t));
...
delete [] memValue;
或者:
bool readMem(HANDLE processHandle, intptr_t address, int sizeToReadBytes, std:vector<uint8_t> &memValue)
{
memValue.resize(sizeToReadBytes);
bool success = ReadProcessMemory(processHandle, (LPVOID)address, &memValue[0], sizeToReadBytes, NULL);
if (!success)
std::wcout << "Memory read failed on address: " << std::hex << address << "\n";
return success;
}
std::vector<uint8_t> buffer;
readMem(processHandle, address, sizeof(intptr_t), buffer);
intptr_t memValue = (intptr_t*) &buffer[0];