使用ctypes时,islower的结果不正确

Lor*_*Aro 4 c python ctypes

>>> from ctypes import *
>>> import ctypes.util
>>> libc = CDLL("libc.so.6")
>>> libc.printf("%c\n", 104)
h
2
>>> libc.islower(104) # Works fine
512
>>> libc.islower.restype = c_bool # But when i do this...
>>> libc.islower(104)
False
>>> c_bool(512)
c_bool(True)
Run Code Online (Sandbox Code Playgroud)

就个人而言,我认为'h'是小写的..

这是ctypes中的错误,还是我做错了什么?

Mat*_*lia 7

restype不仅仅是告诉Python输出类型,但最重要的是,告诉我们期望的C类型,以及如何编组它.islower返回一个int,通常为4个字节宽; 如果你说它返回一个bool(通常是1个字节)你就会打破封送代码的期望.

这次你得到了一个不正确的结果(可能是因为在你的平台上返回代码进入寄存器,所以它只是占用它的低8位),在另一个平台上或另一种类型,这可能很容易打破堆栈,因此崩溃你的过程.

所以:不要那样做.始终遵守C API类型并调用进行转换.