问题
I would like to use Python to perform Mathematics tests on my functions. A typical program that can gain access to Python is this:
#include <iostream>
#include <string>
#include <Python.h>
int RunTests()
{
Py_Initialize();
PyRun_SimpleString("a=5");
PyRun_SimpleString("b='Hello'");
PyRun_SimpleString("c=1+2j");
PyRun_SimpleString("d=[1,3,5,7,9]");
//question here
Py_Finalize();
return 0;
}
My question is: How can I extract the parameters a,b,c,d
to PyObject
s?
回答1:
PyRun_SimpleString()
executes the code in the context of the __main__
module. You can retrieve a reference to this module using PyImport_AddModule()
, get the globals dictionary from this module and lookup variables:
PyObject *main = PyImport_AddModule("__main__");
PyObject *globals = PyModule_GetDict(main);
PyObject *a = PyDict_GetItemString(globals, "a");
Instead of using this approach, you might be better off creating a new globals
dictionary and using PyRun_String()
to execute code in the context of that globals
dict:
PyObject *globals = PyDict_New();
PyObject *a = PyRun_String("5", Py_single_input, globals, globals);
This way, you don't need to first store the result of your expression in some variable and then extract it from the global scope of __main__
. You can still use variables to store intermediate results, which can then be extracted from globals
as above.
来源:https://stackoverflow.com/questions/40041498/python-c-extension-extract-parameter-from-the-engine