我正在尝试使用仅 ctypes模块捕获屏幕。不幸的是,它以分段错误结束。我认为Argtypes和restypes设置正确。这是崩溃的代码:
#!/usr/bin/env python
# coding: utf-8
from sys import maxsize
from ctypes import POINTER, Structure, c_double, byref, c_int32, c_uint32, c_float, cdll
from ctypes.util import find_library
# For tests only
from Quartz import CGDisplayBounds
CGFloat = c_double if maxsize > 2 ** 32 else c_float
class CGPoint(Structure):
_fields_ = [('x', CGFloat), ('y', CGFloat)]
class CGSize(Structure):
_fields_ = [('width', CGFloat), ('height', CGFloat)]
class CGRect(Structure):
_fields_ = [('origin', CGPoint), ('size', CGSize)]
def __repr__(self):
''' With or without this method, segfault. '''
ret = (self.origin.x, self.origin.y, self.size.width, self.size.height)
return ret.__repr__()
# Library
cgs = cdll.LoadLibrary(find_library('CoreGraphics'))
# Argtypes
cgs.CGGetActiveDisplayList.argtypes = \
[c_uint32, POINTER(c_uint32), POINTER(c_uint32)]
cgs.CGDisplayBounds.argtypes = [c_uint32]
# Restypes
cgs.CGGetActiveDisplayList.restypes = c_int32
cgs.CGDisplayBounds.restypes = CGRect
# Monitors
max_displays = 32
display_count = c_uint32(0)
active_displays = (c_uint32 * max_displays)()
cgs.CGGetActiveDisplayList(max_displays, active_displays, byref(display_count))
for idx in range(display_count.value):
display = active_displays[idx]
# This line works
print(CGDisplayBounds(display))
# SEGFAULT HERE!!!!
rect = cgs.CGDisplayBounds(display)
print(rect)
MacOS X版本10.11.3。
Python版本2.7.10和2.6.9。
答案 0 :(得分:0)
...抱歉,设置重定型时出错。有一个尾随的“s”。
该行:
cgs.CGDisplayBounds.restypes = CGRect
应该是:
cgs.CGDisplayBounds.restype = CGRect