在C++中,WriteProcessMemory函數(shù)用于向指定進程的內(nèi)存寫入數(shù)據(jù)。
函數(shù)的用法如下:
BOOL WriteProcessMemory(
HANDLE hProcess, // 目標進程的句柄
LPVOID lpBaseAddress, // 寫入數(shù)據(jù)的起始地址
LPCVOID lpBuffer, // 數(shù)據(jù)緩沖區(qū)的指針
SIZE_T nSize, // 要寫入的字節(jié)數(shù)
SIZE_T *lpNumberOfBytesWritten // 實際寫入的字節(jié)數(shù)
);
參數(shù)說明:
hProcess
:目標進程的句柄,可以通過OpenProcess函數(shù)獲得。lpBaseAddress
:寫入數(shù)據(jù)的起始地址。lpBuffer
:指向要寫入的數(shù)據(jù)的緩沖區(qū)指針。nSize
:要寫入的字節(jié)數(shù)。lpNumberOfBytesWritten
:指向一個變量的指針,用于存儲實際寫入的字節(jié)數(shù)。函數(shù)返回值:
示例代碼:
#include <iostream>
#include <windows.h>
int main()
{
// 打開目標進程
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, targetProcessId);
// 寫入數(shù)據(jù)
int value = 123;
LPVOID lpBaseAddress = (LPVOID)0x12345678;
SIZE_T nSize = sizeof(value);
SIZE_T lpNumberOfBytesWritten;
BOOL result = WriteProcessMemory(hProcess, lpBaseAddress, &value, nSize, &lpNumberOfBytesWritten);
if (result)
{
std::cout << "WriteProcessMemory succeeded. Bytes written: " << lpNumberOfBytesWritten << std::endl;
}
else
{
std::cout << "WriteProcessMemory failed. Error code: " << GetLastError() << std::endl;
}
// 關閉目標進程句柄
CloseHandle(hProcess);
return 0;
}
上述示例代碼中,首先使用OpenProcess函數(shù)打開了一個目標進程的句柄。然后通過WriteProcessMemory函數(shù)向目標進程寫入了一個整數(shù)值。最后使用CloseHandle函數(shù)關閉目標進程句柄。