gpt4 book ai didi

python - ctypes 在 Python 解释器中表现异常

转载 作者:太空狗 更新时间:2023-10-30 02:14:10 26 4
gpt4 key购买 nike

我在使用 ctypes 时遇到了一个有趣的问题;虽然它似乎在常规 python 脚本中工作,但当我在带有 printf() 的解释器中使用它时,它会在字符串本身之后打印字符串的长度。演示:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> libc = CDLL("libc.so.6")
>>> libc.printf("Test")
Test4
>>> int = 55
>>> libc.printf("Test %d", int)
Test 557
>>> int = c_int(55)
>>> libc.printf("Test %d", int)
Test 557

有人知道为什么会这样吗?

最佳答案

来自 printf(3) 手册页:

Upon successful return, these functions return the number of characters printed (not including the trailing ’\0’ used to end output to strings).

Python 解释器在您调用 printf() 后显示返回码。由于您的字符串末尾没有换行符 \n ,因此长度会在打印输出后立即打印出来。请注意,这不会发生在脚本中,只有当您以交互方式使用 python 时才会发生。

你可以通过赋值来隐藏它:

ret = libc.printf("Test\n")

关于python - ctypes 在 Python 解释器中表现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3568867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com