繁体   English   中英

C++,如何用指向特定地址的指针访问

[英]C++, how to access with a pointer to a specific address

我很好奇,所以我尝试这样做:

第一个程序:

#include <iostream>

using namespace std;

int a = 5;

int main()
{
    
    cout << "Value of a: " << a << endl;
    cout << "Address of a: " << &a << endl;
    
    system("pause");
    
    return 0;
}

Output:

  • a的值:5
  • 地址:0x472010

第二个程序:

#include <iostream>

using namespace std;

int* p = reinterpret_cast<int*>(0x472010);
    
int main() 
{   
    cout << "Value of p: " << *p << endl;
    cout << "The address that the pointer points to: " << p << endl;
    
    cout << endl;
    
    system("pause");
    return 0;
}

所以,我想用属于另一个程序的“p”指针读取变量“a”的值,而“p”指针指向特定地址。

在我运行第二个程序之前一切都很好,因为第二个程序没有给出想要的结果

Output 第二程序:

  • p的值:4661264
  • 指针指向的地址:0x472010

如果我保持第一个程序的 window 打开,结果不会改变。

我 promise 我是初学者,我正在尝试新事物

我究竟做错了什么?

您无法以您尝试的方式直接访问另一个进程的 memory。 每个进程都在自己的地址空间中运行。 您的第二个进程试图在其自己的地址空间内访问(无效)地址,而不是在第一个进程的地址空间内。

On Windows, to read another process's memory, your 2nd process must obtain a HANDLE to the 1st process, such as from OpenProcess() , and then must use ReadProcessMemory() to read memory from an address within the 1st process.

另一种方法是让第一个进程分配一个共享 memory块,第二个进程可以直接访问该块。 在 Windows 上,您可以为此目的使用CreateFileMapping()MapViewOfFile() (请参阅 MSDN 上的创建命名共享 Memory )。 在 'Nix 系统上,您可以使用shm_open() mmap()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM