C语言高级编程技巧:函数指针与回调机制

函数指针是C语言中最强大的特性之一,它允许我们将函数作为参数传递,实现回调机制,构建灵活的程序架构。

1. 函数指针基础

1.1 函数指针的声明和使用

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
#include <stdio.h>

// 普通函数
int add(int a, int b) {
return a + b;
}

int multiply(int a, int b) {
return a * b;
}

int subtract(int a, int b) {
return a - b;
}

// 函数指针的不同声明方式
void function_pointer_basics() {
printf("=== 函数指针基础 ===\n");

// 方式1:直接声明
int (*operation)(int, int);

// 方式2:使用typedef
typedef int (*Operation)(int, int);
Operation op;

// 赋值和调用
operation = add;
printf("add(5, 3) = %d\n", operation(5, 3));

operation = multiply;
printf("multiply(5, 3) = %d\n", operation(5, 3));

// 使用typedef的版本
op = subtract;
printf("subtract(5, 3) = %d\n", op(5, 3));

// 函数指针数组
Operation operations[] = {add, subtract, multiply};
const char* names[] = {"add", "subtract", "multiply"};

printf("\n函数指针数组演示:\n");
for (int i = 0; i < 3; i++) {
printf("%s(8, 2) = %d\n", names[i], operations[i](8, 2));
}

printf("\n");
}

int main() {
function_pointer_basics();
return 0;
}

1.2 复杂函数指针的声明

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
62
63
64
65
66
67
68
#include <stdio.h>
#include <stdlib.h>

// 返回函数指针的函数
typedef int (*MathOperation)(int, int);

int add_func(int a, int b) { return a + b; }
int mul_func(int a, int b) { return a * b; }

// 返回函数指针的函数
MathOperation get_operation(char op) {
switch (op) {
case '+': return add_func;
case '*': return mul_func;
default: return NULL;
}
}

// 接受函数指针作为参数的函数
int calculate(int a, int b, MathOperation op) {
if (op) {
return op(a, b);
}
return 0;
}

// 函数指针作为结构体成员
typedef struct {
const char* name;
MathOperation operation;
char symbol;
} Calculator;

void complex_function_pointers() {
printf("=== 复杂函数指针应用 ===\n");

// 使用返回函数指针的函数
MathOperation op = get_operation('+');
if (op) {
printf("Dynamic operation: %d\n", op(10, 5));
}

// 使用接受函数指针的函数
int result = calculate(10, 5, get_operation('*'));
printf("Calculate result: %d\n", result);

// 结构体中的函数指针
Calculator calculators[] = {
{"Addition", add_func, '+'},
{"Multiplication", mul_func, '*'}
};

printf("\n结构体中的函数指针:\n");
for (int i = 0; i < 2; i++) {
printf("%s (%c): 7 %c 3 = %d\n",
calculators[i].name,
calculators[i].symbol,
calculators[i].symbol,
calculators[i].operation(7, 3));
}

printf("\n");
}

int main() {
complex_function_pointers();
return 0;
}

2. 回调机制的实现

2.1 基本回调函数

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// 回调函数类型定义
typedef void (*ProgressCallback)(int current, int total, const char* message);
typedef void (*CompletionCallback)(int success, const char* result);

// 进度回调函数实现
void simple_progress_callback(int current, int total, const char* message) {
int percentage = (current * 100) / total;
printf("[%3d%%] %s\n", percentage, message);
}

void detailed_progress_callback(int current, int total, const char* message) {
int percentage = (current * 100) / total;
int bar_length = 30;
int filled = (percentage * bar_length) / 100;

printf("\r[");
for (int i = 0; i < bar_length; i++) {
if (i < filled) {
printf("=");
} else if (i == filled) {
printf(">");
} else {
printf(" ");
}
}
printf("] %3d%% %s", percentage, message);
fflush(stdout);

if (current == total) {
printf("\n");
}
}

// 完成回调函数实现
void success_callback(int success, const char* result) {
if (success) {
printf("✓ 操作成功完成: %s\n", result);
} else {
printf("✗ 操作失败: %s\n", result);
}
}

