lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  430 随笔 :: 1 文章 :: 3 评论 :: 21万 阅读
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

[c/cpp]:函数指针数组的应用(模拟系统调用)

 

 

 

一、说明

 

  1、  函数指针数组:  一个指针数组,它的元素是函数指针;函数指针数组。

 

 

二、程序代码

复制代码
 1 [root@rocky:test]# cat syscalls.c 
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 
 5 
 6 // syscall macros
 7 #define sys_msg0        0
 8 #define sys_msg1        1
 9 #define sys_msg2        2
10 #define sys_msg3        3
11 
12 
13 // important
14 // declaring: a array pointing to functions
15 // int (*sf[10])(int);
16 
17 
18 // define syscalls - simulate syscalls
19 int msg0(int x)
20 {
21         printf("\t[msg0]#\t syscall_msg0:\t%d\n", x);
22         return 0;
23 }
24 
25 
26 int msg1(int x)
27 {
28         printf("\t[msg1]#\t syscall_msg1:\t%d\n", x);
29         return 0;
30 }
31 
32 
33 int msg2(int x)
34 {
35         printf("\t[msg2]#\t syscall_msg2:\t%d\n", x);
36         return 0;
37 }
38 
39 
40 int msg3(int x)
41 {
42         printf("\t[msg3]#\t syscall_msg3:\t%d\n", x);
43         return 0;
44 }
45 
46 
47 // important
48 // declaring: a array pointing to functions
49 // 
50 // int (*sf[10])(int);  |
51 //                      |
52 // sf[0] = msg0;        |
53 // sf[1] = msg1;        |       wrong, why?
54 // sf[2] = msg2;        |
55 // sf[3] = msg3;        |
56 
57 int (*sf[10])(int) = { msg0, msg1, msg2, msg3 };
58 
59 
60 // function: execute syscalls
61 int user_syscall(int sno)       // sno = syscall number
62 {
63         if ( 0==(sf[sno])(sno) ) {
64                 return 0;
65         } else {
66                 return 1;
67         }
68 }
69 
70 
71 // test modules
72 int main(int argc, char *argv[], char *envp[])
73 {
74 
75         printf("\n");
76         user_syscall(sys_msg0);
77         user_syscall(sys_msg1);
78         user_syscall(sys_msg2);
79         user_syscall(sys_msg3);
80         printf("\n");
81 
82         return 0;
83 }
84 [root@rocky:test]# 
复制代码

 

 

 

三、运行结果

复制代码
[root@rocky:test]# gcc -o syscalls syscalls.c && ./syscalls

        [msg0]#  syscall_msg0:  0
        [msg1]#  syscall_msg1:  1
        [msg2]#  syscall_msg2:  2
        [msg3]#  syscall_msg3:  3

[root@rocky:test]# 
[root@rocky:test]# 
复制代码

 

 

 

四、参考资料

 

  1.  C函数指针与回调函数|菜鸟教程  -  https://www.runoob.com/cprogramming/c-fun-pointer-callback.html

 

posted on   lnlidawei  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2023-11-01 os_config: fedora38 ~ bash config
点击右上角即可分享
微信分享提示