我有一个静态函数,用于接收 C 风格的回调。用多线程方法做一些实验,想尝试一种将回调接收到不同地址的函数的方法,但不想在代码中声明所有这些,而是将一个函数(及其入口点)复制到内存中的另一个地址,然后注册带有回调的地址。还需要在函数体中确定函数入口点的地址。
有没有可能用 C 实现这个目标,特别是 Linux 上的 gcc?
注意:在我的情况下,回调是通过一个参数发生的,该参数对于它的源是唯一的——所以我在区分回调来源方面没有问题。但是,我觉得需要描述的方法用于多线程+分叉环境——即使在那里,回调将通过句柄或进程/分叉/线程 ID 识别
编辑:分叉不起作用:在下面的代码中,realme() 和 testme() 是共享地址;我想-finstrument-functions
,backtrace()
以及其他一些实现 memcpy+pointer 方式的机会(见下面的评论)..
#include <iostream>
#include <string>
// Required by for routine
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h> // Declaration for exit()
using namespace std;
int globalVariable = 2;
void realme()
{
cout << "Testme() is at: " << __builtin_return_address(1) << std::endl;
}
void testme()
{
realme();
}
main()
{
string sIdentifier;
int iStackVariable = 20;
pid_t pID = fork();
if (pID == 0) // child
{
// Code only executed by child process
sIdentifier = "Child Process: ";
globalVariable++;
iStackVariable++;
}
else if (pID < 0) // failed to fork
{
cerr << "Failed to fork" << endl;
exit(1);
// Throw exception
}
else // parent
{
// Code only executed by parent process
sIdentifier = "Parent Process:";
}
// Code executed by both parent and child.
cout << sIdentifier;
cout << " Global variable: " << globalVariable;
cout << " Stack variable: " << iStackVariable << endl;
testme();
}