14.14.1.1 Loading dynamic link libraries

Python 2.5

14.14.1.1 Loading dynamic link libraries

ctypes exports the cdll, and on Windows also windll and oledll objects to load dynamic link libraries.

You load libraries by accessing them as attributes of these objects. cdll loads libraries which export functions using the standard cdecl calling convention, while windll libraries call functions using the stdcall calling convention. oledll also uses the stdcall calling convention, and assumes the functions return a Windows HRESULT error code. The error code is used to automatically raise WindowsError Python exceptions when the function call fails.

Here are some examples for Windows, note that msvcrt is the MS standard C library containing most standard C functions, and uses the cdecl calling convention:

>>> from ctypes import *
>>> print windll.kernel32 # doctest: +WINDOWS
<WinDLL 'kernel32', handle ... at ...>
>>> print cdll.msvcrt # doctest: +WINDOWS
<CDLL 'msvcrt', handle ... at ...>
>>> libc = cdll.msvcrt # doctest: +WINDOWS
>>>

Windows appends the usual '.dll' file suffix automatically.

On Linux, it is required to specify the filename including the extension to load a library, so attribute access does not work. Either the LoadLibrary method of the dll loaders should be used, or you should load the library by creating an instance of CDLL by calling the constructor:

>>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
<CDLL 'libc.so.6', handle ... at ...>
>>> libc = CDLL("libc.so.6")     # doctest: +LINUX
>>> libc                         # doctest: +LINUX
<CDLL 'libc.so.6', handle ... at ...>
>>>

See About this document... for information on suggesting changes.