是否有等效于 eval("function(arg1, arg2)") 的 C/C++?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11078267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:49:26  来源:igfitidea点击:

Is there C/C++ equivalent of eval("function(arg1, arg2)")?

c++eval

提问by Dipesh KC

it need a way to call function whose name is stored in a string similar to eval. Can you help?

它需要一种方法来调用名称存储在类似于 eval 的字符串中的函数。你能帮我吗?

回答by Hauleth

C++ doesn't have reflection so you must hack it, i. e.:

C++ 没有反射,所以你必须破解它,即:

#include <iostream>
#include <map>
#include <string>
#include <functional>

void foo() { std::cout << "foo()"; }
void boo() { std::cout << "boo()"; }
void too() { std::cout << "too()"; }
void goo() { std::cout << "goo()"; }

int main() {
  std::map<std::string, std::function<void()>> functions;
  functions["foo"] = foo;
  functions["boo"] = boo;
  functions["too"] = too;
  functions["goo"] = goo;

  std::string func;
  std::cin >> func;
  if (functions.find(func) != functions.end()) {
    functions[func]();
  }
  return 0;
}

回答by Luchian Grigore

There are at least 2 alternatives:

至少有两种选择:

  • The command pattern.
  • On windows, you can use GetProcAddressto get a callback by name, and dlopen+ dlsymon *nix.
  • 命令模式
  • 在 Windows 上,您可以使用GetProcAddress按名称获取回调,并在 *nix 上使用dlopen+ dlsym

回答by DavidA

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;


double eval( string expression );


int main( int argc, char *argv[] )
{
    string expression = "";
    for ( int i = 1; i < argc; i++ )
    {
       expression = expression + argv[i];
    }
    cout << "Expression [ " << expression << " ] = " << endl;

    eval( expression );
}


double eval( string expression )
{
    string program = "";
    program = program + "#include <cmath>\n";
    program = program + "#include <iostream>\n";
    program = program + "using namespace std;\n";
    program = program + "int main()\n";
    program = program + "{\n";
    program = program + "   cout << ";
    program = program + expression;
    program = program + " << endl;\n";
    program = program + "}";


    ofstream out( "abc.cpp" );
    out << program;
    out.close();

    system( "g++ -o abc.exe abc.cpp" );
    system( "abc" );
}

回答by Tommy Andersen

You could try to adopt an existing scripting engine, expose the functions you like to this and then use this to evaluate your statements. One such enging could be the V8 engine: https://developers.google.com/v8/introbut there are many alternatives and different languages to choose from.

您可以尝试采用现有的脚本引擎,将您喜欢的函数公开给它,然后使用它来评估您的语句。V8 引擎就是其中之一:https: //developers.google.com/v8/intro,但有许多替代方案和不同的语言可供选择。

Here are some examples:

这里有些例子:

回答by YongHao Hu

Except using the function map in the program and hack it on the Makefile, you can access it through ELF.

除了在程序中使用函数映射并在Makefile上hack,你可以通过ELF访问它。

I think this method is better as it did not need to write duplicate code and compile it every time on different machine.

我认为这种方法更好,因为它不需要编写重复的代码并每次在不同的机器上编译它。

Here is my demo C/C++ equivalent of eval(“function(arg1, arg2)”)

这是我的演示C/C++ 等效于 eval(“function(arg1, arg2)”)

#include<stdio.h>
#include<stdlib.h>
#include<elf.h>
#include<libelf.h>
#include<unistd.h>
#include<fcntl.h>
#include<gelf.h>
#include<string.h>

void my_fun()
{
    int a = 19;
    printf("my_fun is excute, a is %d \n", a);
}

void my_fun2()
{
    printf("my_fun2 is excute\n");
    return;
}

void my_fun3()
{
    return;
}

void excute_fun(char *program_name, char *function_name)
{
    int i, count;
    Elf32_Ehdr *ehdr;
    GElf_Shdr   shdr;
    Elf *elf;
    Elf_Scn *scn = NULL;
    Elf_Data *data;
    int flag = 0;
    int fd = open(program_name, O_RDONLY);
    if(fd < 0) {
        perror("open\n");
        exit(1);
    }
    if(elf_version(EV_CURRENT) == EV_NONE) {
        perror("elf_version == EV_NONE");
        exit(1);
    }
    elf = elf_begin(fd, ELF_C_READ, (Elf *) NULL);
    if(!elf) {
        perror("elf error\n");
        exit(1);
    }
    /* Elf32_Off e_shoff; */
    /* if ((ehdr = elf32_getehdr(elf)) != 0) { */
    /*     e_shoff = ehdr->e_shoff; */
    /* } */
    /* scn = elf_getscn(elf, 0); */
    /* printf("e_shoff is %u\n", e_shoff); */
    /* scn += e_shoff; */
    while ((scn = elf_nextscn(elf, scn)) != NULL) {
        gelf_getshdr(scn, &shdr);
        if (shdr.sh_type == SHT_SYMTAB) {
            /* found a symbol table. */
            break;
        }
    }
    data = elf_getdata(scn, NULL);
    if(!shdr.sh_entsize)
        count = 0;
    else
        count = shdr.sh_size / shdr.sh_entsize;
    for (i = 0; i < count; ++i) {
        GElf_Sym sym;
        gelf_getsym(data, i, &sym);
        char *sym_name = elf_strptr(elf, shdr.sh_link, sym.st_name);
        if(sym_name != NULL && sym_name[0] != '_' && sym_name[0] != '##代码##' && sym_name[0] != ' ' && sym.st_value != 0)
        {
            /* printf("sym_name is %s\n", sym_name); */
            /* printf("%s = %X\n", elf_strptr(elf, shdr.sh_link, sym.st_name), sym.st_value); */
            if(!strcmp(sym_name, function_name)) {
                void (*fun)(void) = (void*)sym.st_value;
                (*fun)();
                flag = 1;
            }
        }
    }
    if(!flag)
        printf("can not find this function\n");

    elf_end(elf);
    close(fd);
}

int main(int argc, char *argv[])
{
    char *input = (char*)malloc(100);
    for(;;) {
        printf("input function_name to excute: ");
        scanf("%s", input);
        excute_fun(argv[0], input);
        memset(input, 0, sizeof(input));
        printf("\n");
    }
    free(input);
    return 0;
}

This implementation is based on Example of Printing the ELF Symbol Table

此实现基于打印 ELF 符号表的示例