The Quantum Physicist The Quantum Physicist - 1 month ago 19
C Question

Python C extension: Extract parameter from the engine

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?

Answer

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.