在c/c++中通过其在内存中的地址调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8915797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a function through its address in memory in c / c++
提问by dtech
Given knowledge of the prototype of a function and its address in memory, is it possible to call this function from another process or some piece of code that knows nothing but the prototype and memory address? If possible, how can a returned type be handled back in the code?
鉴于函数原型及其在内存中的地址的知识,是否可以从另一个进程或一些只知道原型和内存地址的代码段调用该函数?如果可能,如何在代码中处理返回的类型?
回答by sbi
On modern operating systems, each process has its own address spaceand addresses are only valid within a process. If you want to execute code in some other process, you either have to inject a shared libraryor attach your program as a debugger.
在现代操作系统上,每个进程都有自己的地址空间,地址只在进程内有效。如果要在其他进程中执行代码,则必须注入共享库或附加程序作为调试器。
Once you are in the other program's address space, this code invokes a function at an arbitrary address:
一旦你进入另一个程序的地址空间,这段代码就会在任意地址调用一个函数:
typedef int func(void);
func* f = (func*)0xdeadbeef;
int i = f();
回答by Carl Norum
Yes - you're describing a function pointer. Here's a simple example;
是的 - 您正在描述一个函数指针。这是一个简单的例子;
int (*func)(void) = (int (*)(void))0x12345678;
int x = func();
It probably won't work between processes - in most operating systems, processes don't have access to each other's memory.
它可能无法在进程之间工作 - 在大多数操作系统中,进程无法访问彼此的内存。
回答by Ulfhetnar
When you need a direct call:
当您需要直接呼叫时:
((void(*)(void))0x1234)();
回答by Fuujuhi
All previous answers are nice but much too long:
以前的所有答案都很好,但太长了:
int i = ((int (*)(void))0xdeadbeef)();
回答by asaelr
In most OP, every process has its own memory, so you can't.
在大多数 OP 中,每个进程都有自己的内存,所以你不能。
Sample code: a.c:
示例代码: ac:
#include <stdio.h>
int r() {return 2;}
int main() {
printf("%p\n",r);
while(1);
}
b.c:
公元前:
#include <stdio.h>
int main() {
int a,(*b)();
scanf("%p",&b);
a=b();
printf("%d\n",a);
return 0;
}
this get segmentation fault.
这得到分段错误。
回答by XxMulti GamerxX
It is definitely possible, but there are restrictions. Each process will have its own block of memory which other processes can't interfere with. Now, you will notice, I wrote it is definitely possible, this is through DLL injection (or code injection).
这绝对是可能的,但有限制。每个进程都有自己的内存块,其他进程不能干涉。现在,你会注意到,我写的绝对是可能的,这是通过 DLL 注入(或代码注入)。
We can use the typedef keyword to achieve this. Now, I see you've marked the answer as 'Answered' and it seems you've gotten on fine, this is just a notice for anyone else that may be interested.
我们可以使用 typedef 关键字来实现这一点。现在,我看到您已将答案标记为“已回答”,而且您似乎进展顺利,这只是给可能感兴趣的其他人的通知。