问题
I need to read local variables from Python in C/C++. When I try to PyEval_GetLocals
, I get a NULL. This happens although Python is initialized. The following is a minimal example.
#include <iostream>
#include <Python.h>
Py_Initialize();
PyRun_SimpleString("a=5");
PyObject *locals = PyEval_GetLocals();
std::cout<<locals<<std::endl; //prints NULL (prints 0)
Py_Finalize();
In the manual, it says that it returns NULL if no frame is running, but... there's a frame running!
What am I doing wrong?
I'm running this in Debian Jessie.
回答1:
Turns out the right way to access variables in the scope is:
Py_Initialize();
PyObject *main = PyImport_AddModule("__main__");
PyObject *globals = PyModule_GetDict(main);
PyObject *a = PyDict_GetItemString(globals, "a");
std::cout<<globals<<std::endl; //Not NULL
Py_Finalize();
来源:https://stackoverflow.com/questions/40046330/python-c-extension-pyeval-getlocals-returns-null