1 #include <unistd.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 typedef int (*Fn)(int i);
6
7 int callback(int i) { //【main进程要执行的】
8 printf("callback : %d\n", i);
9 return i;
10 }
11
12 void proxy(char *address, int i) {
13 Fn fn = NULL;
14 int result = -1;
15 printf("proxy start\n");
16 fn = (Fn)address; // 【将char *强转为函数指针】
17 result = fn(i); // 【代理执行具体的函数】
18 printf("proxy end\n");
19 printf("proxy result = %d\n", result);
20
21 }
22
23 int main(int argc, char *agv[]) {
24 char *temp1 = NULL;
25 char *temp2 = NULL;
26 unsigned long address1 = 0;
27 unsigned long address2 = 0;
28 printf("main : begin\n");
29 address1 = callback;
30 address2 = &callback;
31 printf("main : address 1 = %lu, address 2 = %lu\n", address1, address2);
32 temp1 = (char *)address1; // 【unsigned long 转 char *】
33 temp2 = (char *)address2;
34 printf("main : before temp1\n");
35 proxy(temp1, 100); // 【给代理传递函数指针和形参】
36 printf("main : before temp2\n");
37 proxy(temp2, 200);
38
39 printf("main : end\n");
40 return 0;
41 }
编译:
gcc -o main -g main.c
注意:不要写成 gcc -o main -g -c main.c
#./main
main : begin
main : address 1 = 4195686, address 2 = 4195686
main : before temp1
proxy start
callback : 100
proxy end
proxy result = 100
main : before temp2
proxy start
callback : 200
proxy end
proxy result = 200
main : end
addr2line必须要用64位,如果只是0x400566,无法识别
#addr2line 0x0000000000400566 -e main
/home/kiss1994/study/callback12/main.c:7
#addr2line 0x0000000000400566 -e main -C -f -s
callback
main.c:7
用gdb进行验证:
(gdb) p callback
$1 = {int (int)} 0x400566 <callback> //【还真是这个地址】
char指针和unsigned long的大小
在64位系统上都是8