使用 ReadProcessMemory() 将未知大小的字符数组或字符串读入 wstring 中

Reading a character array or string of unknown size into a wstring using ReadProcessMemory()

本文关键字:字符串 数组 wstring 字符 ReadProcessMemory 未知 使用      更新时间:2023-10-16

编辑:解决了我的问题。我一直在用错地址...

如何使用函数 ReadProcessMemory 从进程中读取未知大小的字符串或字符数组C++?

我尝试过:

std::string temp;
ReadProcessMemory(*hProcess, (LPCVOID)(address+offset), &temp, sizeof(temp), &bytesRead);               
mywString = string2wstring(temp);

函数 string2wstring((: 功能来源

std::wstring string2wstring(const std::string& str)
{
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}

我能够成功读取字符串,但是当我运行以下命令时,我不断收到读取访问冲突:

#include <iostream>
#include <windows.h>
#include <string>

void main()
{
HANDLE hProcess;
DWORD pID = 000;
SIZE_T bytesRead;
uintptr_t address = 0x000;
//HWND gameWindow = FindWindow(NULL, L"TEXTCHECK");
//GetWindowThreadProcessId(gameWindow, &pID);
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pID);

std::string temp;
if (ReadProcessMemory(hProcess, (LPCVOID)(address), &temp, sizeof(temp), &bytesRead))
{
}
std::cout << temp;
system("pause");
}

测试对象:

#include <iostream>
#include <string>
#include <Windows.h>
#include <stdlib.h>
using namespace std;
int main() {
int varInt = 123456;
string varString = "DefaultString";
const char arrChar[128] = "Long char array AABBCCDDEEFFGGHHIIJJKKLL"; 
int* ptr2int = &varInt;
int** ptr2ptr = &ptr2int;
int*** ptr2ptr2 = &ptr2ptr;

while (1) {
cout << "Process ID: " << GetCurrentProcessId() << "n";
cout << "n";
cout << "varInt     (0x" << &varInt << ") = " << varInt << "n";
cout << "varString  (0x" << &varString << ") = " << varString << "n";
cout << "arrChar    (0x" << &arrChar << ") = " << arrChar << "n";
cout <<"n";
cout << "ptr2int    (0x" << &ptr2int << ") = 0x" << ptr2int << "n";
cout << "ptr2ptr    (0x" << &ptr2ptr << ") = 0x" << ptr2ptr << "n";
cout << "ptr2ptr2   (0x" << &ptr2ptr2 << ") = 0x" << ptr2ptr2 << "n";
cout << "n";
cout << "Press ENTER to print again.";
cout << "n";
cout << flush;
cin.get();
cout << "----------------------------------------nnn";
//system("CLS");
}
return 0;
}

托管 win32 异常发生在 GETSTRINGFROMMEM.EXE [16984]

您必须知道要阅读的确切大小。如果您不知道尺寸,您唯一的希望是:

  • 字符串数据以您可以读取的大小为前缀

  • 字符串数据以 null 结尾,在这种情况下,您必须一次读取 1 个字符,直到找到 NULL 终止符。