Determining to which function a pointer is pointing in C?

后端 未结 9 1105
情话喂你
情话喂你 2021-02-01 12:25

I have a pointer to function, assume any signature. And I have 5 different functions with same signature.

At run time one of them gets assigned to the pointer, and that

9条回答
  •  萌比男神i
    2021-02-01 13:16

    You will have to check which of your 5 functions your pointer points to:

    if (func_ptr == my_function1) {
        puts("func_ptr points to my_function1");
    } else if (func_ptr == my_function2) {
        puts("func_ptr points to my_function2");
    } else if (func_ptr == my_function3) {
        puts("func_ptr points to my_function3");
    } ... 
    

    If this is a common pattern you need, then use a table of structs instead of a function pointer:

    typedef void (*my_func)(int);
    
    struct Function {
        my_func func;
        const char *func_name;
    };
    
    #define FUNC_ENTRY(function) {function, #function}
    
    const Function func_table[] = {
        FUNC_ENTRY(function1),
        FUNC_ENTRY(function2),
        FUNC_ENTRY(function3),
        FUNC_ENTRY(function4),
        FUNC_ENTRY(function5)
    }
    
    struct Function *func = &func_table[3]; //instead of func_ptr = function4;
    
    printf("Calling function %s\n", func->func_name);
    func ->func(44); //instead of func_ptr(44);
    

提交回复
热议问题