// 模拟长时间运行的任务
void long_running_task(const char* task_name,
ProgressCallback progress_cb,
CompletionCallback completion_cb) {
const int total_steps = 10;

printf("开始执行任务: %s\n", task_name);

for (int i = 1; i <= total_steps; i++) {
// 模拟工作
struct timespec ts = {0, 200000000}; // 200ms
nanosleep(&ts, NULL);

// 调用进度回调
if (progress_cb) {
char message[100];
snprintf(message, sizeof(message), "正在处理步骤 %d/%d", i, total_steps);
progress_cb(i, total_steps, message);
}
}

// 调用完成回调
if (completion_cb) {
completion_cb(1, "任务成功完成");
}
}

void callback_demo() {
printf("=== 回调机制演示 ===\n");

printf("\n1. 简单进度回调:\n");
long_running_task("数据处理", simple_progress_callback, success_callback);

printf("\n2. 详细进度条回调:\n");
long_running_task("文件传输", detailed_progress_callback, success_callback);

printf("\n3. 无回调执行:\n");
long_running_task("静默任务", NULL, NULL);
printf("任务完成(无回调信息)\n");
}

int main() {
callback_demo();
return 0;
}

2.2 事件驱动系统

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 事件类型
typedef enum {
EVENT_BUTTON_CLICK,
EVENT_KEY_PRESS,
EVENT_MOUSE_MOVE,
EVENT_TIMER,
EVENT_MAX
} EventType;

// 事件数据结构
typedef struct {
EventType type;
void* data;
int timestamp;
} Event;

// 事件处理函数类型
typedef void (*EventHandler)(const Event* event);

// 事件监听器结构
typedef struct EventListener {
EventType event_type;
EventHandler handler;
struct EventListener* next;
} EventListener;

// 事件系统
typedef struct {
EventListener* listeners[EVENT_MAX];
int event_count;
} EventSystem;

// 全局事件系统
static EventSystem g_event_system = {0};

// 注册事件监听器
void register_event_listener(EventType type, EventHandler handler) {
EventListener* listener = malloc(sizeof(EventListener));
listener->event_type = type;
listener->handler = handler;
listener->next = g_event_system.listeners[type];
g_event_system.listeners[type] = listener;
}

// 触发事件
void trigger_event(EventType type, void* data) {
Event event = {
.type = type,
.data = data,
.timestamp = (int)time(NULL)
};

EventListener* listener = g_event_system.listeners[type];
while (listener) {
if (listener->handler) {
listener->handler(&event);
}
listener = listener->next;
}

g_event_system.event_count++;
}

// 事件处理函数实现
void on_button_click(const Event* event) {
const char* button_name = (const char*)event->data;
printf("[%d] 按钮点击事件: %s\n", event->timestamp, button_name);
}

void on_key_press(const Event* event) {
char key = *(char*)event->data;
printf("[%d] 按键事件: '%c'\n", event->timestamp, key);
}

void on_mouse_move(const Event* event) {
int* coords = (int*)event->data;
printf("[%d] 鼠标移动: (%d, %d)\n", event->timestamp, coords[0], coords[1]);
}

void on_timer(const Event* event) {
int* interval = (int*)event->data;
printf("[%d] 定时器事件: %d毫秒\n", event->timestamp, *interval);
}

// 日志记录处理器
void log_all_events(const Event* event) {
const char* event_names[] = {
"BUTTON_CLICK", "KEY_PRESS", "MOUSE_MOVE", "TIMER"
};
printf("[LOG] 事件类型: %s, 时间戳: %d\n",
event_names[event->type], event->timestamp);
}

