Importing module from string in the Python C API
<p>Importing Python modules from files is relatively easy with the Python C API with <code>pyImport_Import()</code> however I would need to use functions stored in strings. Is there a way to import python modules from strings (to clarify: there is no file; the code is in a string) or will I have to save the strings as temp files?</p>

<p><s>If my understanding is correct, you could use <a href="https://docs.python.org/3/c-api/import.html#c.PyImport_ImportModule" rel="nofollow"><code>PyImport_ImportModule</code></a> which takes a <code>const char* name</code> to specify the module to be imported.</s></p>

<p>Since my understanding was incorrect:</p>

<p>It would generally be better to dump the contents to a <code>.py</code> file and then execute them with <a href="https://docs.python.org/3/c-api/veryhigh.html?highlight=compile#c.PyRun_File" rel="nofollow"><code>PyRun_File</code></a> but, if you have strings and want to work with those <em>I guess</em> you could use <a href="https://docs.python.org/3/c-api/veryhigh.html?highlight=compile#c.Py_CompileString" rel="nofollow"><code>Py_CompileString</code></a> to compile it to a code object and then feed it to <a href="https://docs.python.org/3/c-api/veryhigh.html?highlight=compile#c.PyEval_EvalCode" rel="nofollow"><code>PyEval_EvalCode</code></a> for evaluation.</p>

python c python-c-api cross-language