Pass Python object directly to C++ program without using subprocess
<p>I have a C++ program that, through the terminal, takes a text file as input and produces another text file. I'm executing this program from a Python script which first produces said text string, stores it to a file, runs the C++ program as a subprocess with the created file as input and parses the output text file back into a Python object.</p>

<p>Is it possible to do this without using a subprocess call? In other words: is it possible to avoid the reading and writing and just run the C++ program inside the Python environment with the text-string as input and then capture the output, again inside the Python environment?</p>

<p>For code I refer to the function <code>community_detection_multiplex</code> in <a href="https://github.com/ulfaslak/InfomapSensibleDTU/blob/master/preproc.ipynb" rel="nofollow">this IPython notebook</a>.</p>

<p>You can use <a href="https://docs.python.org/3.5/library/ctypes.html" rel="nofollow">ctypes</a>.<br>
It requires the C++ function to be wrapped with <code>extern "c"</code> and compiled as C code.</p>

<p>Say your C++ function looks like that:</p>

<pre><code>char* changeString(char* someString)
{
    // do something with your string
    return someString;
}
</code></pre>

<p>You can call it from python like that:</p>

<pre><code>import ctypes as ct

yourString = "somestring"
yourDLL = ct.CDLL("path/to/dll") # assign the dll to a variable
cppFunc = yourDLL.changeString # assign the cpp func to a variable
cppFunc.restype = ct.c_char_p # set the return type to a string
returnedString = cppfunc(yourString.encode('ascii')).decode()
</code></pre>

<p>Now <code>returnedString</code> will have the processed string. </p>

python c++