我知道每个进程都创建了自己的内存地址空间,不过我想知道,
如果进程A具有如下函数:
int DoStuff() { return 1; }
Run Code Online (Sandbox Code Playgroud)
和指针typedef,如:
typedef int(DoStuff_f*)();
Run Code Online (Sandbox Code Playgroud)
和一个getter函数,如:
DoStuff_f * getDoStuff() { return DoStuff; }
Run Code Online (Sandbox Code Playgroud)
和一个通过...进行通信的神奇方式...说boost :: interprocess
是否可以将函数指针传递给进程B并调用
直接从流程B处理A的DoStuff?
不.所有函数指针都是进程地址空间中的地址.它没有内在标记,这是不同过程所特有的.因此,即使您的函数指针恰好在将其移动到B后仍然有效,它也会代表进程B调用该函数.
例如,如果你有
////PROCESS A////
int processA_myfun() { return 3; }
// get a pointer to pA_mf and pass it to process B
////PROCESS B////
int processB_myfun() { return 4; } // This happens to be at the same virtual address as pA_myfun
// get address from process A
int x = call_myfun(); // call via the pointer
x == 4; // x is 4, because we called process B's version!
Run Code Online (Sandbox Code Playgroud)
如果进程A和B运行相同的代码,您可能会在相同的地址处使用相同的函数 - 但您仍将使用B的数据结构和全局内存!所以简短的回答是,不,这不是你想要做到的!
此外,诸如地址空间布局随机化之类的安全措施可以防止这些"诡计"无法正常工作.
你混淆了IPC和RPC.IPC用于传递数据,例如对象或文本块. RPC用于使代码在远程进程中执行.