在 C 中调用以字符串变量命名的函数 [英] Call a function named in a string variable in C

查看:30
本文介绍了在 C 中调用以字符串变量命名的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用变量调用函数.这在 C 中可能吗?

I want to call a function using a variable. Is that possible in C?

其实我想做的是,从用户那里获取函数名,并存入一个变量中.现在我想调用已存储其名称的函数.谁能告诉我如何在 C 中做到这一点?

Actually, what I want to do is, get the function name from the user and store it in a variable. Now I want to call the function that has its name stored. Can anyone tell me how this can be done in C?

我想为两人游戏开发 AI 游戏引擎.两个没有主要功能的程序将被提供给游戏引擎,这些程序实现了赢得比赛的逻辑.让我明确一下,程序名称将与程序中实现赢得比赛逻辑的素函数名称相同.

I want to develop an AI game engine for a two player game. Two programs with no main function that implement the logic for winning the game will be fed to the game engine. Let me be clear that the program names will be same as that of the primefunctions in the program that implement the logic for winning the game.

所以当用户输入第一名和第二名玩家的名字时,我可以将它们存储在 2 个不同的变量中.现在,由于素函数名称与程序名称相同,我打算使用包含程序名称的变量调用函数.

So when the user enters the name of first and second players, I can store them in 2 different variables. Now, since the primefunction names are same as that of the program names, I intend to call the functions with variables containing the prog names.

推荐答案

C 不支持这种操作(有反射的语言会).您将能够做的最好的事情是创建一个从函数名称到函数指针的查找表,并使用它来确定要调用的函数.或者您可以使用 switch 语句.

C does not support this kind of operation (languages that have reflection would). The best you're going to be able to do is to create a lookup table from function names to function pointers and use that to figure out what function to call. Or you could use a switch statement.

这篇关于在 C 中调用以字符串变量命名的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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