void event_system_demo() {
printf("=== 事件驱动系统演示 ===\n");

// 注册事件监听器
register_event_listener(EVENT_BUTTON_CLICK, on_button_click);
register_event_listener(EVENT_KEY_PRESS, on_key_press);
register_event_listener(EVENT_MOUSE_MOVE, on_mouse_move);
register_event_listener(EVENT_TIMER, on_timer);

// 注册通用日志监听器
register_event_listener(EVENT_BUTTON_CLICK, log_all_events);
register_event_listener(EVENT_KEY_PRESS, log_all_events);
register_event_listener(EVENT_MOUSE_MOVE, log_all_events);
register_event_listener(EVENT_TIMER, log_all_events);

// 模拟事件触发
printf("\n模拟用户交互:\n");

char* button_names[] = {"确定", "取消", "保存"};
for (int i = 0; i < 3; i++) {
trigger_event(EVENT_BUTTON_CLICK, button_names[i]);
sleep(1);
}

char keys[] = {'A', 'B', 'C'};
for (int i = 0; i < 3; i++) {
trigger_event(EVENT_KEY_PRESS, &keys[i]);
sleep(1);
}

int mouse_positions[][2] = {{100, 200}, {150, 250}, {200, 300}};
for (int i = 0; i < 3; i++) {
trigger_event(EVENT_MOUSE_MOVE, mouse_positions[i]);
sleep(1);
}

int timer_interval = 1000;
trigger_event(EVENT_TIMER, &timer_interval);

printf("\n总共处理了 %d 个事件\n", g_event_system.event_count);
}

int main() {
event_system_demo();
return 0;
}

3. 函数表与策略模式

3.1 策略模式实现

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

// 排序策略接口
typedef void (*SortStrategy)(int* arr, int size);

// 比较策略接口
typedef int (*CompareStrategy)(const void* a, const void* b);

