Python中wrapped c函数出错后获取errno

2024-06-07 05:37:03 发布

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

我正在学习如何在出现错误后使用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。我现在不知道如何访问errno。如果我尝试ctypes.get_errno(),则返回0。如果我试图调用c_lib.errno(),这将导致一个segmentation error,因此这也不起作用。有没有办法可以检索errno?在


Tags: andtoaddgetlib错误ableerror
1条回答
网友
1楼 · 发布于 2024-06-07 05:37:03

您必须从构建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是enoint(没有这样的文件或目录),因此它被设置为正确的。在

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

相关问题 更多 >