在Python 3.x下将字符串传递给ctypes函数

Edw*_*ard 14 python ctypes python-3.x

from ctypes import *
msvcrt = cdll.msvcrt
message_string = "Hello world!\n"
msvcrt.printf("Testing: %s", message_string)
Run Code Online (Sandbox Code Playgroud)

我正在阅读一本关于Ctypes和Python的书,但示例代码不起作用.

可能是因为这本书是为python 2而写的,而我是在Python 3上?

printf只打印第一个字母.

Dun*_*can 21

C printf函数期望字节串.在Python 3中,所有字符串都是unicode,因此您必须编码为字节:

>>> msvcrt.printf("Testing: %s".encode('ascii'), message_string.encode('ascii'))
Testing: Hello world!
22
Run Code Online (Sandbox Code Playgroud)

如果您有任何非ascii字符,则编码到相关的Windows代码页.

  • 谢谢!有效.我几乎无法在任何地方找到答案.先生,我应该如何重命名标题以方便未来的用户? (2认同)

Dou*_*oug 5

bleh,使用 "".encode('ascii') 是丑陋的。您通常可以通过这样做来逃脱:

TTF_OpenFont(b"assets/droid.ttf", 10)
             ^^
Run Code Online (Sandbox Code Playgroud)

请注意字符串的 'b' 类型。这也可以移植到 python 2.7。