问题
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?
回答1:
On modern operating systems, each process has its own address space and addresses are only valid within a process. If you want to execute code in some other process, you either have to inject a shared library or 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();
回答2:
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.
回答3:
When you need a direct call:
((void(*)(void))0x1234)();
回答4:
All previous answers are nice but much too long ;-) :
int i = ((int (*)(void))0xdeadbeef)();
回答5:
In most OP, every process has its own memory, so you can't.
Sample code: a.c:
#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.
回答6:
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).
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.
来源:https://stackoverflow.com/questions/8915797/calling-a-function-through-its-address-in-memory-in-c-c