OSX和ctypes:CGDisplayBounds()以segfau结尾

2024-10-08 22:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试仅使用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。你知道吗


Tags: fromimportselffieldsdisplayctypesstructureclass

热门问题