Python C extension: Extract parameter from the engine
<p>I would like to use Python to perform Mathematics tests on my functions. A typical program that can gain access to Python is this:</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;Python.h&gt;
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;
}
</code></pre>

<p>My question is: How can I extract the parameters <code>a,b,c,d</code> to <code>PyObject</code>s?</p>

<p><code>PyRun_SimpleString()</code> executes the code in the context of the <code>__main__</code> module. You can retrieve a reference to this module using <code>PyImport_AddModule()</code>, get the globals dictionary from this module and lookup variables:</p>

<pre><code>PyObject *main = PyImport_AddModule("__main__");
PyObject *globals = PyModule_GetDict(main);
PyObject *a = PyDict_GetItemString(globals, "a");
</code></pre>

<p>Instead of using this approach, you might be better off creating a new <code>globals</code> dictionary and using <code>PyRun_String()</code> to execute code in the context of that <code>globals</code> dict:</p>

<pre><code>PyObject *globals = PyDict_New();
PyObject *a = PyRun_String("5", Py_single_input, globals, globals);
</code></pre>

<p>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 <code>__main__</code>.  You can still use variables to store intermediate results, which can then be extracted from <code>globals</code> as above.</p>

python c++ c python-c-extension