gpt4 book ai didi

c - 将包含函数名称及其参数的字符串传递给另一个函数。

转载 作者:行者123 更新时间:2023-11-30 20:07:39 25 4
gpt4 key购买 nike

我想将一个字符串传递给 C 中的函数,该函数将解析出函数名、函数的参数及其数据类型,然后为我调用该函数。最好的方法是什么?

最佳答案

如果您想编写一个带有格式字符串和变量参数的函数,例如:

int function(const char* strFormat, ... )
{
//parse out the format using regex or something
//then store the data into the variable aruments
//or create a string concatenating everything
}

就像 printf、sprintf 或 scanf 那样,

那么你最好做的就是看一些好的教程。

http://msdn.microsoft.com/en-us/library/fxhdxye9(v=vs.80).aspx

http://www.cprogramming.com/tutorial/c/lesson17.html

如果您想要实际传递要调用的函数的函数名称及其参数,您需要在 C 代码中实现某种形式的反射或内省(introspection),这是一个非常复杂的 switch 语句,它调用函数您基于字符串值,或者编写一些复杂的宏来充当辅助编译器。

glib 的 gobject 是 c 中内省(introspection)的一个很好的例子。 http://developer.gnome.org/gobject/stable/

不自省(introspection)的简单事情可能是:

void* function (const char* strFunctionName, ... )
{
if(!strcmp(strFunctionName, "functionA"))
{
//use va_list to parse out the arguments for the function.
functionA(//each of the arguments from va_list);
}
else if(!strcmp(strFunctionName, "functionB"))
{
//use va_list to parse out the arguments for the function.
functionB(//args from va_list);
}
...
}

如果您有更具体的想法,请在您的问题中具体说明。

关于c - 将包含函数名称及其参数的字符串传递给另一个函数。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9074727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com