Search code examples
c++wstring

How would I read Memory into a wstring?


I already tried using wchar_t and a for-loop to read the Memory wchar by wchar and it worked. Working code:

int cl = 20;
std::wstring wstr;
wchar_t L;
for (int i = 0; i < cl; i++) {
ReadProcessMemory(ProcHandle, (unsigned char*)Address, &L, 2, NULL);
Address += 2;
wstr.push_back(L);
}
std::wcout << wstr << std::endl;

Now when I try using std::wstring and read directly into it, it fails for whatever reason.

int cl = 20;
std::wstring L;
L.resize(cl); // could use reserve?
ReadProcessMemory(ProcHandle, (unsigned char*)Address, &L, cl*2, NULL);
std::wcout << L << std::endl;

I figured I'd use (cl * 2) as size because wchar_t has 2 chars size.

I would expect it to print the wstring to wcout but instead it errors with something similar to Failed to read sequence

Note: I cannot use wchat_t[20] because I later want cl to be dynamic.

Edit: Forgot to say that I'm on std c++17


Solution

  • std::vector<wchar_t> is more suitable for your case.

    &L is the address of the string object, not the string buffer. You wanna use &L[0], the address of the first wchar.