gpt4 book ai didi

c - 如何从 STDIN 读取 C 函数并在程序中运行它?

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:20 25 4
gpt4 key购买 nike

我想编写一个从标准输入读取的程序:scanf("%s %s", foo, args); 然后运行带参数的函数 foo(之前在程序中定义): foo(args); 我不知道如何在 C 中执行此操作。我以前可以在 Shell 中轻松地做到这一点,但在 C 中似乎很难

最佳答案

对于这个同时通用跨平台/标准的问题没有解决方案。

不依赖非标准扩展的非通用解决方案:将名称和函数指针对存储在数组中,执行搜索,通过指针调用函数。例如:

struct namedfunc {
const char *name;
void (*fptr)(void);
} fvect[3] = {
{ "foo", foo_impl },
{ "bar", bar_impl },
{ "baz", baz_impl }
};

char buf[0x100];
fgets(buf, sizeof buf, stdin);
char *p = strchr(buf, '\n');
if (p != NULL)
*p = 0;

for (size_t i = 0; i < sizeof fvect / sizeof fvect[0]; i++) {
if (strcmp(buf, fvect[i].name) == 0) {
fvect[i].fptr();
break;
}
}

依赖动态加载的更通用的解决方案:使用 dlopen() API ,像这样:

void *hndl = dlopen(RTLD_SELF, RTLD_LAZY); // try NULL if RTLD_SELF doesn't work
void (*fptr)(void) = dlsym(hndl, buf);
if (fptr != NULL)
fptr();

dlclose(hndl);

关于c - 如何从 STDIN 读取 C 函数并在程序中运行它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19098778/

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