代码之家  ›  专栏  ›  技术社区  ›  TheStrangeQuark

在Python中包装的c函数出错后获取errno

  •  0
  • TheStrangeQuark  · 技术社区  · 6 年前

    我正在学习如何使用Python的 ctypes' and am able to wrap and call a function, but I can't figure out how to get the errno`出错后。对于这个例子,我正在包装 inotify_add_watch . 这不是完整的代码,只是会导致错误的示例:

    import ctypes
    
    c_lib = ctypes.cdll.LoadLibrary('libc.so.6')
    
    inotify_add = c_lib.inotify_add_watch
    inotify_add.argtypes = (ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32)
    inotify_add.restype = ctypes.c_int
    
    # This will cause an EBADF error
    inotify_add(32, b'/tmp', 1)  # returns -1
    

    -1 它确实如此,但它也会凝固 errno 适当地。我不知道怎么进入 厄尔诺 ctypes.get_errno() ,这才回来 0 . 如果我想打电话 c_lib.errno() segmentation error ,所以这也不起作用。有没有办法让我找回 厄尔诺 ?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Mark Tolonen    6 年前

    必须从构建Python时使用的同一个CRT库中获取errno。对于Windows上的python3.7也是如此。我手头没有Linux可供尝试,所以希望这能让您找到正确的方向。

    >>> dll = CDLL('ucrtbase',use_errno=True)
    >>> get_errno()
    0
    >>> dll._access(b'nonexisting',0)
    -1
    >>> get_errno()
    2
    

    Errno 2是enent(没有这样的文件或目录),所以它被设置并看起来是正确的。

    不同的CRT库具有不同的 errno 因此Python无法正确捕获它以用于 set_errno()/get_errno() .