我的程序包含以下文件:data_handler.c、app.c 和 callback_struct.h。
data_handler.c 通过回调 app.c 从 app.c 中的函数中检索数据。
该程序应允许用户在 app.c 中定义一组具有任意名称的函数。用户通过定义他的函数,并将它们与一组启动的函数指针(ptr_func1、ptr_func2 等)相关联,在 callback_struct.h 中找到。
通过这种方法,我想消除从 data_handler.c 对 app.c 中的用户函数进行显式调用的需要(这样,如果用户更改其函数名称,则不必修改 data_handler.c 中的代码例如),我也不想将 (#) app.c 包含到 data_handler.c 中。
很明显,这里有些事情我没有说到。如果有人能帮助我理解我做错了什么,并可能给我一些指示,说明我建议的实现是否在正确的轨道上,我将不胜感激
在下面查看我的实现:
回调结构.h:
struct callback_struct{
int (*ptr_func1)(void);
int (*ptr_func2)(void);
// etc...
};
extern struct callback_struct user_functions; // should be defined in app.c
应用.c
#include "callback_struct.h"
int user_function_func1(void);
int user_function_func2(void);
struct callback_struct user_functions={
.ptr_func1 = user_function_func1,
.ptr_func2 = user_function_func2,
};
int user_function_func1(void){
int data = 1; // for example...
return data;
}
int user_function_func2(void){
int data = 2; // for example...
return data;
}
// etc.....
数据处理程序.c
#include "callback_struct.h"
/*this function makes callbacks to app.c to retrieve data*/
void get_data(int (*ptr)(void)){
int retrieved_data=ptr();
}
void main(void){
get_data(user_functions.ptr_func1);
get_data(user_functions.ptr_func2);
// etc....
}
最佳答案
这只是一个语法错误。只需更换
extern struct user_functions={
通过
struct callback_struct user_functions={
在您的 app.c 中,它会起作用。
关于c - C语言实现文件间回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20925124/