我有一个静态函数是为了接收C风格的回调。使用多线程方法进行一些实验时,希望尝试一种将回调接收到不同地址的函数的方法,但不希望在代码中声明它们全部,而是将函数(使用其入口点)复制到内存中的另一个地址,然后注册与回调的adrress。此外,它需要确定功能体的功能入口点的地址..C:如何实现动态功能复制?
任何可能达到这与C,尤其是与Linux上的gcc?
注意:在我的情况下,回调发生在一个参数中,它的源代码是唯一的 - 所以我没有区别回调起源的问题..但是,我觉得需要描述多线程+分叉环境 -分叉不工作::即使在那里,回调将或者通过手柄或过程/叉/线程ID
编辑来识别在下面的代码,realme()和TESTME()共享的地址;我想-finstrument-functions
,backtrace()
和其他一些机会来实现的memcpy +指针方式(见下面的某处评论)..
#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();
}
一个条目,让我们觉得我的'的sizeof做'malloc'( known_size_of_function_body)',复制整个函数体并像'int(* ptr)()x; x(100)' - 这个想法是从http://cboard.cprogramming.com/linux-programming/102703-passing-function-pointer-using-message-queues.html - 这种方式我仍然不能改变任何值函数副本 - 不同的编译器会以不同的方式改变主体 - 但是我可以在运行时接收到函数start的指针吗? –
to @unwind,看http://citforum.ru/book/cook/selfmod.shtml上的示例代码 - 尝试采用,稍后会评论 –