Re: [ctypes-users] errno
Brought to you by:
theller
From: <jU...@ar...> - 2006-12-13 19:42:00
|
Thomas Heller schrieb: > Scott Dial schrieb: > =20 >> David Remahl wrote: >> =20 >>> On my system, a pointer to the per-thread errno is returned by __erro= r=20 >>> (): >>> >>> In [5]: ctypes.__errno.restype =3D ctypes.POINTER(ctypes.c_int) >>> In [6]: libc.__error().contents >>> Out[6]: c_long(0) >>> >>> This is a platform specific implementation detail. >>> >>> =20 >> Ah, thank you, I don't have access to a mac so you solved that part of= =20 >> the platform specifics that I was missing. To handle win32 and linux, = I=20 >> propose the following (which I think covers most of your bases): >> >> import sys >> from ctypes import * >> >> if sys.platform =3D=3D 'win32': >> libc =3D CDLL('msvcrt.dll') >> libc._errno.restype =3D POINTER(c_int) >> def get_errno(): >> return libc._errno().contents.value >> elif sys.platform in ('linux2', 'freebsd6'): >> libc =3D CDLL('libc.so.6') >> libc.__errno_location.restype =3D POINTER(c_int) >> def get_errno(): >> return libc.__errno_location().contents.value >> elif sys.platform =3D=3D 'darwin': >> libc =3D CDLL('libc.dylib') >> libc.__errno.restype =3D 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.platfo= rm >> >> =20 > 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 runti= me library > is not always 'msvcrt.dll'. However, here is a snippet that can be use= d to determine > the C runtime library which you /should/ use: You should use the same l= ibrary 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 par= se 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 =3D open(sys.executable, "rb").read() > match =3D re.search("msvcr([0-9]+|t).dll", bytes, re.IGNORECASE) > return match.group(0) > > if __name__ =3D=3D "__main__": > print find_msvcr() > """ > > Thomas > > =20 This is certainly off topic. But the if sys.paltform =3D=3D "whatever" part reminds me on some code I wished I had in hands, many times before. if sys.platform =3D=3D 'win32': def alloc_chunk_of_shared_mem(): pass def create_global_lock(): pass (...) not only for the win32 part, but for all platforms. J=FCrgen |