Get called function name as string

前端 未结 2 2006
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 08:13

I\'d like to display the name of a function I\'m calling. Here is my code

void (*tabFtPtr [nbExo])(); // Array of function pointers
int i;
for (i = 0; i <         


        
2条回答
  •  一生所求
    2020-12-09 09:10

    I'm not sure this is what you want, but you could do something like this. Declare a structure to hold a function name and address, and an array of functions at file scope:

    #define FNUM 3
    
    struct fnc {
        void *addr;
        char name[32];
    };
    
    void (*f[FNUM])();
    struct fnc fnames[FNUM];
    

    Initialise these in your code manually by function name, e.g.

        fnames[0] = (struct fnc){foo1, "foo1"}; // function address + its name
        fnames[1] = (struct fnc){foo2, "foo2"};
        fnames[2] = (struct fnc){foo3, "foo3"};
    

    Make a function to search the array, e.g.

    char *getfname(void *p)
    {
            for (int i = 0; i < FNUM; i++) {
                    if (fnames[i].addr == p)
                            return fnames[i].name;
            }
            return NULL;
    }
    

    I ran a quick test of this. I initialised the array in main, and called foo1(). Here's my function, and the output:

    void foo1(void)
    {
        printf("The pointer of the current function is %p\n", getfnp(__func__));
        printf("The name of this function is %s\n", getfname(getfnp(__func__)));
        printf("The name of the function at pointer f[2] (%p) is '%s'\n", f[2],
            getfname(f[2]));    
    }
    
    The pointer of the current function is 0x400715
    The name of this function is foo1
    The name of the function at pointer f[2] (0x40078c) is 'foo3'
    

    Or, more generally:

    void foo2(void)
    {
        for (int i = 0; i < FNUM; i++) {
            printf("Function f[%d] is called '%s'\n", i, getfname(f[i]));
        }
    }
    
    Function f[0] is called 'foo1'
    Function f[1] is called 'foo2'
    Function f[2] is called 'foo3'
    

提交回复
热议问题