c - 按名称处理函数

标签 c linux function function-pointers

假设您创建了一个 main() 来处理您要求学生做的练习。

每个学生都应该使用相同的 API 编写自己的函数。并且将创建一个文件,其中包含所有函数和调用它们的主要函数。

假设:int studentname(int a, int b) 是函数模式。

我处理它的一种方法是使用指向函数 int (*func[MAX])() 的指针 vector 。但是你需要一个一个地完成 vector func[0]=studentname;

我想知道,有没有办法通过函数的名称以某种方式调用函数?

类似于:int student1(int a , int b)student2()

main 中我们可以调用 sscanf(funcname,"student%d",i); funcname();.

你还有别的想法吗?也许

int studentname(int a, int b, char *fname)
{
    strcpy(fname, "studentname");

任何创意都可以! :)

谢谢! 成为

附言。我只尝试了一个函数 vector ,但 C 不允许我这样做! :)

int func[2]()={{;},{;}};

这样我就可以给每个学生一个数字,然后瞧......但没办法。不过这很有趣。


已编辑:我正在使用 linux。

编辑 2:谢谢!我接受了一个对我有帮助的答案,但我还记录了一个完整的示例作为下面的答案。

最佳答案

也许有点过于复杂,但自发的想法:

  • 将所有学生源文件编译到一个共享库中,并导出学生函数。
  • 然后枚举所有暴露的函数,调用并测试它们。

作为替代方案:

  • 编写一个小工具,使用预处理器定义编译所有“学生单元”,以用唯一名称(“func1”、“func2”等)替换预定义的函数名称。
  • 然后让工具编写一个小单元,在执行测试等时调用所有这些函数。

还有一个想法:

  • 使用 C++ 编写一个特殊的类模板,它将在对象工厂中注册派生类,并使用 extern "C" 嵌入学生的代码。不过,根据实现情况,这可能看起来有点困惑和过于复杂。
  • 然后使用工厂为每个实例创建一个实例并运行代码。

使用 dlopen()dlsym() 的方法示例(每个库只有一个函数还是全部 - 无关紧要):

void *pluginlib = dlopen("student1.so", RTLD_NOW); // RTLD_NOW will load the file right away
if (!pluginlib)
    ; // failed to load
studentproc func = (studentproc)dlsym(pluginlib, "student1"); // this loads the function called "student1"
if (!func)
    ; // failed to resolve
func("hello world!"); // call the lib
dlclose(pluginlib); // unloads the dll (this will make all further calls invalid)

关于c - 按名称处理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280384/

相关文章:

在 C 中将 RGB 转换为 RGBA

c - printf ("%d", 1.0) 是否未定义?

r - 在管道 %>% 之后插入 if 语句以在自定义函数中返回错误消息

C 在手动填充的数组中搜索值

C编程: String manipulation

c - 如何将字节转换为整数?

linux - 在 bash 中,循环并发送命令来执行

linux - rvm 安装麻烦

python - 从 python 代码控制本地 redis 服务器

Python:传递带有参数的函数作为参数