从C ++调用Python eval。
问题描述:
我正在尝试使用Python C API在C ++中评估字符串。
我尝试过:
我试过这个:
I'm trying to evaluate a string in C++ using the Python C API.
What I have tried:
I've tried this:
std::string s = "2 + 2 * 4";
PyObject* module = PyImport_AddModule("__main__");
if (module)
{
PyObject* func = PyObject_GetAttrString(module, "eval");
PyObject* returnValue = PyObject_CallObject(func, PyUnicode_FromString(s.c_str()));
std::cout << PyLong_AsLong(returnValue);
}
但不是10,我得-1。
为什么会这样?
But instead of 10, I get -1.
Why is that?
答
PyObject* module = PyImport_AddModule("__main__");
__ main __
不是模块名称,可能存在于数千个模块中。并且 eval
是内置函数,不是任何导入的一部分。尝试使用 __ builtins __
作为模块名称。
__main__
is not a module name and could exist in thousands of modules. And eval
is a builtin function, not part of any import. Try using __builtins__
as the module name.