如何在C中实现Php call_user_func

时间:2012-09-10 10:52:51

标签: php c function-pointers

php call_user_func()中有一个函数,它接受一个字符串名称的参数,并回调一个名字相似的函数。 同样我想用C语言做。我想编写一个程序,提示用户输入min或max,并根据用户输入的字符串调用min或max函数。我尝试了以下但由于显而易见的原因无效。任何人都可以提出我需要做出的更正

int max(int a, int b)
{
    return a > b ? a : b ;
}

int min(int a, int b)
{
    return a < b ? a : b ;
}

int main()
{
    int (*foo)(int a, int b);
    char *str;
    int a, b;
    str = (char  *)malloc(5);
    printf("Enter the what you want to calculate min or max\n");
    scanf("%s", str);
    printf("Enter the two values\n");
    scanf("%d %d", &a, &b);

    foo = str;

    printf("%d\n", (*foo)(a, b));
    return 0;

}

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

int max(int a, int b)
{
    return a > b ? a : b ;
}

int min(int a, int b)
{
    return a < b ? a : b ;
}

typedef struct {
    int (*fp)(int, int);
    const char *name;
} func_with_name_t;

func_with_name_t functions[] = {
    {min, "min"},
    {max, "max"},
    {NULL, NULL}    // delimiter   
};

int main()
{
    char *str;
    int a, b, i;
    str = (char  *)malloc(5);
    printf("Enter the what you want to calculate min or max\n");
    scanf("%s", str);
    printf("Enter the two values\n");
    scanf("%d %d", &a, &b);

    for (i = 0; functions[i].name != NULL; i++) {
        if (!strcmp(str, functions[i].name)) {
            printf("%d\n", functions[i].fp(a, b));
            break;
        }
    }

    return 0;
}