今天偶然看到一段代码,是关于函数指针强制转化的,看了半天都没看明白。回来写了个形式类似的代码:- int add(int a, int b)
- {
- return (a+b);
- }
- int sub(int a, int b,int c)
- {
- c= c + 1;
- return (a-b);
- }
- typedef int (*padd)(int, int);
- typedef int (*psub)(int, int, int);
- int main(void)
- {
- int ret;
- padd fun = (padd)sub;
- ret = fun(2,3);
- return 0;
- }
开始给 ret = fun(2,3,4),结果编译不通过,说参数个数太多,改为2个,通过。由此推测,强制类型转换后,函数参数的传递要按强制类型转换的函数指针类型声明来传递。也就是这里的 padd类型,需要2个int参数。不理解,于是汇编:- .file "a.c"
- .text
- .align 2
- .global add
- .type add, %function
- add:
- @ Function supports interworking.
- @ args = 0, pretend = 0, frame = 8
- @ frame_needed = 1, uses_anonymous_args = 0
- mov ip, sp
- stmfd sp!, {fp, ip, lr, pc}
- sub fp, ip, #4
- sub sp, sp, #8
- str r0, [fp, #-16]
- str r1, [fp, #-20]
- ldr r2, [fp, #-16]
- ldr r3, [fp, #-20]
- add r3, r2, r3
- mov r0, r3
- sub sp, fp, #12
- ldmfd sp, {fp, sp, lr}
- bx lr
- .size add, .-add
- .align 2
- .global sub
- .type sub, %function
- sub:
- @ Function supports interworking.
- @ args = 0, pretend = 0, frame = 16
- @ frame_needed = 1, uses_anonymous_args = 0
- mov ip, sp
- stmfd sp!, {fp, ip, lr, pc}
- sub fp, ip, #4
- sub sp, sp, #16
- str r0, [fp, #-16]
- str r1, [fp, #-20]
- str r2, [fp, #-24]
- ldr r3, [fp, #-24]
- add r3, r3, #1
- str r3, [fp, #-24]
- ldr r2, [fp, #-16]
- ldr r3, [fp, #-20]
- rsb r3, r3, r2
- mov r0, r3
- sub sp, fp, #12
- ldmfd sp, {fp, sp, lr}
- bx lr
- .size sub, .-sub
- .align 2
- .global main
- .type main, %function
- main:
- @ Function supports interworking.
- @ args = 0, pretend = 0, frame = 8
- @ frame_needed = 1, uses_anonymous_args = 0
- mov ip, sp
- stmfd sp!, {fp, ip, lr, pc}
- sub fp, ip, #4
- sub sp, sp, #8
- ldr r3, .L7
- str r3, [fp, #-16]
- ldr r3, [fp, #-16]
- mov r0, #2
- mov r1, #3
- mov lr, pc
- bx r3
- mov r3, r0
- str r3, [fp, #-20]
- mov r3, #0
- mov r0, r3
- sub sp, fp, #12
- ldmfd sp, {fp, sp, lr}
- bx lr
- .L8:
- .align 2
- .L7:
- .word sub
- .size main, .-main
- .ident "GCC: (GNU) 4.1.2"
果真如此,他最终调用的是sub,而不是add,那么sub需要的第三个参数怎么来,(arm函数参数传递<=4时用r0-r3来传,超出用堆栈),看到sub里面,r2被用上了,这时它是个随机的值。 函数体依旧用原来的,只是参数传递按强制类型的。看不出这样使用有什么作用?明天继续。
算是比较丢脸,自己连函数调用和函数指针转换都搞错了。此处本是一个函数调用而已,我去偏偏看成是个函数指针转换,浪费时间。貌似函数指针转换基本没意义。
阅读(3980) | 评论(0) | 转发(0) |