初始化C中的函数指针 [英] Initializing a function pointer in C
问题描述
我有函数
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ code>
并且在主程序中有:
given_Role = Authorization_getRole(userId,roleTable)
我想用函数调用替换一个函数指针:
pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ given_Role =& getRole_ptr;
我的问题是:
我初始化函数指针getRole_ptr?
如何初始化函数指针?
下面的语法正确吗?
getRole_ptr = Authorization_getRole(userId,roleTable)
我总是推荐带有函数指针的typedef。然后,你会写:
//确保在这里获得函数的签名
typedef uint8_t(* GetRole_Ptr_T )(char const *,UsertoRole_T const *);
//现在初始化你的指针:
GetRole_Ptr_T getRole_ptr = Authorization_getRole;
//调用指向的函数:
given_Role = getRole_ptr(userId,roleTable);
关于我在哪里初始化函数指针getRole_ptr?:取决于您的需求。您可以在声明指针时执行此操作(如我在示例中所做的操作),也可以稍后更改指针:
getRole_ptr = Some_function_with_correct_signature;
I have the function
uint8_t Authorization_getRole (char const* userId, UsertoRole_T const *roleTable)
and in the main program I have:
given_Role = Authorization_getRole (userId, roleTable)
I want to replace the function call with a function pointer:
uint8_t (*getRole_ptr)()
given_Role = &getRole_ptr;
My questions are:
Where do I initalize the function pointer getRole_ptr?
How do I initialize the function pointer?
Is the syntax below correct?
getRole_ptr = Authorization_getRole (userId, roleTable)
I'd always recommend a typedef with function pointers. Then, you would write:
// Make sure to get the function's signature right here
typedef uint8_t (*GetRole_Ptr_T)(char const*, UsertoRole_T const*);
// Now initialize your pointer:
GetRole_Ptr_T getRole_ptr = Authorization_getRole;
// To invoke the function pointed to:
given_Role = getRole_ptr(userId, roleTable);
Regarding "Where do I initalize the function pointer getRole_ptr?": Depends on your requirements. You can do it when declaring the pointer, as I did in my example, or you can change the pointer later on by assigning to it:
getRole_ptr = Some_function_with_correct_signature;
这篇关于初始化C中的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!