1. 設定function point, 沒有回傳值, 沒有輸入參數
#include
void (*pFun) (); //create a function point and return void
void funA ()
{
printf("A\n"); //if you set pFun = funA, and call pFun, it will show "A"
}
void funB ()
{
printf("B\n"); //if you set pFun = funB and call pFun, it will show "B"
}
int main(int argc, char *argv[])
{
pFun = funA; //set pFun = funA
pFun();
pFun = funB; //set pFun = funB
pFun();
}
輸出
nelsonchung@gps1004:~/test/funpoint$ vim funpoint1.c
nelsonchung@gps1004:~/test/funpoint$ gcc funpoint1.c -o a.out
nelsonchung@gps1004:~/test/funpoint$ ./a.out
A
B
2. 設定function point, 沒有回傳值, 有輸入參數
#include
void (*pFun) (int i); //create a function point and have one arg
void funA (int i) //if you set pFun = funA, and set arg, it will show the number the same with you input
{
printf("A = %d\n",i);
}
void funB (int i)
{
printf("B = %d\n",i);
}
int main(int argc, char *argv[])
{
pFun = funA;
pFun(1);
pFun = funB;
pFun(2);
}
輸出
nelsonchung@gps1004:~/test/funpoint$ vim funpoint2.c
nelsonchung@gps1004:~/test/funpoint$ gcc funpoint2.c -o b.out
nelsonchung@gps1004:~/test/funpoint$ ./b.out
A = 1
B = 2
3. 設定function point, 有回傳值, 有輸入參數
#include
int (*pFun) (int i); //create a function point, have one arg input and have return value
int funA (int i)
{
printf("funA: input %d\n",i);
return i;
}
int funB (int i)
{
printf("funB: input %d\n",i);
return i;
}
int main(int argc, char *argv[])
{
pFun = funA;
printf("call pFun = %d\n", pFun(1));
pFun = funB;
printf("call pFun = %d\n", pFun(2));
}
輸出
nelsonchung@gps1004:~/test/funpoint$ vim funpoint3.c
nelsonchung@gps1004:~/test/funpoint$ gcc funpoint3.c -o c.out
nelsonchung@gps1004:~/test/funpoint$ ./c.out
funA: input 1
call pFun = 1
funB: input 2
call pFun = 2
需求起源
linux kernel code 有許多用struct都用function point先宣告
根據不同的設備
再去指定需要執行的function
ex.
usb 1, 2, 3, 4不同裝置
整個usb架構出來之後
接下來只需要設定相關的function需要做什麼事情
就可以自動呼叫相關的function嚕
沒有留言:
張貼留言