PageRenderTime 1580ms CodeModel.GetById 181ms app.highlight 1065ms RepoModel.GetById 197ms app.codeStats 1ms

/Doc/library/ctypes.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 2482 lines | 1769 code | 713 blank | 0 comment | 0 complexity | 6bd179d674b269a799687de33ef31e0a MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1
   2:mod:`ctypes` --- A foreign function library for Python.
   3========================================================
   4
   5.. module:: ctypes
   6   :synopsis: A foreign function library for Python.
   7.. moduleauthor:: Thomas Heller <theller@python.net>
   8
   9
  10.. versionadded:: 2.5
  11
  12``ctypes`` is a foreign function library for Python.  It provides C compatible
  13data types, and allows calling functions in DLLs or shared libraries.  It can be
  14used to wrap these libraries in pure Python.
  15
  16
  17.. _ctypes-ctypes-tutorial:
  18
  19ctypes tutorial
  20---------------
  21
  22Note: The code samples in this tutorial use ``doctest`` to make sure that they
  23actually work.  Since some code samples behave differently under Linux, Windows,
  24or Mac OS X, they contain doctest directives in comments.
  25
  26Note: Some code samples reference the ctypes :class:`c_int` type. This type is
  27an alias for the :class:`c_long` type on 32-bit systems.  So, you should not be
  28confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
  29they are actually the same type.
  30
  31
  32.. _ctypes-loading-dynamic-link-libraries:
  33
  34Loading dynamic link libraries
  35^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  36
  37``ctypes`` exports the *cdll*, and on Windows *windll* and *oledll*
  38objects, for loading dynamic link libraries.
  39
  40You load libraries by accessing them as attributes of these objects. *cdll*
  41loads libraries which export functions using the standard ``cdecl`` calling
  42convention, while *windll* libraries call functions using the ``stdcall``
  43calling convention. *oledll* also uses the ``stdcall`` calling convention, and
  44assumes the functions return a Windows :class:`HRESULT` error code. The error
  45code is used to automatically raise a :class:`WindowsError` exception when
  46the function call fails.
  47
  48Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
  49library containing most standard C functions, and uses the cdecl calling
  50convention::
  51
  52   >>> from ctypes import *
  53   >>> print windll.kernel32 # doctest: +WINDOWS
  54   <WinDLL 'kernel32', handle ... at ...>
  55   >>> print cdll.msvcrt # doctest: +WINDOWS
  56   <CDLL 'msvcrt', handle ... at ...>
  57   >>> libc = cdll.msvcrt # doctest: +WINDOWS
  58   >>>
  59
  60Windows appends the usual ``.dll`` file suffix automatically.
  61
  62On Linux, it is required to specify the filename *including* the extension to
  63load a library, so attribute access can not be used to load libraries. Either the
  64:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
  65the library by creating an instance of CDLL by calling the constructor::
  66
  67   >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
  68   <CDLL 'libc.so.6', handle ... at ...>
  69   >>> libc = CDLL("libc.so.6")     # doctest: +LINUX
  70   >>> libc                         # doctest: +LINUX
  71   <CDLL 'libc.so.6', handle ... at ...>
  72   >>>
  73
  74.. XXX Add section for Mac OS X.
  75
  76
  77.. _ctypes-accessing-functions-from-loaded-dlls:
  78
  79Accessing functions from loaded dlls
  80^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  81
  82Functions are accessed as attributes of dll objects::
  83
  84   >>> from ctypes import *
  85   >>> libc.printf
  86   <_FuncPtr object at 0x...>
  87   >>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
  88   <_FuncPtr object at 0x...>
  89   >>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS
  90   Traceback (most recent call last):
  91     File "<stdin>", line 1, in ?
  92     File "ctypes.py", line 239, in __getattr__
  93       func = _StdcallFuncPtr(name, self)
  94   AttributeError: function 'MyOwnFunction' not found
  95   >>>
  96
  97Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
  98as well as UNICODE versions of a function. The UNICODE version is exported with
  99an ``W`` appended to the name, while the ANSI version is exported with an ``A``
 100appended to the name. The win32 ``GetModuleHandle`` function, which returns a
 101*module handle* for a given module name, has the following C prototype, and a
 102macro is used to expose one of them as ``GetModuleHandle`` depending on whether
 103UNICODE is defined or not::
 104
 105   /* ANSI version */
 106   HMODULE GetModuleHandleA(LPCSTR lpModuleName);
 107   /* UNICODE version */
 108   HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
 109
 110*windll* does not try to select one of them by magic, you must access the
 111version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
 112explicitly, and then call it with strings or unicode strings
 113respectively.
 114
 115Sometimes, dlls export functions with names which aren't valid Python
 116identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use ``getattr``
 117to retrieve the function::
 118
 119   >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
 120   <_FuncPtr object at 0x...>
 121   >>>
 122
 123On Windows, some dlls export functions not by name but by ordinal. These
 124functions can be accessed by indexing the dll object with the ordinal number::
 125
 126   >>> cdll.kernel32[1] # doctest: +WINDOWS
 127   <_FuncPtr object at 0x...>
 128   >>> cdll.kernel32[0] # doctest: +WINDOWS
 129   Traceback (most recent call last):
 130     File "<stdin>", line 1, in ?
 131     File "ctypes.py", line 310, in __getitem__
 132       func = _StdcallFuncPtr(name, self)
 133   AttributeError: function ordinal 0 not found
 134   >>>
 135
 136
 137.. _ctypes-calling-functions:
 138
 139Calling functions
 140^^^^^^^^^^^^^^^^^
 141
 142You can call these functions like any other Python callable. This example uses
 143the ``time()`` function, which returns system time in seconds since the Unix
 144epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
 145handle.
 146
 147This example calls both functions with a NULL pointer (``None`` should be used
 148as the NULL pointer)::
 149
 150   >>> print libc.time(None) # doctest: +SKIP
 151   1150640792
 152   >>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
 153   0x1d000000
 154   >>>
 155
 156``ctypes`` tries to protect you from calling functions with the wrong number of
 157arguments or the wrong calling convention.  Unfortunately this only works on
 158Windows.  It does this by examining the stack after the function returns, so
 159although an error is raised the function *has* been called::
 160
 161   >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
 162   Traceback (most recent call last):
 163     File "<stdin>", line 1, in ?
 164   ValueError: Procedure probably called with not enough arguments (4 bytes missing)
 165   >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
 166   Traceback (most recent call last):
 167     File "<stdin>", line 1, in ?
 168   ValueError: Procedure probably called with too many arguments (4 bytes in excess)
 169   >>>
 170
 171The same exception is raised when you call an ``stdcall`` function with the
 172``cdecl`` calling convention, or vice versa::
 173
 174   >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
 175   Traceback (most recent call last):
 176     File "<stdin>", line 1, in ?
 177   ValueError: Procedure probably called with not enough arguments (4 bytes missing)
 178   >>>
 179
 180   >>> windll.msvcrt.printf("spam") # doctest: +WINDOWS
 181   Traceback (most recent call last):
 182     File "<stdin>", line 1, in ?
 183   ValueError: Procedure probably called with too many arguments (4 bytes in excess)
 184   >>>
 185
 186To find out the correct calling convention you have to look into the C header
 187file or the documentation for the function you want to call.
 188
 189On Windows, ``ctypes`` uses win32 structured exception handling to prevent
 190crashes from general protection faults when functions are called with invalid
 191argument values::
 192
 193   >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
 194   Traceback (most recent call last):
 195     File "<stdin>", line 1, in ?
 196   WindowsError: exception: access violation reading 0x00000020
 197   >>>
 198
 199There are, however, enough ways to crash Python with ``ctypes``, so you should
 200be careful anyway.
 201
 202``None``, integers, longs, byte strings and unicode strings are the only native
 203Python objects that can directly be used as parameters in these function calls.
 204``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are
 205passed as pointer to the memory block that contains their data (``char *`` or
 206``wchar_t *``).  Python integers and Python longs are passed as the platforms
 207default C ``int`` type, their value is masked to fit into the C type.
 208
 209Before we move on calling functions with other parameter types, we have to learn
 210more about ``ctypes`` data types.
 211
 212
 213.. _ctypes-fundamental-data-types:
 214
 215Fundamental data types
 216^^^^^^^^^^^^^^^^^^^^^^
 217
 218``ctypes`` defines a number of primitive C compatible data types :
 219
 220   +----------------------+--------------------------------+----------------------------+
 221   | ctypes type          | C type                         | Python type                |
 222   +======================+================================+============================+
 223   | :class:`c_char`      | ``char``                       | 1-character string         |
 224   +----------------------+--------------------------------+----------------------------+
 225   | :class:`c_wchar`     | ``wchar_t``                    | 1-character unicode string |
 226   +----------------------+--------------------------------+----------------------------+
 227   | :class:`c_byte`      | ``char``                       | int/long                   |
 228   +----------------------+--------------------------------+----------------------------+
 229   | :class:`c_ubyte`     | ``unsigned char``              | int/long                   |
 230   +----------------------+--------------------------------+----------------------------+
 231   | :class:`c_short`     | ``short``                      | int/long                   |
 232   +----------------------+--------------------------------+----------------------------+
 233   | :class:`c_ushort`    | ``unsigned short``             | int/long                   |
 234   +----------------------+--------------------------------+----------------------------+
 235   | :class:`c_int`       | ``int``                        | int/long                   |
 236   +----------------------+--------------------------------+----------------------------+
 237   | :class:`c_uint`      | ``unsigned int``               | int/long                   |
 238   +----------------------+--------------------------------+----------------------------+
 239   | :class:`c_long`      | ``long``                       | int/long                   |
 240   +----------------------+--------------------------------+----------------------------+
 241   | :class:`c_ulong`     | ``unsigned long``              | int/long                   |
 242   +----------------------+--------------------------------+----------------------------+
 243   | :class:`c_longlong`  | ``__int64`` or ``long long``   | int/long                   |
 244   +----------------------+--------------------------------+----------------------------+
 245   | :class:`c_ulonglong` | ``unsigned __int64`` or        | int/long                   |
 246   |                      | ``unsigned long long``         |                            |
 247   +----------------------+--------------------------------+----------------------------+
 248   | :class:`c_float`     | ``float``                      | float                      |
 249   +----------------------+--------------------------------+----------------------------+
 250   | :class:`c_double`    | ``double``                     | float                      |
 251   +----------------------+--------------------------------+----------------------------+
 252   | :class:`c_longdouble`| ``long double``                | float                      |
 253   +----------------------+--------------------------------+----------------------------+
 254   | :class:`c_char_p`    | ``char *`` (NUL terminated)    | string or ``None``         |
 255   +----------------------+--------------------------------+----------------------------+
 256   | :class:`c_wchar_p`   | ``wchar_t *`` (NUL terminated) | unicode or ``None``        |
 257   +----------------------+--------------------------------+----------------------------+
 258   | :class:`c_void_p`    | ``void *``                     | int/long or ``None``       |
 259   +----------------------+--------------------------------+----------------------------+
 260
 261
 262All these types can be created by calling them with an optional initializer of
 263the correct type and value::
 264
 265   >>> c_int()
 266   c_long(0)
 267   >>> c_char_p("Hello, World")
 268   c_char_p('Hello, World')
 269   >>> c_ushort(-3)
 270   c_ushort(65533)
 271   >>>
 272
 273Since these types are mutable, their value can also be changed afterwards::
 274
 275   >>> i = c_int(42)
 276   >>> print i
 277   c_long(42)
 278   >>> print i.value
 279   42
 280   >>> i.value = -99
 281   >>> print i.value
 282   -99
 283   >>>
 284
 285Assigning a new value to instances of the pointer types :class:`c_char_p`,
 286:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
 287point to, *not the contents* of the memory block (of course not, because Python
 288strings are immutable)::
 289
 290   >>> s = "Hello, World"
 291   >>> c_s = c_char_p(s)
 292   >>> print c_s
 293   c_char_p('Hello, World')
 294   >>> c_s.value = "Hi, there"
 295   >>> print c_s
 296   c_char_p('Hi, there')
 297   >>> print s                 # first string is unchanged
 298   Hello, World
 299   >>>
 300
 301You should be careful, however, not to pass them to functions expecting pointers
 302to mutable memory. If you need mutable memory blocks, ctypes has a
 303``create_string_buffer`` function which creates these in various ways.  The
 304current memory block contents can be accessed (or changed) with the ``raw``
 305property; if you want to access it as NUL terminated string, use the ``value``
 306property::
 307
 308   >>> from ctypes import *
 309   >>> p = create_string_buffer(3)      # create a 3 byte buffer, initialized to NUL bytes
 310   >>> print sizeof(p), repr(p.raw)
 311   3 '\x00\x00\x00'
 312   >>> p = create_string_buffer("Hello")      # create a buffer containing a NUL terminated string
 313   >>> print sizeof(p), repr(p.raw)
 314   6 'Hello\x00'
 315   >>> print repr(p.value)
 316   'Hello'
 317   >>> p = create_string_buffer("Hello", 10)  # create a 10 byte buffer
 318   >>> print sizeof(p), repr(p.raw)
 319   10 'Hello\x00\x00\x00\x00\x00'
 320   >>> p.value = "Hi"
 321   >>> print sizeof(p), repr(p.raw)
 322   10 'Hi\x00lo\x00\x00\x00\x00\x00'
 323   >>>
 324
 325The ``create_string_buffer`` function replaces the ``c_buffer`` function (which
 326is still available as an alias), as well as the ``c_string`` function from
 327earlier ctypes releases.  To create a mutable memory block containing unicode
 328characters of the C type ``wchar_t`` use the ``create_unicode_buffer`` function.
 329
 330
 331.. _ctypes-calling-functions-continued:
 332
 333Calling functions, continued
 334^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 335
 336Note that printf prints to the real standard output channel, *not* to
 337``sys.stdout``, so these examples will only work at the console prompt, not from
 338within *IDLE* or *PythonWin*::
 339
 340   >>> printf = libc.printf
 341   >>> printf("Hello, %s\n", "World!")
 342   Hello, World!
 343   14
 344   >>> printf("Hello, %S\n", u"World!")
 345   Hello, World!
 346   14
 347   >>> printf("%d bottles of beer\n", 42)
 348   42 bottles of beer
 349   19
 350   >>> printf("%f bottles of beer\n", 42.5)
 351   Traceback (most recent call last):
 352     File "<stdin>", line 1, in ?
 353   ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
 354   >>>
 355
 356As has been mentioned before, all Python types except integers, strings, and
 357unicode strings have to be wrapped in their corresponding ``ctypes`` type, so
 358that they can be converted to the required C data type::
 359
 360   >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
 361   An int 1234, a double 3.140000
 362   31
 363   >>>
 364
 365
 366.. _ctypes-calling-functions-with-own-custom-data-types:
 367
 368Calling functions with your own custom data types
 369^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 370
 371You can also customize ``ctypes`` argument conversion to allow instances of your
 372own classes be used as function arguments. ``ctypes`` looks for an
 373:attr:`_as_parameter_` attribute and uses this as the function argument. Of
 374course, it must be one of integer, string, or unicode::
 375
 376   >>> class Bottles(object):
 377   ...     def __init__(self, number):
 378   ...         self._as_parameter_ = number
 379   ...
 380   >>> bottles = Bottles(42)
 381   >>> printf("%d bottles of beer\n", bottles)
 382   42 bottles of beer
 383   19
 384   >>>
 385
 386If you don't want to store the instance's data in the :attr:`_as_parameter_`
 387instance variable, you could define a ``property`` which makes the data
 388available.
 389
 390
 391.. _ctypes-specifying-required-argument-types:
 392
 393Specifying the required argument types (function prototypes)
 394^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 395
 396It is possible to specify the required argument types of functions exported from
 397DLLs by setting the :attr:`argtypes` attribute.
 398
 399:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
 400probably not a good example here, because it takes a variable number and
 401different types of parameters depending on the format string, on the other hand
 402this is quite handy to experiment with this feature)::
 403
 404   >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
 405   >>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
 406   String 'Hi', Int 10, Double 2.200000
 407   37
 408   >>>
 409
 410Specifying a format protects against incompatible argument types (just as a
 411prototype for a C function), and tries to convert the arguments to valid types::
 412
 413   >>> printf("%d %d %d", 1, 2, 3)
 414   Traceback (most recent call last):
 415     File "<stdin>", line 1, in ?
 416   ArgumentError: argument 2: exceptions.TypeError: wrong type
 417   >>> printf("%s %d %f\n", "X", 2, 3)
 418   X 2 3.000000
 419   13
 420   >>>
 421
 422If you have defined your own classes which you pass to function calls, you have
 423to implement a :meth:`from_param` class method for them to be able to use them
 424in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
 425the Python object passed to the function call, it should do a typecheck or
 426whatever is needed to make sure this object is acceptable, and then return the
 427object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
 428pass as the C function argument in this case. Again, the result should be an
 429integer, string, unicode, a ``ctypes`` instance, or an object with an
 430:attr:`_as_parameter_` attribute.
 431
 432
 433.. _ctypes-return-types:
 434
 435Return types
 436^^^^^^^^^^^^
 437
 438By default functions are assumed to return the C ``int`` type.  Other return
 439types can be specified by setting the :attr:`restype` attribute of the function
 440object.
 441
 442Here is a more advanced example, it uses the ``strchr`` function, which expects
 443a string pointer and a char, and returns a pointer to a string::
 444
 445   >>> strchr = libc.strchr
 446   >>> strchr("abcdef", ord("d")) # doctest: +SKIP
 447   8059983
 448   >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
 449   >>> strchr("abcdef", ord("d"))
 450   'def'
 451   >>> print strchr("abcdef", ord("x"))
 452   None
 453   >>>
 454
 455If you want to avoid the ``ord("x")`` calls above, you can set the
 456:attr:`argtypes` attribute, and the second argument will be converted from a
 457single character Python string into a C char::
 458
 459   >>> strchr.restype = c_char_p
 460   >>> strchr.argtypes = [c_char_p, c_char]
 461   >>> strchr("abcdef", "d")
 462   'def'
 463   >>> strchr("abcdef", "def")
 464   Traceback (most recent call last):
 465     File "<stdin>", line 1, in ?
 466   ArgumentError: argument 2: exceptions.TypeError: one character string expected
 467   >>> print strchr("abcdef", "x")
 468   None
 469   >>> strchr("abcdef", "d")
 470   'def'
 471   >>>
 472
 473You can also use a callable Python object (a function or a class for example) as
 474the :attr:`restype` attribute, if the foreign function returns an integer.  The
 475callable will be called with the ``integer`` the C function returns, and the
 476result of this call will be used as the result of your function call. This is
 477useful to check for error return values and automatically raise an exception::
 478
 479   >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
 480   >>> def ValidHandle(value):
 481   ...     if value == 0:
 482   ...         raise WinError()
 483   ...     return value
 484   ...
 485   >>>
 486   >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
 487   >>> GetModuleHandle(None) # doctest: +WINDOWS
 488   486539264
 489   >>> GetModuleHandle("something silly") # doctest: +WINDOWS
 490   Traceback (most recent call last):
 491     File "<stdin>", line 1, in ?
 492     File "<stdin>", line 3, in ValidHandle
 493   WindowsError: [Errno 126] The specified module could not be found.
 494   >>>
 495
 496``WinError`` is a function which will call Windows ``FormatMessage()`` api to
 497get the string representation of an error code, and *returns* an exception.
 498``WinError`` takes an optional error code parameter, if no one is used, it calls
 499:func:`GetLastError` to retrieve it.
 500
 501Please note that a much more powerful error checking mechanism is available
 502through the :attr:`errcheck` attribute; see the reference manual for details.
 503
 504
 505.. _ctypes-passing-pointers:
 506
 507Passing pointers (or: passing parameters by reference)
 508^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 509
 510Sometimes a C api function expects a *pointer* to a data type as parameter,
 511probably to write into the corresponding location, or if the data is too large
 512to be passed by value. This is also known as *passing parameters by reference*.
 513
 514``ctypes`` exports the :func:`byref` function which is used to pass parameters
 515by reference.  The same effect can be achieved with the ``pointer`` function,
 516although ``pointer`` does a lot more work since it constructs a real pointer
 517object, so it is faster to use :func:`byref` if you don't need the pointer
 518object in Python itself::
 519
 520   >>> i = c_int()
 521   >>> f = c_float()
 522   >>> s = create_string_buffer('\000' * 32)
 523   >>> print i.value, f.value, repr(s.value)
 524   0 0.0 ''
 525   >>> libc.sscanf("1 3.14 Hello", "%d %f %s",
 526   ...             byref(i), byref(f), s)
 527   3
 528   >>> print i.value, f.value, repr(s.value)
 529   1 3.1400001049 'Hello'
 530   >>>
 531
 532
 533.. _ctypes-structures-unions:
 534
 535Structures and unions
 536^^^^^^^^^^^^^^^^^^^^^
 537
 538Structures and unions must derive from the :class:`Structure` and :class:`Union`
 539base classes which are defined in the ``ctypes`` module. Each subclass must
 540define a :attr:`_fields_` attribute.  :attr:`_fields_` must be a list of
 541*2-tuples*, containing a *field name* and a *field type*.
 542
 543The field type must be a ``ctypes`` type like :class:`c_int`, or any other
 544derived ``ctypes`` type: structure, union, array, pointer.
 545
 546Here is a simple example of a POINT structure, which contains two integers named
 547``x`` and ``y``, and also shows how to initialize a structure in the
 548constructor::
 549
 550   >>> from ctypes import *
 551   >>> class POINT(Structure):
 552   ...     _fields_ = [("x", c_int),
 553   ...                 ("y", c_int)]
 554   ...
 555   >>> point = POINT(10, 20)
 556   >>> print point.x, point.y
 557   10 20
 558   >>> point = POINT(y=5)
 559   >>> print point.x, point.y
 560   0 5
 561   >>> POINT(1, 2, 3)
 562   Traceback (most recent call last):
 563     File "<stdin>", line 1, in ?
 564   ValueError: too many initializers
 565   >>>
 566
 567You can, however, build much more complicated structures. Structures can itself
 568contain other structures by using a structure as a field type.
 569
 570Here is a RECT structure which contains two POINTs named ``upperleft`` and
 571``lowerright``  ::
 572
 573   >>> class RECT(Structure):
 574   ...     _fields_ = [("upperleft", POINT),
 575   ...                 ("lowerright", POINT)]
 576   ...
 577   >>> rc = RECT(point)
 578   >>> print rc.upperleft.x, rc.upperleft.y
 579   0 5
 580   >>> print rc.lowerright.x, rc.lowerright.y
 581   0 0
 582   >>>
 583
 584Nested structures can also be initialized in the constructor in several ways::
 585
 586   >>> r = RECT(POINT(1, 2), POINT(3, 4))
 587   >>> r = RECT((1, 2), (3, 4))
 588
 589Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
 590for debugging because they can provide useful information::
 591
 592   >>> print POINT.x
 593   <Field type=c_long, ofs=0, size=4>
 594   >>> print POINT.y
 595   <Field type=c_long, ofs=4, size=4>
 596   >>>
 597
 598
 599.. _ctypes-structureunion-alignment-byte-order:
 600
 601Structure/union alignment and byte order
 602^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 603
 604By default, Structure and Union fields are aligned in the same way the C
 605compiler does it. It is possible to override this behavior be specifying a
 606:attr:`_pack_` class attribute in the subclass definition. This must be set to a
 607positive integer and specifies the maximum alignment for the fields. This is
 608what ``#pragma pack(n)`` also does in MSVC.
 609
 610``ctypes`` uses the native byte order for Structures and Unions.  To build
 611structures with non-native byte order, you can use one of the
 612BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
 613base classes.  These classes cannot contain pointer fields.
 614
 615
 616.. _ctypes-bit-fields-in-structures-unions:
 617
 618Bit fields in structures and unions
 619^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 620
 621It is possible to create structures and unions containing bit fields. Bit fields
 622are only possible for integer fields, the bit width is specified as the third
 623item in the :attr:`_fields_` tuples::
 624
 625   >>> class Int(Structure):
 626   ...     _fields_ = [("first_16", c_int, 16),
 627   ...                 ("second_16", c_int, 16)]
 628   ...
 629   >>> print Int.first_16
 630   <Field type=c_long, ofs=0:0, bits=16>
 631   >>> print Int.second_16
 632   <Field type=c_long, ofs=0:16, bits=16>
 633   >>>
 634
 635
 636.. _ctypes-arrays:
 637
 638Arrays
 639^^^^^^
 640
 641Arrays are sequences, containing a fixed number of instances of the same type.
 642
 643The recommended way to create array types is by multiplying a data type with a
 644positive integer::
 645
 646   TenPointsArrayType = POINT * 10
 647
 648Here is an example of an somewhat artificial data type, a structure containing 4
 649POINTs among other stuff::
 650
 651   >>> from ctypes import *
 652   >>> class POINT(Structure):
 653   ...    _fields_ = ("x", c_int), ("y", c_int)
 654   ...
 655   >>> class MyStruct(Structure):
 656   ...    _fields_ = [("a", c_int),
 657   ...                ("b", c_float),
 658   ...                ("point_array", POINT * 4)]
 659   >>>
 660   >>> print len(MyStruct().point_array)
 661   4
 662   >>>
 663
 664Instances are created in the usual way, by calling the class::
 665
 666   arr = TenPointsArrayType()
 667   for pt in arr:
 668       print pt.x, pt.y
 669
 670The above code print a series of ``0 0`` lines, because the array contents is
 671initialized to zeros.
 672
 673Initializers of the correct type can also be specified::
 674
 675   >>> from ctypes import *
 676   >>> TenIntegers = c_int * 10
 677   >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
 678   >>> print ii
 679   <c_long_Array_10 object at 0x...>
 680   >>> for i in ii: print i,
 681   ...
 682   1 2 3 4 5 6 7 8 9 10
 683   >>>
 684
 685
 686.. _ctypes-pointers:
 687
 688Pointers
 689^^^^^^^^
 690
 691Pointer instances are created by calling the ``pointer`` function on a
 692``ctypes`` type::
 693
 694   >>> from ctypes import *
 695   >>> i = c_int(42)
 696   >>> pi = pointer(i)
 697   >>>
 698
 699Pointer instances have a ``contents`` attribute which returns the object to
 700which the pointer points, the ``i`` object above::
 701
 702   >>> pi.contents
 703   c_long(42)
 704   >>>
 705
 706Note that ``ctypes`` does not have OOR (original object return), it constructs a
 707new, equivalent object each time you retrieve an attribute::
 708
 709   >>> pi.contents is i
 710   False
 711   >>> pi.contents is pi.contents
 712   False
 713   >>>
 714
 715Assigning another :class:`c_int` instance to the pointer's contents attribute
 716would cause the pointer to point to the memory location where this is stored::
 717
 718   >>> i = c_int(99)
 719   >>> pi.contents = i
 720   >>> pi.contents
 721   c_long(99)
 722   >>>
 723
 724.. XXX Document dereferencing pointers, and that it is preferred over the .contents attribute.
 725
 726Pointer instances can also be indexed with integers::
 727
 728   >>> pi[0]
 729   99
 730   >>>
 731
 732Assigning to an integer index changes the pointed to value::
 733
 734   >>> print i
 735   c_long(99)
 736   >>> pi[0] = 22
 737   >>> print i
 738   c_long(22)
 739   >>>
 740
 741It is also possible to use indexes different from 0, but you must know what
 742you're doing, just as in C: You can access or change arbitrary memory locations.
 743Generally you only use this feature if you receive a pointer from a C function,
 744and you *know* that the pointer actually points to an array instead of a single
 745item.
 746
 747Behind the scenes, the ``pointer`` function does more than simply create pointer
 748instances, it has to create pointer *types* first. This is done with the
 749``POINTER`` function, which accepts any ``ctypes`` type, and returns a new
 750type::
 751
 752   >>> PI = POINTER(c_int)
 753   >>> PI
 754   <class 'ctypes.LP_c_long'>
 755   >>> PI(42)
 756   Traceback (most recent call last):
 757     File "<stdin>", line 1, in ?
 758   TypeError: expected c_long instead of int
 759   >>> PI(c_int(42))
 760   <ctypes.LP_c_long object at 0x...>
 761   >>>
 762
 763Calling the pointer type without an argument creates a ``NULL`` pointer.
 764``NULL`` pointers have a ``False`` boolean value::
 765
 766   >>> null_ptr = POINTER(c_int)()
 767   >>> print bool(null_ptr)
 768   False
 769   >>>
 770
 771``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
 772invalid non-\ ``NULL`` pointers would crash Python)::
 773
 774   >>> null_ptr[0]
 775   Traceback (most recent call last):
 776       ....
 777   ValueError: NULL pointer access
 778   >>>
 779
 780   >>> null_ptr[0] = 1234
 781   Traceback (most recent call last):
 782       ....
 783   ValueError: NULL pointer access
 784   >>>
 785
 786
 787.. _ctypes-type-conversions:
 788
 789Type conversions
 790^^^^^^^^^^^^^^^^
 791
 792Usually, ctypes does strict type checking.  This means, if you have
 793``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
 794a member field in a structure definition, only instances of exactly the same
 795type are accepted.  There are some exceptions to this rule, where ctypes accepts
 796other objects.  For example, you can pass compatible array instances instead of
 797pointer types.  So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
 798
 799   >>> class Bar(Structure):
 800   ...     _fields_ = [("count", c_int), ("values", POINTER(c_int))]
 801   ...
 802   >>> bar = Bar()
 803   >>> bar.values = (c_int * 3)(1, 2, 3)
 804   >>> bar.count = 3
 805   >>> for i in range(bar.count):
 806   ...     print bar.values[i]
 807   ...
 808   1
 809   2
 810   3
 811   >>>
 812
 813To set a POINTER type field to ``NULL``, you can assign ``None``::
 814
 815   >>> bar.values = None
 816   >>>
 817
 818.. XXX list other conversions...
 819
 820Sometimes you have instances of incompatible types.  In C, you can cast one
 821type into another type.  ``ctypes`` provides a ``cast`` function which can be
 822used in the same way.  The ``Bar`` structure defined above accepts
 823``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
 824but not instances of other types::
 825
 826   >>> bar.values = (c_byte * 4)()
 827   Traceback (most recent call last):
 828     File "<stdin>", line 1, in ?
 829   TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
 830   >>>
 831
 832For these cases, the ``cast`` function is handy.
 833
 834The ``cast`` function can be used to cast a ctypes instance into a pointer to a
 835different ctypes data type.  ``cast`` takes two parameters, a ctypes object that
 836is or can be converted to a pointer of some kind, and a ctypes pointer type.  It
 837returns an instance of the second argument, which references the same memory
 838block as the first argument::
 839
 840   >>> a = (c_byte * 4)()
 841   >>> cast(a, POINTER(c_int))
 842   <ctypes.LP_c_long object at ...>
 843   >>>
 844
 845So, ``cast`` can be used to assign to the ``values`` field of ``Bar`` the
 846structure::
 847
 848   >>> bar = Bar()
 849   >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
 850   >>> print bar.values[0]
 851   0
 852   >>>
 853
 854
 855.. _ctypes-incomplete-types:
 856
 857Incomplete Types
 858^^^^^^^^^^^^^^^^
 859
 860*Incomplete Types* are structures, unions or arrays whose members are not yet
 861specified. In C, they are specified by forward declarations, which are defined
 862later::
 863
 864   struct cell; /* forward declaration */
 865
 866   struct {
 867       char *name;
 868       struct cell *next;
 869   } cell;
 870
 871The straightforward translation into ctypes code would be this, but it does not
 872work::
 873
 874   >>> class cell(Structure):
 875   ...     _fields_ = [("name", c_char_p),
 876   ...                 ("next", POINTER(cell))]
 877   ...
 878   Traceback (most recent call last):
 879     File "<stdin>", line 1, in ?
 880     File "<stdin>", line 2, in cell
 881   NameError: name 'cell' is not defined
 882   >>>
 883
 884because the new ``class cell`` is not available in the class statement itself.
 885In ``ctypes``, we can define the ``cell`` class and set the :attr:`_fields_`
 886attribute later, after the class statement::
 887
 888   >>> from ctypes import *
 889   >>> class cell(Structure):
 890   ...     pass
 891   ...
 892   >>> cell._fields_ = [("name", c_char_p),
 893   ...                  ("next", POINTER(cell))]
 894   >>>
 895
 896Lets try it. We create two instances of ``cell``, and let them point to each
 897other, and finally follow the pointer chain a few times::
 898
 899   >>> c1 = cell()
 900   >>> c1.name = "foo"
 901   >>> c2 = cell()
 902   >>> c2.name = "bar"
 903   >>> c1.next = pointer(c2)
 904   >>> c2.next = pointer(c1)
 905   >>> p = c1
 906   >>> for i in range(8):
 907   ...     print p.name,
 908   ...     p = p.next[0]
 909   ...
 910   foo bar foo bar foo bar foo bar
 911   >>>
 912
 913
 914.. _ctypes-callback-functions:
 915
 916Callback functions
 917^^^^^^^^^^^^^^^^^^
 918
 919``ctypes`` allows to create C callable function pointers from Python callables.
 920These are sometimes called *callback functions*.
 921
 922First, you must create a class for the callback function, the class knows the
 923calling convention, the return type, and the number and types of arguments this
 924function will receive.
 925
 926The CFUNCTYPE factory function creates types for callback functions using the
 927normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
 928function creates types for callback functions using the stdcall calling
 929convention.
 930
 931Both of these factory functions are called with the result type as first
 932argument, and the callback functions expected argument types as the remaining
 933arguments.
 934
 935I will present an example here which uses the standard C library's :func:`qsort`
 936function, this is used to sort items with the help of a callback function.
 937:func:`qsort` will be used to sort an array of integers::
 938
 939   >>> IntArray5 = c_int * 5
 940   >>> ia = IntArray5(5, 1, 7, 33, 99)
 941   >>> qsort = libc.qsort
 942   >>> qsort.restype = None
 943   >>>
 944
 945:func:`qsort` must be called with a pointer to the data to sort, the number of
 946items in the data array, the size of one item, and a pointer to the comparison
 947function, the callback. The callback will then be called with two pointers to
 948items, and it must return a negative integer if the first item is smaller than
 949the second, a zero if they are equal, and a positive integer else.
 950
 951So our callback function receives pointers to integers, and must return an
 952integer. First we create the ``type`` for the callback function::
 953
 954   >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
 955   >>>
 956
 957For the first implementation of the callback function, we simply print the
 958arguments we get, and return 0 (incremental development ;-)::
 959
 960   >>> def py_cmp_func(a, b):
 961   ...     print "py_cmp_func", a, b
 962   ...     return 0
 963   ...
 964   >>>
 965
 966Create the C callable callback::
 967
 968   >>> cmp_func = CMPFUNC(py_cmp_func)
 969   >>>
 970
 971And we're ready to go::
 972
 973   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
 974   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
 975   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
 976   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
 977   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
 978   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
 979   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
 980   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
 981   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
 982   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
 983   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
 984   >>>
 985
 986We know how to access the contents of a pointer, so lets redefine our callback::
 987
 988   >>> def py_cmp_func(a, b):
 989   ...     print "py_cmp_func", a[0], b[0]
 990   ...     return 0
 991   ...
 992   >>> cmp_func = CMPFUNC(py_cmp_func)
 993   >>>
 994
 995Here is what we get on Windows::
 996
 997   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
 998   py_cmp_func 7 1
 999   py_cmp_func 33 1
