On Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] 为什么 GetDC() 的返回值符号扩展?
from ctypes import *
hDC1 = windll.user32.GetDC(None)
print hex(hDC1), hDC1, type(hDC1)
hDC2 = windll.user32.GetDC(None)
print hex(hDC2), hDC2, type(hDC2)
这有时会导致负返回值:
0x6a0116c1 1778456257 <type 'int'> # OK
-0x53fed994 -1409210772 <type 'int'> # Why negative?
我相信 GetDC() 返回的 HANDLES 总是适合 32 位(即使在 x64 上),但是如果设置了 32 位值中的最高位(大约 50%),cython 似乎是对后者 GetDC() 返回值的符号扩展的时间)。稍后,在后续 GDI 调用中尝试使用此负值 HANDLE 失败。
这似乎是一个重大问题,我不明白我错过了什么。
编辑:
这篇文章似乎触及了问题的根源:Why does setting ctypes dll.function.restype=c_void_p return long?
在我们的例子中,添加:
class c_void_p(c_void_p):
pass
到为每个 GDI 库函数定义 restype 的模块开头似乎已经解决了这个问题。
请您参考如下方法:
ctypes 假定函数返回一个带符号的 int,除非您另有说明。将函数 restype 设置为无符号值:
from ctypes import *
windll.user32.GetDC.restype = c_void_p
hDC1 = windll.user32.GetDC(None)
ctypes 对参数和返回值一无所知,只知道函数的入口点。它需要猜测,但允许您使用 argtypes 和 restype 覆盖。
