确定某一个函数指针在C指点? [英] Determining to which function a pointer is pointing in C?

查看:120
本文介绍了确定某一个函数指针在C指点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数指针,承担任何签名。
和我有相同的签名5个不同的功能。

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 function is called.

如果没有这些功能插入任何打印语句,我怎么会知道的函数指针当前指向?名

Without inserting any print statement in those functions, how can I come to know the name of function which the pointer currently points to?

推荐答案

您必须检查其中的5个功能指针指向:

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);

这篇关于确定某一个函数指针在C指点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