// 冒泡排序实现
void bubble_sort(int* arr, int size) {
printf("使用冒泡排序\n");
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

// 选择排序实现
void selection_sort(int* arr, int size) {
printf("使用选择排序\n");
for (int i = 0; i < size - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
if (min_idx != i) {
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
}

// 插入排序实现
void insertion_sort(int* arr, int size) {
printf("使用插入排序\n");
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

// 比较函数
int compare_ascending(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}

int compare_descending(const void* a, const void* b) {
return (*(int*)b - *(int*)a);
}

// 排序上下文
typedef struct {
SortStrategy strategy;
const char* name;
} SortContext;

// 执行排序
void execute_sort(int* arr, int size, SortContext* context) {
printf("\n执行 %s:\n", context->name);
printf("排序前: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

context->strategy(arr, size);

printf("排序后: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

// 策略工厂
SortContext* create_sort_context(const char* algorithm) {
static SortContext contexts[] = {
{bubble_sort, "冒泡排序"},
{selection_sort, "选择排序"},
{insertion_sort, "插入排序"}
};

if (strcmp(algorithm, "bubble") == 0) return &contexts[0];
if (strcmp(algorithm, "selection") == 0) return &contexts[1];
if (strcmp(algorithm, "insertion") == 0) return &contexts[2];

return &contexts[0]; // 默认使用冒泡排序
}

void strategy_pattern_demo() {
printf("=== 策略模式演示 ===\n");

int original[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(original) / sizeof(original[0]);

const char* algorithms[] = {"bubble", "selection", "insertion"};

for (int i = 0; i < 3; i++) {
// 复制原始数组
int* arr = malloc(size * sizeof(int));
memcpy(arr, original, size * sizeof(int));

// 获取排序策略
SortContext* context = create_sort_context(algorithms[i]);

// 执行排序
execute_sort(arr, size, context);

free(arr);
}

// 使用qsort演示比较策略
printf("\n使用qsort和不同比较策略:\n");

int* arr1 = malloc(size * sizeof(int));
int* arr2 = malloc(size * sizeof(int));
memcpy(arr1, original, size * sizeof(int));
memcpy(arr2, original, size * sizeof(int));

printf("原始数组: ");
for (int i = 0; i < size; i++) {
printf("%d ", original[i]);
}
printf("\n");

qsort(arr1, size, sizeof(int), compare_ascending);
printf("升序排序: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr1[i]);
}
printf("\n");

qsort(arr2, size, sizeof(int), compare_descending);
printf("降序排序: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr2[i]);
}
printf("\n");

free(arr1);
free(arr2);
}

int main() {
strategy_pattern_demo();
return 0;
}

3.2 状态机实现

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 状态枚举
typedef enum {
STATE_IDLE,
STATE_RUNNING,
STATE_PAUSED,
STATE_STOPPED,
STATE_ERROR
} State;

// 事件枚举
typedef enum {
EVENT_START,
EVENT_PAUSE,
EVENT_RESUME,
EVENT_STOP,
EVENT_ERROR_OCCURRED,
EVENT_RESET
} StateMachineEvent;

// 前向声明
typedef struct StateMachine StateMachine;

// 状态处理函数类型
typedef State (*StateHandler)(StateMachine* sm, StateMachineEvent event);

// 状态机结构
struct StateMachine {
State current_state;
StateHandler handlers[5]; // 对应5个状态
void* context; // 状态机上下文数据
int transition_count;
};

// 状态名称
const char* state_names[] = {
"IDLE", "RUNNING", "PAUSED", "STOPPED", "ERROR"
};

// 事件名称
const char* event_names[] = {
"START", "PAUSE", "RESUME", "STOP", "ERROR_OCCURRED", "RESET"
};

// 状态处理函数实现
State handle_idle_state(StateMachine* sm, StateMachineEvent event) {
switch (event) {
case EVENT_START:
printf(" 从空闲状态开始运行\n");
return STATE_RUNNING;
case EVENT_RESET:
printf(" 重置(已经在空闲状态)\n");
return STATE_IDLE;
default:
printf(" 空闲状态下忽略事件: %s\n", event_names[event]);
return STATE_IDLE;
}
}

State handle_running_state(StateMachine* sm, StateMachineEvent event) {
switch (event) {
case EVENT_PAUSE:
printf(" 暂停运行\n");
return STATE_PAUSED;
case EVENT_STOP:
printf(" 停止运行\n");
return STATE_STOPPED;
case EVENT_ERROR_OCCURRED:
printf(" 运行时发生错误\n");
return STATE_ERROR;
default:
printf(" 运行状态下忽略事件: %s\n", event_names[event]);
return STATE_RUNNING;
}
}

State handle_paused_state(StateMachine* sm, StateMachineEvent event) {
switch (event) {
case EVENT_RESUME:
printf(" 恢复运行\n");
return STATE_RUNNING;
case EVENT_STOP:
printf(" 从暂停状态停止\n");
return STATE_STOPPED;
case EVENT_RESET:
printf(" 从暂停状态重置\n");
return STATE_IDLE;
default:
printf(" 暂停状态下忽略事件: %s\n", event_names[event]);
return STATE_PAUSED;
}
}

State handle_stopped_state(StateMachine* sm, StateMachineEvent event) {
switch (event) {
case EVENT_START:
printf(" 从停止状态重新开始\n");
return STATE_RUNNING;
case EVENT_RESET:
printf(" 从停止状态重置\n");
return STATE_IDLE;
default:
printf(" 停止状态下忽略事件: %s\n", event_names[event]);
return STATE_STOPPED;
}
}

State handle_error_state(StateMachine* sm, StateMachineEvent event) {
switch (event) {
case EVENT_RESET:
printf(" 从错误状态重置\n");
return STATE_IDLE;
default:
printf(" 错误状态下只能重置,忽略事件: %s\n", event_names[event]);
return STATE_ERROR;
}
}

// 初始化状态机
void init_state_machine(StateMachine* sm) {
sm->current_state = STATE_IDLE;
sm->handlers[STATE_IDLE] = handle_idle_state;
sm->handlers[STATE_RUNNING] = handle_running_state;
sm->handlers[STATE_PAUSED] = handle_paused_state;
sm->handlers[STATE_STOPPED] = handle_stopped_state;
sm->handlers[STATE_ERROR] = handle_error_state;
sm->context = NULL;
sm->transition_count = 0;
}

// 处理事件
void process_event(StateMachine* sm, StateMachineEvent event) {
State old_state = sm->current_state;
printf("\n[%d] 当前状态: %s, 事件: %s\n",
sm->transition_count, state_names[old_state], event_names[event]);

State new_state = sm->handlers[old_state](sm, event);

if (new_state != old_state) {
sm->current_state = new_state;
sm->transition_count++;
printf(" 状态转换: %s -> %s\n", state_names[old_state], state_names[new_state]);
} else {
printf(" 状态保持: %s\n", state_names[old_state]);
}
}

void state_machine_demo() {
printf("=== 状态机演示 ===\n");

StateMachine sm;
init_state_machine(&sm);

// 模拟状态机事件序列
StateMachineEvent events[] = {
EVENT_START, // IDLE -> RUNNING
EVENT_PAUSE, // RUNNING -> PAUSED
EVENT_RESUME, // PAUSED -> RUNNING
EVENT_ERROR_OCCURRED, // RUNNING -> ERROR
EVENT_START, // ERROR (ignored)
EVENT_RESET, // ERROR -> IDLE
EVENT_START, // IDLE -> RUNNING
EVENT_STOP, // RUNNING -> STOPPED
EVENT_RESET // STOPPED -> IDLE
};

int num_events = sizeof(events) / sizeof(events[0]);

for (int i = 0; i < num_events; i++) {
process_event(&sm, events[i]);
}

printf("\n状态机演示完成,总共进行了 %d 次状态转换\n", sm.transition_count);
}

int main() {
state_machine_demo();
return 0;
}

4. 插件系统设计

4.1 简单插件架构

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h> // 动态库加载(Unix/Linux)

// 插件接口定义
typedef struct {
const char* name;
const char* version;
const char* description;
} PluginInfo;

typedef struct {
PluginInfo* (*get_info)(void);
int (*initialize)(void);
void (*execute)(const char* input, char* output, size_t output_size);
void (*cleanup)(void);
} PluginInterface;

// 插件管理器
typedef struct PluginNode {
char* name;
void* handle; // 动态库句柄
PluginInterface interface;
struct PluginNode* next;
} PluginNode;

typedef struct {
PluginNode* plugins;
int plugin_count;
} PluginManager;

static PluginManager g_plugin_manager = {NULL, 0};

// 静态插件实现(模拟动态插件)

// 文本转换插件
static PluginInfo text_plugin_info = {
.name = "TextTransform",
.version = "1.0.0",
.description = "文本转换插件"
};

PluginInfo* text_plugin_get_info(void) {
return &text_plugin_info;
}

int text_plugin_initialize(void) {
printf("文本转换插件初始化\n");
return 1; // 成功
}

void text_plugin_execute(const char* input, char* output, size_t output_size) {
// 简单的大写转换
strncpy(output, input, output_size - 1);
output[output_size - 1] = '\0';

for (char* p = output; *p; p++) {
if (*p >= 'a' && *p <= 'z') {
*p = *p - 'a' + 'A';
}
}
}

void text_plugin_cleanup(void) {
printf("文本转换插件清理\n");
}

// 数学计算插件
static PluginInfo math_plugin_info = {
.name = "MathCalculator",
.version = "2.1.0",
.description = "数学计算插件"
};

PluginInfo* math_plugin_get_info(void) {
return &math_plugin_info;
}

int math_plugin_initialize(void) {
printf("数学计算插件初始化\n");
return 1;
}

void math_plugin_execute(const char* input, char* output, size_t output_size) {
// 简单的表达式计算(仅支持加法)
int a, b;
if (sscanf(input, "%d+%d", &a, &b) == 2) {
snprintf(output, output_size, "%d", a + b);
} else {
snprintf(output, output_size, "错误:不支持的表达式");
}
}

void math_plugin_cleanup(void) {
printf("数学计算插件清理\n");
}

// 注册静态插件
void register_static_plugin(const char* name, PluginInterface interface) {
PluginNode* node = malloc(sizeof(PluginNode));
node->name = strdup(name);
node->handle = NULL; // 静态插件没有动态库句柄
node->interface = interface;
node->next = g_plugin_manager.plugins;
g_plugin_manager.plugins = node;
g_plugin_manager.plugin_count++;

// 初始化插件
if (interface.initialize) {
interface.initialize();
}
}

// 查找插件
PluginNode* find_plugin(const char* name) {
PluginNode* current = g_plugin_manager.plugins;
while (current) {
if (strcmp(current->name, name) == 0) {
return current;
}
current = current->next;
}
return NULL;
}

// 执行插件
void execute_plugin(const char* plugin_name, const char* input) {
PluginNode* plugin = find_plugin(plugin_name);
if (!plugin) {
printf("错误:找不到插件 '%s'\n", plugin_name);
return;
}

char output[256];
if (plugin->interface.execute) {
plugin->interface.execute(input, output, sizeof(output));
printf("插件 '%s' 执行结果: %s\n", plugin_name, output);
} else {
printf("错误:插件 '%s' 没有执行函数\n", plugin_name);
}
}

// 列出所有插件
void list_plugins(void) {
printf("\n已注册的插件:\n");
printf("%-15s %-10s %s\n", "名称", "版本", "描述");
printf("%-15s %-10s %s\n", "----", "----", "----");

PluginNode* current = g_plugin_manager.plugins;
while (current) {
if (current->interface.get_info) {
PluginInfo* info = current->interface.get_info();
printf("%-15s %-10s %s\n", info->name, info->version, info->description);
}
current = current->next;
}
printf("\n总共 %d 个插件\n", g_plugin_manager.plugin_count);
}

// 清理插件管理器
void cleanup_plugin_manager(void) {
PluginNode* current = g_plugin_manager.plugins;
while (current) {
PluginNode* next = current->next;

// 调用插件清理函数
if (current->interface.cleanup) {
current->interface.cleanup();
}

// 如果是动态插件,关闭动态库
if (current->handle) {
dlclose(current->handle);
}

free(current->name);
free(current);
current = next;
}

g_plugin_manager.plugins = NULL;
g_plugin_manager.plugin_count = 0;
}

void plugin_system_demo() {
printf("=== 插件系统演示 ===\n");

// 注册静态插件
PluginInterface text_interface = {
.get_info = text_plugin_get_info,
.initialize = text_plugin_initialize,
.execute = text_plugin_execute,
.cleanup = text_plugin_cleanup
};

PluginInterface math_interface = {
.get_info = math_plugin_get_info,
.initialize = math_plugin_initialize,
.execute = math_plugin_execute,
.cleanup = math_plugin_cleanup
};

register_static_plugin("TextTransform", text_interface);
register_static_plugin("MathCalculator", math_interface);

// 列出插件
list_plugins();

// 执行插件
printf("\n执行插件示例:\n");
execute_plugin("TextTransform", "hello world");
execute_plugin("MathCalculator", "15+25");
execute_plugin("MathCalculator", "invalid expression");
execute_plugin("NonExistent", "test");

// 清理
cleanup_plugin_manager();
}

int main() {
plugin_system_demo();
return 0;
}

5. 高级应用技巧

5.1 函数指针与泛型编程

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 泛型比较函数类型
typedef int (*CompareFn)(const void* a, const void* b);

// 泛型操作函数类型
typedef void (*ProcessFn)(void* item);

// 泛型过滤函数类型
typedef int (*FilterFn)(const void* item);

// 泛型数组结构
typedef struct {
void* data;
size_t element_size;
size_t capacity;
size_t count;
} GenericArray;

// 创建泛型数组
GenericArray* create_array(size_t element_size, size_t initial_capacity) {
GenericArray* arr = malloc(sizeof(GenericArray));
if (!arr) return NULL;

arr->data = malloc(element_size * initial_capacity);
if (!arr->data) {
free(arr);
return NULL;
}

arr->element_size = element_size;
arr->capacity = initial_capacity;
arr->count = 0;

return arr;
}

// 添加元素
int array_add(GenericArray* arr, const void* element) {
if (arr->count >= arr->capacity) {
// 扩容
size_t new_capacity = arr->capacity * 2;
void* new_data = realloc(arr->data, arr->element_size * new_capacity);
if (!new_data) return 0;

arr->data = new_data;
arr->capacity = new_capacity;
}

char* dest = (char*)arr->data + (arr->count * arr->element_size);
memcpy(dest, element, arr->element_size);
arr->count++;

return 1;
}

// 获取元素
void* array_get(GenericArray* arr, size_t index) {
if (index >= arr->count) return NULL;
return (char*)arr->data + (index * arr->element_size);
}

// 泛型排序
void array_sort(GenericArray* arr, CompareFn compare) {
qsort(arr->data, arr->count, arr->element_size, compare);
}

// 泛型遍历
void array_foreach(GenericArray* arr, ProcessFn process) {
for (size_t i = 0; i < arr->count; i++) {
void* element = array_get(arr, i);
process(element);
}
}

// 泛型过滤
GenericArray* array_filter(GenericArray* arr, FilterFn filter) {
GenericArray* result = create_array(arr->element_size, arr->count);
if (!result) return NULL;

for (size_t i = 0; i < arr->count; i++) {
void* element = array_get(arr, i);
if (filter(element)) {
array_add(result, element);
}
}

return result;
}

// 释放数组
void free_array(GenericArray* arr) {
if (arr) {
free(arr->data);
free(arr);
}
}

// 整数比较函数
int int_compare(const void* a, const void* b) {
int ia = *(const int*)a;
int ib = *(const int*)b;
return (ia > ib) - (ia < ib);
}

// 字符串比较函数
int string_compare(const void* a, const void* b) {
return strcmp(*(const char**)a, *(const char**)b);
}

// 整数打印函数
void print_int(void* item) {
printf("%d ", *(int*)item);
}

// 字符串打印函数
void print_string(void* item) {
printf("%s ", *(char**)item);
}

// 偶数过滤函数
int is_even(const void* item) {
return (*(int*)item) % 2 == 0;
}

// 长字符串过滤函数
int is_long_string(const void* item) {
return strlen(*(char**)item) > 5;
}

void generic_programming_demo() {
printf("=== 泛型编程演示 ===\n");

// 整数数组演示
printf("\n整数数组操作:\n");
GenericArray* int_array = create_array(sizeof(int), 5);

int numbers[] = {64, 34, 25, 12, 22, 11, 90};
for (int i = 0; i < 7; i++) {
array_add(int_array, &numbers[i]);
}

printf("原始数组: ");
array_foreach(int_array, print_int);
printf("\n");

array_sort(int_array, int_compare);
printf("排序后: ");
array_foreach(int_array, print_int);
printf("\n");

GenericArray* even_numbers = array_filter(int_array, is_even);
printf("偶数: ");
array_foreach(even_numbers, print_int);
printf("\n");

// 字符串数组演示
printf("\n字符串数组操作:\n");
GenericArray* string_array = create_array(sizeof(char*), 5);

char* words[] = {"apple", "banana", "cherry", "date", "elderberry", "fig"};
for (int i = 0; i < 6; i++) {
array_add(string_array, &words[i]);
}

printf("原始数组: ");
array_foreach(string_array, print_string);
printf("\n");

array_sort(string_array, string_compare);
printf("排序后: ");
array_foreach(string_array, print_string);
printf("\n");

GenericArray* long_strings = array_filter(string_array, is_long_string);
printf("长字符串: ");
array_foreach(long_strings, print_string);
printf("\n");

// 清理内存
free_array(int_array);
free_array(even_numbers);
free_array(string_array);
free_array(long_strings);
}

int main() {
generic_programming_demo();
return 0;
}

总结

函数指针和回调机制是C语言高级编程的核心技术,掌握这些技巧可以让你的程序更加灵活和可扩展:

  1. 函数指针基础:理解函数指针的声明、赋值和调用
  2. 回调机制:实现事件驱动和异步编程模式
  3. 策略模式:使用函数指针实现算法的动态选择
  4. 状态机:构建复杂的状态转换逻辑
  5. 插件系统:实现模块化和可扩展的架构
  6. 泛型编程:利用函数指针实现类型无关的通用算法

这些技术在系统编程、嵌入式开发、游戏引擎等领域都有广泛应用。通过熟练掌握函数指针,你将能够设计出更加优雅和高效的C语言程序。

版权所有,如有侵权请联系我