函数指针
Functions pointers
大家好,我有一个问题:如何使用指针从枚举结构中调用函数?
例如我有这个结构:
typedef enum struct_e
{
FUNCTION_ONE,
FUNCTION_TWO,
FUNCTION_THREE,
FUNCTION_FOUR,
} sctruct_t;
我有一个函数接收这些变量之一和函数的参数(例如一个 int)
void call_functions(struct_t action, int exemple) {...}
// -> call like this call_functions(FUNCTION_ONE, 45);
在该函数中我必须调用如下函数之一:
void function_one(int a)
{
printf("You have %d years old", a);
}
假设要调用的每个函数都具有类型 void (*)(int)
,您可以创建一个函数指针数组,使用枚举值作为数组索引:
typedef void (*call_func_type)(int);
call_func_type func_list[] = {
[FUNCTION_ONE] = function_one,
[FUNCTION_TWO] = function_two,
[FUNCTION_THREE] = function_three,
[FUNCTION_FOUR] = function_four
}
然后 call_functions
将索引到该数组:
void call_functions(struct_t action, int example)
{
func_list[action](example);
}
我通常发现处理函数指针的第一步是使用 typedef 以使语法更具可读性。然后,可以像使用任何其他数据类型一样使用此类指针。
// declares function_ptr as a new type, pointer to function taking an integer parameter and returning void
typedef void (*function_ptr)(int);
// define function pointer p and initialize to point at function one
function_ptr p = function_one;
// call function_one passing 7 as a parameter
(*p)(7);
在这种情况下,假设所有函数都将整数作为参数,我们可以使用 table 指针来表示您要调用的所有函数:
function_ptr table[]=
{
function_one,
function_two,
function_three,
function_four,
};
此时使用此方法调用任意数量的函数都相当容易。
void call_functions(struct_t action, int exemple)
{
if( action >= FUNCTION_ONE && action <= FUNCTION_FOUR )
{
(table[action])(exemple);
}
else
{
printf("Unrecognized function %i. Check that function table is up to date\n", (int)action);
}
}
大家好,我有一个问题:如何使用指针从枚举结构中调用函数?
例如我有这个结构:
typedef enum struct_e
{
FUNCTION_ONE,
FUNCTION_TWO,
FUNCTION_THREE,
FUNCTION_FOUR,
} sctruct_t;
我有一个函数接收这些变量之一和函数的参数(例如一个 int)
void call_functions(struct_t action, int exemple) {...}
// -> call like this call_functions(FUNCTION_ONE, 45);
在该函数中我必须调用如下函数之一:
void function_one(int a)
{
printf("You have %d years old", a);
}
假设要调用的每个函数都具有类型 void (*)(int)
,您可以创建一个函数指针数组,使用枚举值作为数组索引:
typedef void (*call_func_type)(int);
call_func_type func_list[] = {
[FUNCTION_ONE] = function_one,
[FUNCTION_TWO] = function_two,
[FUNCTION_THREE] = function_three,
[FUNCTION_FOUR] = function_four
}
然后 call_functions
将索引到该数组:
void call_functions(struct_t action, int example)
{
func_list[action](example);
}
我通常发现处理函数指针的第一步是使用 typedef 以使语法更具可读性。然后,可以像使用任何其他数据类型一样使用此类指针。
// declares function_ptr as a new type, pointer to function taking an integer parameter and returning void
typedef void (*function_ptr)(int);
// define function pointer p and initialize to point at function one
function_ptr p = function_one;
// call function_one passing 7 as a parameter
(*p)(7);
在这种情况下,假设所有函数都将整数作为参数,我们可以使用 table 指针来表示您要调用的所有函数:
function_ptr table[]=
{
function_one,
function_two,
function_three,
function_four,
};
此时使用此方法调用任意数量的函数都相当容易。
void call_functions(struct_t action, int exemple)
{
if( action >= FUNCTION_ONE && action <= FUNCTION_FOUR )
{
(table[action])(exemple);
}
else
{
printf("Unrecognized function %i. Check that function table is up to date\n", (int)action);
}
}