发生错误后,我正在学习如何使用Python的ctypes' and am able to wrap and call a function, but I can't figure out how to get the
errno`包装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
?
答案 0 :(得分:2)
您必须从构建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()
。