头文件:1.h
#include<stdio.h> int nul_func(); int test1(int a,int b); int test2(int a,int b,int c); int test3(int a,int b,int c,int d); int GetFunc(char *p,int (**pfunc)()); struct test { char *pName; int (*pFunc)(); }fun[] = { {"test1",test1}, {"test2",test2}, {"test3",test3}, {"nul_func",nul_func} };
函数实现:15.c
#include "1.h" #include <string.h> int GetFunc(char *p,int (**pfunc)()) { int i=0; while( memcmp(fun[i].pName,"nul_func",8) != 0) { if( memcmp(p,fun[i].pName,strlen(fun[i].pName)) == 0 ) { *pfunc = fun[i].pFunc; return 0; } i++; } printf("%s ","No Such Func."); return 0; } int test1(int a, int b) { printf("a = %d, b = %d ",a,b); return 0; } int test2(int a, int b, int c) { printf("a = %d, b = %d , c = %d ",a,b,c); return 0; } int test3(int a, int b,int c,int d) { printf("a = %d, b = %d, c = %d, d = %d ",a,b,c,d); return 0; } int nul_func() { printf("%s ","No Such Func"); return 0; }
主函数:14.c
#include<stdio.h> int main() { int i; int (*pFunc)(); char caName[10] = ""; memcpy(caName,"test1",5); i = GetFunc(caName,&pFunc); printf("%s ",caName); i = (*pFunc)(1,2); memcpy(caName,"test2",5); i = GetFunc(caName,&pFunc); printf("%s ",caName); i = (*pFunc)(3,4,5); memcpy(caName,"test3",5); i = GetFunc(caName,&pFunc); printf("%s ",caName); i = (*pFunc)(6,7,8,9); return 0; }
编译:gcc 14.c 15.c -o test
结果:./test