首页 > 解决方案 > 在 xlib 上使用 ctypes 时出现分段错误

问题描述

我正在尝试从 xlib 屏幕保护程序中获取空闲时间

我尝试调试它,错误开始在该行之后发生

dpy = xlib.XOpenDisplay(os.environ['DISPLAY'].encode('ascii'))

这是我的代码

class XScreenSaverInfo( ctypes.Structure):
    """ typedef struct { ... } XScreenSaverInfo; """
    _fields_ = [('window',      ctypes.c_ulong), # screen saver window
              ('state',       ctypes.c_int),   # off,on,disabled
              ('kind',        ctypes.c_int),   # blanked,internal,external
              ('since',       ctypes.c_ulong), # milliseconds
              ('idle',        ctypes.c_ulong), # milliseconds
              ('event_mask',  ctypes.c_ulong)] # events


xlib = ctypes.cdll.LoadLibrary('libX11.so')
dpy = xlib.XOpenDisplay(os.environ['DISPLAY'].encode('ascii'))
root = xlib.XDefaultRootWindow(dpy)
xss = ctypes.cdll.LoadLibrary( 'libXss.so')
xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo)
xss_info = xss.XScreenSaverAllocInfo()
xss.XScreenSaverQueryInfo( dpy, root, xss_info)
print("Idle time in milliseconds: %d") % xss_info.contents.idle

我得到一个Segmentation fault (core dumped)错误。请帮忙:)

标签: python-3.xctypesxlib

解决方案


错误是因为未指定argtypes (和restype ),如[Python 3.Docs]: ctypes - Specifying the required argument types (function prototypes)中所述。在这种情况下发生的事情有很多例子,这里有两个:

在调用它之前为每个函数声明它们:

xlib.XOpenDisplay.argtypes = [ctypes.c_char_p]
xlib.XOpenDisplay.restype = ctypes.c_void_p  # Actually, it's a Display pointer, but since the Display structure definition is not known (nor do we care about it), make it a void pointer

xlib.XDefaultRootWindow.argtypes = [ctypes.c_void_p]
xlib.XDefaultRootWindow.restype = ctypes.c_uint32

xss.XScreenSaverQueryInfo.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.POINTER(XScreenSaverInfo)]
xss.XScreenSaverQueryInfo.restype = ctypes.c_int

推荐阅读