1000   py_cmp_func 99 1
1001   py_cmp_func 5 1
1002   py_cmp_func 7 5
1003   py_cmp_func 33 5
1004   py_cmp_func 99 5
1005   py_cmp_func 7 99
1006   py_cmp_func 33 99
1007   py_cmp_func 7 33
1008   >>>
1009
1010It is funny to see that on linux the sort function seems to work much more
1011efficient, it is doing less comparisons::
1012
1013   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
1014   py_cmp_func 5 1
1015   py_cmp_func 33 99
1016   py_cmp_func 7 33
1017   py_cmp_func 5 7
1018   py_cmp_func 1 7
1019   >>>
1020
1021Ah, we're nearly done! The last step is to actually compare the two items and
1022return a useful result::
1023
1024   >>> def py_cmp_func(a, b):
1025   ...     print "py_cmp_func", a[0], b[0]
1026   ...     return a[0] - b[0]
1027   ...
1028   >>>
1029
1030Final run on Windows::
1031
1032   >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
1033   py_cmp_func 33 7
1034   py_cmp_func 99 33
1035   py_cmp_func 5 99
1036   py_cmp_func 1 99
1037   py_cmp_func 33 7
1038   py_cmp_func 1 33
1039   py_cmp_func 5 33
1040   py_cmp_func 5 7
1041   py_cmp_func 1 7
1042   py_cmp_func 5 1
1043   >>>
1044
1045and on Linux::
1046
1047   >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1048   py_cmp_func 5 1
1049   py_cmp_func 33 99
1050   py_cmp_func 7 33
1051   py_cmp_func 1 7
1052   py_cmp_func 5 7
1053   >>>
1054
1055It is quite interesting to see that the Windows :func:`qsort` function needs
1056more comparisons than the linux version!
1057
1058As we can easily check, our array is sorted now::
1059
1060   >>> for i in ia: print i,
1061   ...
1062   1 5 7 33 99
1063   >>>
1064
1065**Important note for callback functions:**
1066
1067Make sure you keep references to CFUNCTYPE objects as long as they are used from
1068C code. ``ctypes`` doesn't, and if you don't, they may be garbage collected,
1069crashing your program when a callback is made.
1070
1071
1072.. _ctypes-accessing-values-exported-from-dlls:
1073
1074Accessing values exported from dlls
1075^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1076
1077Some shared libraries not only export functions, they also export variables. An
1078example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
1079to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
1080startup.
1081
1082``ctypes`` can access values like this with the :meth:`in_dll` class methods of
1083the type.  *pythonapi* is a predefined symbol giving access to the Python C
1084api::
1085
1086   >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
1087   >>> print opt_flag
1088   c_long(0)
1089   >>>
1090
1091If the interpreter would have been started with :option:`-O`, the sample would
1092have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1093specified.
1094
1095An extended example which also demonstrates the use of pointers accesses the
1096``PyImport_FrozenModules`` pointer exported by Python.
1097
1098Quoting the Python docs: *This pointer is initialized to point to an array of
1099"struct _frozen" records, terminated by one whose members are all NULL or zero.
1100When a frozen module is imported, it is searched in this table. Third-party code
1101could play tricks with this to provide a dynamically created collection of
1102frozen modules.*
1103
1104So manipulating this pointer could even prove useful. To restrict the example
1105size, we show only how this table can be read with ``ctypes``::
1106
1107   >>> from ctypes import *
1108   >>>
1109   >>> class struct_frozen(Structure):
1110   ...     _fields_ = [("name", c_char_p),
1111   ...                 ("code", POINTER(c_ubyte)),
1112   ...                 ("size", c_int)]
1113   ...
1114   >>>
1115
1116We have defined the ``struct _frozen`` data type, so we can get the pointer to
1117the table::
1118
1119   >>> FrozenTable = POINTER(struct_frozen)
1120   >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1121   >>>
1122
1123Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1124can iterate over it, but we just have to make sure that our loop terminates,
1125because pointers have no size. Sooner or later it would probably crash with an
1126access violation or whatever, so it's better to break out of the loop when we
1127hit the NULL entry::
1128
1129   >>> for item in table:
1130   ...    print item.name, item.size
1131   ...    if item.name is None:
1132   ...        break
1133   ...
1134   __hello__ 104
1135   __phello__ -104
1136   __phello__.spam 104
1137   None 0
1138   >>>
1139
1140The fact that standard Python has a frozen module and a frozen package
1141(indicated by the negative size member) is not well known, it is only used for
1142testing. Try it out with ``import __hello__`` for example.
1143
1144
1145.. _ctypes-surprises:
1146
1147Surprises
1148^^^^^^^^^
1149
1150There are some edges in ``ctypes`` where you may be expect something else than
1151what actually happens.
1152
1153Consider the following example::
1154
1155   >>> from ctypes import *
1156   >>> class POINT(Structure):
1157   ...     _fields_ = ("x", c_int), ("y", c_int)
1158   ...
1159   >>> class RECT(Structure):
1160   ...     _fields_ = ("a", POINT), ("b", POINT)
1161   ...
1162   >>> p1 = POINT(1, 2)
1163   >>> p2 = POINT(3, 4)
1164   >>> rc = RECT(p1, p2)
1165   >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1166   1 2 3 4
1167   >>> # now swap the two points
1168   >>> rc.a, rc.b = rc.b, rc.a
1169   >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1170   3 4 3 4
1171   >>>
1172
1173Hm. We certainly expected the last statement to print ``3 4 1 2``. What
1174happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
1175
1176   >>> temp0, temp1 = rc.b, rc.a
1177   >>> rc.a = temp0
1178   >>> rc.b = temp1
1179   >>>
1180
1181Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1182the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1183contents of ``temp0`` into ``rc`` 's buffer.  This, in turn, changes the
1184contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1185the expected effect.
1186
1187Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1188doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
1189the root-object's underlying buffer.
1190
1191Another example that may behave different from what one would expect is this::
1192
1193   >>> s = c_char_p()
1194   >>> s.value = "abc def ghi"
1195   >>> s.value
1196   'abc def ghi'
1197   >>> s.value is s.value
1198   False
1199   >>>
1200
1201Why is it printing ``False``?  ctypes instances are objects containing a memory
1202block plus some :term:`descriptor`\s accessing the contents of the memory.
1203Storing a Python object in the memory block does not store the object itself,
1204instead the ``contents`` of the object is stored.  Accessing the contents again
1205constructs a new Python object each time!
1206
1207
1208.. _ctypes-variable-sized-data-types:
1209
1210Variable-sized data types
1211^^^^^^^^^^^^^^^^^^^^^^^^^
1212
1213``ctypes`` provides some support for variable-sized arrays and structures (this
1214was added in version 0.9.9.7).
1215
1216The ``resize`` function can be used to resize the memory buffer of an existing
1217ctypes object.  The function takes the object as first argument, and the
1218requested size in bytes as the second argument.  The memory block cannot be made
1219smaller than the natural memory block specified by the objects type, a
1220``ValueError`` is raised if this is tried::
1221
1222   >>> short_array = (c_short * 4)()
1223   >>> print sizeof(short_array)
1224   8
1225   >>> resize(short_array, 4)
1226   Traceback (most recent call last):
1227       ...
1228   ValueError: minimum size is 8
1229   >>> resize(short_array, 32)
1230   >>> sizeof(short_array)
1231   32
1232   >>> sizeof(type(short_array))
1233   8
1234   >>>
1235
1236This is nice and fine, but how would one access the additional elements
1237contained in this array?  Since the type still only knows about 4 elements, we
1238get errors accessing other elements::
1239
1240   >>> short_array[:]
1241   [0, 0, 0, 0]
1242   >>> short_array[7]
1243   Traceback (most recent call last):
1244       ...
1245   IndexError: invalid index
1246   >>>
1247
1248Another way to use variable-sized data types with ``ctypes`` is to use the
1249dynamic nature of Python, and (re-)define the data type after the required size
1250is already known, on a case by case basis.
1251
1252
1253.. _ctypes-ctypes-reference:
1254
1255ctypes reference
1256----------------
1257
1258
1259.. _ctypes-finding-shared-libraries:
1260
1261Finding shared libraries
1262^^^^^^^^^^^^^^^^^^^^^^^^
1263
1264When programming in a compiled language, shared libraries are accessed when
1265compiling/linking a program, and when the program is run.
1266
1267The purpose of the ``find_library`` function is to locate a library in a way
1268similar to what the compiler does (on platforms with several versions of a
1269shared library the most recent should be loaded), while the ctypes library
1270loaders act like when a program is run, and call the runtime loader directly.
1271
1272The ``ctypes.util`` module provides a function which can help to determine the
1273library to load.
1274
1275
1276.. data:: find_library(name)
1277   :module: ctypes.util
1278   :noindex:
1279
1280   Try to find a library and return a pathname.  *name* is the library name without
1281   any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1282   is the form used for the posix linker option :option:`-l`).  If no library can
1283   be found, returns ``None``.
1284
1285The exact functionality is system dependent.
1286
1287On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
1288and objdump) to find the library file.  It returns the filename of the library
1289file.  Here are some examples::
1290
1291   >>> from ctypes.util import find_library
1292   >>> find_library("m")
1293   'libm.so.6'
1294   >>> find_library("c")
1295   'libc.so.6'
1296   >>> find_library("bz2")
1297   'libbz2.so.1.0'
1298   >>>
1299
1300On OS X, ``find_library`` tries several predefined naming schemes and paths to
1301locate the library, and returns a full pathname if successful::
1302
1303   >>> from ctypes.util import find_library
1304   >>> find_library("c")
1305   '/usr/lib/libc.dylib'
1306   >>> find_library("m")
1307   '/usr/lib/libm.dylib'
1308   >>> find_library("bz2")
1309   '/usr/lib/libbz2.dylib'
1310   >>> find_library("AGL")
1311   '/System/Library/Frameworks/AGL.framework/AGL'
1312   >>>
1313
1314On Windows, ``find_library`` searches along the system search path, and returns
1315the full pathname, but since there is no predefined naming scheme a call like
1316``find_library("c")`` will fail and return ``None``.
1317
1318If wrapping a shared library with ``ctypes``, it *may* be better to determine
1319the shared library name at development type, and hardcode that into the wrapper
1320module instead of using ``find_library`` to locate the library at runtime.
1321
1322
1323.. _ctypes-loading-shared-libraries:
1324
1325Loading shared libraries
1326^^^^^^^^^^^^^^^^^^^^^^^^
1327
1328There are several ways to loaded shared libraries into the Python process.  One
1329way is to instantiate one of the following classes:
1330
1331
1332.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1333
1334   Instances of this class represent loaded shared libraries. Functions in these
1335   libraries use the standard C calling convention, and are assumed to return
1336   ``int``.
1337
1338
1339.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1340
1341   Windows only: Instances of this class represent loaded shared libraries,
1342   functions in these libraries use the ``stdcall`` calling convention, and are
1343   assumed to return the windows specific :class:`HRESULT` code.  :class:`HRESULT`
1344   values contain information specifying whether the function call failed or
1345   succeeded, together with additional error code.  If the return value signals a
1346   failure, an :class:`WindowsError` is automatically raised.
1347
1348
1349.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1350
1351   Windows only: Instances of this class represent loaded shared libraries,
1352   functions in these libraries use the ``stdcall`` calling convention, and are
1353   assumed to return ``int`` by default.
1354
1355   On Windows CE only the standard calling convention is used, for convenience the
1356   :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1357   platform.
1358
1359The Python :term:`global interpreter lock` is released before calling any
1360function exported by these libraries, and reacquired afterwards.
1361
1362
1363.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1364
1365   Instances of this class behave like :class:`CDLL` instances, except that the
1366   Python GIL is *not* released during the function call, and after the function
1367   execution the Python error flag is checked. If the error flag is set, a Python
1368   exception is raised.
1369
1370   Thus, this is only useful to call Python C api functions directly.
1371
1372All these classes can be instantiated by calling them with at least one
1373argument, the pathname of the shared library.  If you have an existing handle to
1374an already loaded shared library, it can be passed as the ``handle`` named
1375parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
1376function is used to load the library into the process, and to get a handle to
1377it.
1378
1379The *mode* parameter can be used to specify how the library is loaded.  For
1380details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
1381
1382The *use_errno* parameter, when set to True, enables a ctypes mechanism that
1383allows to access the system :data:`errno` error number in a safe way.
1384:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1385variable; if you call foreign functions created with ``use_errno=True`` then the
1386:data:`errno` value before the function call is swapped with the ctypes private
1387copy, the same happens immediately after the function call.
1388
1389The function :func:`ctypes.get_errno` returns the value of the ctypes private
1390copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1391to a new value and returns the former value.
1392
1393The *use_last_error* parameter, when set to True, enables the same mechanism for
1394the Windows error code which is managed by the :func:`GetLastError` and
1395:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1396:func:`ctypes.set_last_error` are used to request and change the ctypes private
1397copy of the windows error code.
1398
1399.. versionadded:: 2.6
1400   The ``use_last_error`` and ``use_errno`` optional parameters
1401   were added.
1402
1403.. data:: RTLD_GLOBAL
1404   :noindex:
1405
1406   Flag to use as *mode* parameter.  On platforms where this flag is not available,
1407   it is defined as the integer zero.
1408
1409
1410.. data:: RTLD_LOCAL
1411   :noindex:
1412
1413   Flag to use as *mode* parameter.  On platforms where this is not available, it
1414   is the same as *RTLD_GLOBAL*.
1415
1416
1417.. data:: DEFAULT_MODE
1418   :noindex:
1419
1420   The default mode which is used to load shared libraries.  On OSX 10.3, this is
1421   *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1422
1423Instances of…

Large files files are truncated, but you can click here to view the full file