我希望这是微不足道的,我只是没有在教程中找到它。我正在编写“监督”c 代码的 python 代码,也就是我使用来自 python 的 ctypes 运行 c 代码。现在我想'catch' c'printfs'来处理c代码输出的数据。知道如何做到这一点吗?
谢谢
最佳答案
您可以在从 C
代码写入之前拦截 stdout
,然后处理输出值。
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__
但是,将缓冲区传递给 C 代码会更容易和更好,而不是 printf
-ing 输出值,而是将它们写入提供的缓冲区。
或者,更好的是,您可以传递 byref
一个 c_char_p
,在 C
代码中为它分配内存,用输出值然后使用 Python
中的缓冲区。不要忘记释放内存(您应该为 free
函数制作一个 ctypes
包装器)。
关于python - 如何使用 ctypes 在 python 中使用 'catch' c printf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3131977/