Python3k ctypes printf

时间:2010-04-14 10:30:48

标签: python printf ctypes

printf返回1而不是“Hello World!”这是理想的结果。

我用Google搜索并认为它是因为序列处理方式的变化。

如何修改代码以打印“Hello World!”?

www.mail-archive.com/python-3000@python.org/msg15119.html

import ctypes

msvcrt=ctypes.cdll.msvcrt
string=b"Hello World!"
msvcrt.printf("%s", string)

1 个答案:

答案 0 :(得分:3)

第一个参数也需要是一个字节字符串:

msvcrt.printf(b"%s", string)

printf的返回值是打印的字符数,在这种情况下应为12。

编辑:

如果您希望返回字符串而不是打印字符串,则可以使用sprintf代替。这很危险,不推荐。

s = ctypes.create_string_buffer(100)   #must be large enough!!
msvcrt.sprintf(s, b'%s', b'Hello World!')
val = s.value

我不知道你为什么要这样做,因为Python有自己的字符串格式。 sprintf是一种危险的方法,因为它容易受到缓冲区溢出的影响。