python - 如何使用 ctypes 在 python 中使用 'catch' c printf?

标签 python c printf ctypes

我希望这是微不足道的,我只是没有在教程中找到它。我正在编写“监督”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/

相关文章:

python - pop() empty deque() 逻辑

python - Django:在views.py中使用向后关系

c - TCP_INFO tcpi_lost 和 tcpi_retrans 之间的区别

c - 带有指向字符的指针的情况

c - 在 C 中将 int 转换为 char 时出现段错误

python - Selenium:如何打开空白的 Firefox 浏览器

python - 如果已经检索到最后一个结果,GAE Query 类的 cursor() 方法返回什么?

c - 内联汇编代码错误

c - 如何在C中找到处理char16_t的内置函数?

c - 对输出感到困惑