0

我有一个静态函数,用于接收 C 风格的回调。用多线程方法做一些实验,想尝试一种将回调接收到不同地址的函数的方法,但不想在代码中声明所有这些,而是​​将一个函数(及其入口点)复制到内存中的另一个地址,然后注册带有回调的地址。还需要在函数体中确定函数入口点的地址。

有没有可能用 C 实现这个目标,特别是 Linux 上的 gcc?

注意:在我的情况下,回调是通过一个参数发生的,该参数对于它的源是唯一的——所以我在区分回调来源方面没有问题。但是,我觉得需要描述的方法用于多线程+分叉环境——即使在那里,回调将通过句柄或进程/分叉/线程 ID 识别

编辑:分叉不起作用:在下面的代码中,realme() 和 testme() 是共享地址;我想-finstrument-functionsbacktrace()以及其他一些实现 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();
}
4

2 回答 2

1

这将要求您编写自我修改代码,除了它不是那么简单之外,它还会给您带来巨大的性能损失。模拟所需内容而没有太多麻烦的唯一方法是制作某种宏,每次需要传递回调函数指针时都会编写一个新函数,但必须在编译时知道它。也许宏可以在您每次引用它时根据某些参数生成一个函数到一个 .c 文件。

PS 不是在谈论,#define而是在预编译时调用的应用程序,搜索关键字并进入 .c 文件

于 2011-07-07T13:14:35.737 回答
1

我不认为你可以在 C 中可靠地做到这一点。不能保证驻留在函数内部的代码在执行后独立于其自身的位置(考虑本地分支)。没有办法在 C 中获得函数的大小,所以你不知道要复制多少。

于 2011-07-07T12:53:56.713 回答