还有SD卡的文件格式识别还不会,等明天和飞刀一起讨论下,基本的Android的SD卡的自动挂载已经实现了,可惜只支持FAT格式的,EXT格式的他不支持,添加了那些其他格式的挂载还是不行,主要是识别还不知道怎么去实现。好了,既然这么着,还是把以前看的一些函数指针做个记录吧。因为linux驱动中很多很多都用到了函数指针,一开始我都觉得奇怪,后来才知道这个。都怪自己以前对于指针的一些知识学得太少了,太浅了。
先看个简单的代码吧:
#include <stdio.h> static int max(int a,int b) { if(a > b) { return a; } else { return b; } return 0; } int main(void) { int(*pmax)(int, int); //函数指针 int x, y, z; pmax = max; //把函数max的首地址赋值给pmax函数指针 printf("input two numbers:\n"); scanf("%d%d",&x, &y); z = (*pmax)(x, y); //调用函数 printf("maxmum = %d\n",z); return 0; }
再看看运行结果:
这里定义了一个函数指针,pmax,然后这个指针指向了max这个函数,然后当执行z = (*pmax)(x, y);时就会执行那个比较大小的函数了,然后就有了上面的结果了。
好了,接下去我们看看比较复杂的,本人写得搓搓的代码:
#include <stdio.h> #include <math.h> #include <stdlib.h> struct point { int x; int y; }; struct my_point_ops { struct point *p; double (*line_Length)(struct point p1, struct point p2); int (*draw_Point)(struct point *p); }; double my_line_length(struct point p1, struct point p2) { return ((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y)); } int my_draw_point(struct point *p) { return p->x + p->y; } struct my_point_ops mops = { .line_Length = my_line_length, .draw_Point = my_draw_point }; int main(void) { struct point p1 = {.x = 5, .y = 2}; struct point p2 = {.x = 1, .y = 8}; p3 = (struct point *)malloc(sizeof(struct point)); p3->x = 3; p3->y = 4; printf("%lf\n", mops.line_Length(p1, p2)); printf("%d\n", mops.draw_Point(p3)); free(p3); return 0; }
不知道为什么Cfree运行错了,用GCC编译时过了的。这个就不纠结了。
首先看看这个my_point_ops结构体
struct my_point_ops { struct point *p; double (*line_Length)(struct point p1, struct point p2); int (*draw_Point)(struct point *p); };
里面定义了两个函数指针。驱动里的代码越来越觉得有面向对象的概念了,什么都是一个一个对象一个结构了。
然后接下来看看这个,这个其实就是初始化了,其函数指针line_Length指向了my_line_length函数,函数指针draw_Point =指向了my_draw_point函数。
struct my_point_ops mops = { .line_Length = my_line_length, .draw_Point = my_draw_point };
在看最后
printf("%lf\n", mops.line_Length(p1, p2)); printf("%d\n", mops.draw_Point(p3));
当调用mmops的成员函数mops.line_Length(p1, p2)其实就是调用了
double my_line_length(struct point p1, struct point p2) { return ((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y)); }
而当调用mmops的成员函数mops.draw_Point(p3)其实就是调用了
int my_draw_point(struct point *p) { return p->x + p->y; }
简单吧,就是这样的。哈哈。。。。