Introduction
Suppose I have this C code:
#include <stdio.h>
void printout() {
puts("Hello");
}
void printhere(FILE* f) {
fputs("Hello\n", f);
}
What I am compiling as a shared object (DLL): gcc -Wall -std=c99 -fPIC -shared example.c -o example.so
And then I import it into Python 3.x, running in Jupyter or IPython notepad :
import ctypes
example = ctypes.cdll.LoadLibrary('./example.so')
printout = example.printout
printout.argtypes = ()
printout.restype = None
printhere = example.printhere
printhere.argtypes = (ctypes.c_void_p)
printhere.restype = None
Question
How can I execute functions ctypes printout()and printhere()C (via ctypes) and get print output in Jupyter / IPython notepad?
If possible, I want to avoid writing more C code. I would prefer a purely Python solution.
I would also prefer to avoid writing to a temporary file. However, writing to a pipe / socket may be reasonable.
Expected Status, Current Status
If I type the following code in one cell of a laptop:
print("Hi")
printout()
printhere(something)
print("Bye")
I want to get this output:
Hi
Hello
Hello
Bye
Python . C , .
, Jupyter/IPython sys.stdout :
import sys
sys.stdout
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
<IPython.kernel.zmq.iostream.OutStream at 0x7f39c6930438>
<ipykernel.iostream.OutStream at 0x7f6dc8f2de80>
sys.stdout.fileno()
1
UnsupportedOperation: IOStream has no fileno.
:
, . , Python, C .
?
, C open_memstream() FILE* stdout, , stdout .
fileno() , open_memstream(), , .
freopen(), API .
Python tempfile.SpooledTemporaryFile(), . , fileno().
-o. , . ( , , .)
os.pipe(), .