通过c/c ++中的内存地址调用函数

dte*_*ech 27 c c++ function-call memory-address

鉴于函数原型及其在内存中的地址的知识,是否可以从另一个进程或一些只知道原型和内存地址的代码调用此函数?如果可能,如何在代码中处理返回的类型?

sbi*_*sbi 48

在现代操作系统上,每个进程都有自己的地址空间,地址只在进程中有效.如果要在其他进程中执行代码,则必须注入共享库将程序作为调试器附加.

一旦进入其他程序的地址空间,此代码将调用任意地址的函数:

typedef int func(void);
func* f = (func*)0xdeadbeef;
int i = f();
Run Code Online (Sandbox Code Playgroud)

  • 感谢@ R.Martinho [更好的typedef函数原型样式](http://chat.stackoverflow.com/transcript/message/2400130#2400130).我甚至不知道这个作品! (6认同)
  • @TheQuantumPhysicist:因为每个进程都有自己的虚拟内存空间.你的过程''0xdeadbeef`是你的,我的过程'是我的.它们位于物理内存的不同地址. (2认同)

Car*_*rum 14

是的 - 你正在描述一个函数指针.这是一个简单的例子;

int (*func)(void) = (int (*)(void))0x12345678;
int x = func();
Run Code Online (Sandbox Code Playgroud)

它可能无法在进程之间工作 - 在大多数操作系统中,进程无法访问彼此的内存.

  • @CarlNorum:当你懒得键入`typedef`时会发生这样的错误.`:)` (2认同)

Ulf*_*nar 7

当您需要直接致电时:

((void(*)(void))0x1234)();
Run Code Online (Sandbox Code Playgroud)


Fuu*_*uhi 6

以前的所有答案都很好,但太长了:

int i = ((int (*)(void))0xdeadbeef)();
//                      ==========     --> addr of the function to call
//        =============                --> type of the function to call
//       =========================     --> ... we get a ptr to that fct
//      =============================  --> ... and we call the function
Run Code Online (Sandbox Code Playgroud)

  • 不,他们很棒。另一方面,你的情况非常糟糕。完全没有解释。 (4认同)