ctypes Usage Note

eryk sun eryksun at gmail.com
Tue Aug 2 01:17:19 EDT 2016


On Tue, Aug 2, 2016 at 1:41 AM, Lawrence D’Oliveiro
<lawrencedo99 at gmail.com> wrote:
>
> Don’t do that. Do this instead:
>
>     libc = ctypes.cdll.LoadLibrary("libc.so.6")

I recommend using ctypes.CDLL instead. ctypes.cdll is pretty much
pointless on Unix systems (and a potential problem on Windows due to
cached function pointers). It also doesn't allow passing the mode,
handle, and use_errno parameters.

As to the library name, you may instead want to use find_library for
Unix shared libraries:

    >>> ctypes.util.find_library('c')
    'libc.so.6'
    >>> ctypes.util.find_library('python3.5m')
    'libpython3.5m.so.1.0'

It's pretty much pointless on Windows since it just searches PATH for
the given name. It doesn't match how Windows LoadLibrary(Ex) really
works, which allows precise control over exactly what gets searched
via AddDllDirectory, SetDefaultDllDirectories, and activation contexts
(i.e. ActivateActCtx). Plus find_library('c') no longer even works in
3.5+ on Windows (it returns None) because the CRT has been split into
API sets (currently all mapped to ucrtbase.dll, but presumably that
can change with servicing).



More information about the Python-list mailing list