Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'catch' c printf in python with ctypes?

I hope this is trivial and I just didn't find it in the tutorials. I am writing python code that 'supervises' c code, aka I run the c code with ctypes from python. Now I want to 'catch' the c 'printfs' to process the data that is output by the c code. Any idea how one would do this?

Thanks

like image 416
Framester Avatar asked Nov 05 '22 11:11

Framester


1 Answers

You could intercept stdout before being written to from your C code, then process the output value.

import sys
import StringIO

buffer = StringIO.StringIO()

# redirect stdout to a buffer
sys.stdout = buffer

# call the c code with ctypes
# process the buffer

# recover the old stdout
sys.stdout = sys.__stdout__

However, it would be easier and nicer to pass a buffer to the C code, and instead of printf-ing the output values you would write them in the provided buffer.

Or, better yet, you could pass byref a c_char_p, allocate memory for it inside the C code, update the buffer with the output value then use the buffer in Python. Don't forget to deallocate the memory (you should make a ctypes wrapper for the free function).

like image 127
the_void Avatar answered Nov 11 '22 03:11

the_void