Re: [ctypes-users] errno
Brought to you by:
theller
From: Thomas H. <th...@ct...> - 2006-12-13 19:11:34
|
Scott Dial schrieb: > David Remahl wrote: >> On my system, a pointer to the per-thread errno is returned by __error >> (): >> >> In [5]: ctypes.__errno.restype = ctypes.POINTER(ctypes.c_int) >> In [6]: libc.__error().contents >> Out[6]: c_long(0) >> >> This is a platform specific implementation detail. >> > > Ah, thank you, I don't have access to a mac so you solved that part of > the platform specifics that I was missing. To handle win32 and linux, I > propose the following (which I think covers most of your bases): > > import sys > from ctypes import * > > if sys.platform == 'win32': > libc = CDLL('msvcrt.dll') > libc._errno.restype = POINTER(c_int) > def get_errno(): > return libc._errno().contents.value > elif sys.platform in ('linux2', 'freebsd6'): > libc = CDLL('libc.so.6') > libc.__errno_location.restype = POINTER(c_int) > def get_errno(): > return libc.__errno_location().contents.value > elif sys.platform == 'darwin': > libc = CDLL('libc.dylib') > libc.__errno.restype = POINTER(c_int) > def get_errno(): > return libc.__error().contents.value > else: > raise "Ack! I don't know how to get to errno for %s" % sys.platform > I think this code would be a great recipe for the wiki: http://starship.python.net/crew/theller/wiki/ Oh, and the windows code would probably not work too well. The C runtime library is not always 'msvcrt.dll'. However, here is a snippet that can be used to determine the C runtime library which you /should/ use: You should use the same library that Python itself uses. A not very robust but working hack is to scan the executable for the string (better would be to locate the real import table and parse that, but I'm too lazy for this now). """ # Find the C runtime library used by the current interpreter. Should # also work with py2exe'd scripts. import re import sys def find_msvcr(): bytes = open(sys.executable, "rb").read() match = re.search("msvcr([0-9]+|t).dll", bytes, re.IGNORECASE) return match.group(0) if __name__ == "__main__": print find_msvcr() """ Thomas |