Is There C/C++ Equivalent of Eval("Function(Arg1, Arg2)")

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

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

#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;
}

Making a function call to a function whose name is inside a string - C++

This would be the easiest solution, but I think your problem consists of several such calls?

std::string line = "The king's name is getKingName()";
if (line.find("getKingName()") != std::string::npos) {
King name = getKingName();
}

Strange closure behaviors using eval() -- why?

eval is recognized specially by the compiler. This is what allows it to introduce and access local variable bindings. But the compiler can only recognize it when it's used by its normal name. When it sees a call to fn_, it can't tell that this variable is equivalent to eval, so it compiles it as a normal function call.

For lots of details about this, see

javascript eval considered crazy

Passing arguments to python eval()

You have three options, roughly speaking. You can keep going with eval(),you could actually write the string as a file and execute it with subprocess.Popen(), or you could call the function something besides main() and call it after defining it with eval().

exec() way:

In the string you want to exec

main(#REPLACE_THIS#)

Function to evaluate

import string
def exec_with_args(exec_string,args):
arg_string=reduce(lambda x,y:x+','+y,args)
exec_string.replace("#REPLACE_THIS#", arg_string)

Subprocess way:

 import subprocess
#Write string to a file
exec_file=open("file_to_execute","w")
exec_file.write(string_to_execute)
#Run the python file as a separate process
output=subprocess.Popen(["python","file_to_execute"].extend(argument_list),
stdout=subprocess.PIPE)

Function Definition Way

In the string you want to exec

def function_name(*args):
import sys

def a(x,y):
return x

def b(y):
return y

def inner_main(x,y):
lambda x,y: a(b(y),a(x,y))

inner_main(*args)

Outer code

exec(program_string)
function_name(*args)


Related Topics



Leave a reply



Submit