Python3k ctypes printf

标签 python printf ctypes

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

我用谷歌搜索了一下,认为这是因为序列处理方式的变化。

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

www.mail-archive.com/[email protected]/msg15119.html

import ctypes

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

最佳答案

第一个参数也必须是字节字符串:

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 是一种危险的方法,因为它容易发生缓冲区溢出。

关于Python3k ctypes printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2636597/

相关文章:

python - keras 忽略 $HOME/.keras/keras.json 文件中的值

python - Nicing 正在运行的 python 进程?

python - 使用 Python 调用 DLL 函数时出现 ctypes.ArgumentError

c - 在 C 中理解和编写 wchar_t

python - 找不到 ctypes 错误 AttributeError 符号,OS X 10.7.5

python ctype递归结构

python - 一个对 python 装饰器感到困惑的人

python - temp.readline() 为空?

linux - 像 ls、pwd、find 这样的 Linux 命令源代码的输出部分是否像 return 或 printf 一样定义?

c - 在for循环中声明int数组并在C中更改其元素