arrays - Using a function from a function array stored in a struct in C
问题描述
I declared a struct like this one :
typedef struct s_data {
char buff[2048];
int len;
void *func[10];
struct data *next;
} t_data;
In my code, when passing a *data, I assigned some functions (just giving one so it is more understandable)
void init_data(t_data *data)
{
data->len = 0;
data->func[0] = &myfirstfunctions;
//doing the same for 9 others
}
My first function would be something taking as argument *data, and an int. Then, I try to use this function in another function, doing
data->func[0](data, var);
I tried this and a couple of other syntaxes involving trying to adress (*func[0]) but none of them work. I kind of understood from other much more complex questions over there that I shouldn't store my function like this, or should cast it in another typedef, but I did not really understand everything as I am kind of new in programming.
解决方案
void*
can only be used reliably as a generic object pointer ("pointer to variables"). Not as a generic function pointer.
You can however convert between different function pointer types safely, as long as you only call the actual function with the correct type. So it is possible to do just use any function pointer type as the generic one, like this:
void (*func[10])(void);
...
func[0] = ((void)(*)(void))&myfirstfunction;
...
((whatever)func[0]) (arguments); // call the function
As you might note, the function pointer syntax in C is horrible. So I'd recommend using typedefs:
typedef void genfunc_t (void);
typedef int somefunc_t (whatever*); // assuming this is the type of myfirstfunction
Then the code turns far easier to read and write:
genfunc_t* func [10];
...
func[0] = (genfunc_t*)&myfirstfunction;
...
((somefunc_t*)func[0]) (arguments);
推荐阅读
- java - Mockito:验证参数而无需强制转换
- c++ - 未找到模板重载
- output - 输出 vhdl 信号分配
- adfs - 带有 ADFS 的 Project Server 2016 PSI
- mysql - mysql查询以获取每个给定键的记录
- node.js - 源代码中的节点快速请求处理程序
- php - google adwords api oauth2 api 刷新令牌出错
- node.js - Puppeteer 的 Click API 不会在图像地图元素上触发
- extjs - 当单元格的红旗被移除或已知保留时,ExtJs 6 checkcolumn 监听器
- python - Tensorflow Estimator 中的 TFHub 嵌入特征列