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



出现错误后,我正在学习如何使用 Python 的ctypes' and am able to wrap and call a function, but I can't figure out how to get theerrno 包装 c 函数。对于此示例,我正在包装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。我现在不知道如何访问errno。如果我尝试ctypes.get_errno(),这只会返回0。如果我尝试调用c_lib.errno(),这会导致segmentation error,所以这也不起作用。有没有办法检索errno

你必须从构建 Python 时使用的同一个 CRT 库中获取 errno。 对于Windows上的Python 3.7也是如此。 我没有方便尝试的Linux,所以希望这能让你朝着正确的方向前进。

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

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

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

最新更新