源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h> 

typedef void (*pFunction)(void); //无返回值
typedef unsigned long (*pFunction2)(void); //有返回值

unsigned long aaa(void)
{
printf("my address is %lx\r\n", (unsigned long)aaa);
return (unsigned long)aaa; //返回函数地址
}


int main()
{
void (*p1)(void);

printf("void * - %ld\r\n",sizeof(void*))
printf("unsigned int - %ld\r\n",sizeof(unsigned int));
printf("unsigned long - %ld\r\n",sizeof(unsigned long));

unsigned long b = 0;

unsigned long a = aaa();
printf("a = %lx\r\n",a);

p1 = (void(*)(void))aaa; //显式转换
p1();

p1 = aaa; //隐式转换
//b = p1(); //wrong

p1 = a; //直接使用地址
p1();

unsigned long (*p2)(void); //定义函数指针
p2 = a; //直接使用地址
b = p2();
printf("b=%lx\r\n",b);

((void(*)())a)();
b = ((unsigned long(*)())a)();
printf("b=%lx\r\n",b);

pFunction pp = aaa;
pp();
//b = pp(); //wrong
pp = a;
pp();

pFunction2 pp2 = a;
b = pp2();
printf("b=%lx\r\n",b);

printf("a=%lx\r\n",a);
pFunction f = (pFunction)a;
f();

pFunction f2 = (void(*)())a;
f2();
return 0;
}

结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
ly@xxxx:test$ ./d
void * - 8
unsigned int - 4
unsigned long - 8
my address is 55d37b981149
a = 55d37b981149
my address is 55d37b981149
my address is 55d37b981149
my address is 55d37b981149
b=55d37b981149
my address is 55d37b981149
my address is 55d37b981149
b=55d37b981149
my address is 55d37b981149
my address is 55d37b981149
my address is 55d37b981149
b=55d37b981149
a=55d37b981149
my address is 55d37b981149
my address is 55d37b981149