rest25/library/ctypes.rst => rest262/library/ctypes.rst
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
n13-data types, and allows to call functions in dlls/shared libraries.  It can be
n13+data 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
n22-Note: The code samples in this tutorial uses ``doctest`` to make sure that they
n22+Note: 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
n26-Note: Quite some code samples references the ctypes :class:`c_int` type. This
n26+Note: Some code samples reference the ctypes :class:`c_int` type. This type is
27-type is an alias to the :class:`c_long` type on 32-bit systems.  So, you should
27+an alias for the :class:`c_long` type on 32-bit systems.  So, you should not be
28-not be confused if :class:`c_long` is printed if you would expect :class:`c_int`
28+confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
29-they are actually the same type.
29+they are actually the same type.
30
31
32.. _ctypes-loading-dynamic-link-libraries:
33
34Loading dynamic link libraries
35^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
36
n37-``ctypes`` exports the *cdll*, and on Windows also *windll* and *oledll* objects
n37+``ctypes`` exports the *cdll*, and on Windows *windll* and *oledll*
38-to load dynamic link libraries.
38+objects, 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
n45-code is used to automatically raise :class:`WindowsError` Python exceptions when
n45+code is used to automatically raise a :class:`WindowsError` exception when
46the function call fails.
47
n48-Here are some examples for Windows, note that ``msvcrt`` is the MS standard C
n48+Here 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
n60-Windows appends the usual '.dll' file suffix automatically.
n60+Windows appends the usual ``.dll`` file suffix automatically.
61
62On Linux, it is required to specify the filename *including* the extension to
n63-load a library, so attribute access does not work. Either the
n63+load 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
n74-.. % XXX Add section for Mac OS X.
n74+.. 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::
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``
n112-explicitely, and then call it with normal strings or unicode strings
n112+explicitly, 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...>
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   +----------------------+--------------------------------+----------------------------+
n252+   | :class:`c_longdouble`| ``long double``                | float                      |
253+   +----------------------+--------------------------------+----------------------------+
252   | :class:`c_char_p`    | ``char *`` (NUL terminated)    | string or ``None``         |
253   +----------------------+--------------------------------+----------------------------+
254   | :class:`c_wchar_p`   | ``wchar_t *`` (NUL terminated) | unicode or ``None``        |
255   +----------------------+--------------------------------+----------------------------+
256   | :class:`c_void_p`    | ``void *``                     | int/long or ``None``       |
257   +----------------------+--------------------------------+----------------------------+
258
259
295   >>> print s                 # first string is unchanged
296   Hello, World
297   >>>
298
299You should be careful, however, not to pass them to functions expecting pointers
300to mutable memory. If you need mutable memory blocks, ctypes has a
301``create_string_buffer`` function which creates these in various ways.  The
302current memory block contents can be accessed (or changed) with the ``raw``
n303-property, if you want to access it as NUL terminated string, use the ``string``
n305+property; if you want to access it as NUL terminated string, use the ``value``
304property::
305
306   >>> from ctypes import *
307   >>> p = create_string_buffer(3)      # create a 3 byte buffer, initialized to NUL bytes
308   >>> print sizeof(p), repr(p.raw)
309   3 '\x00\x00\x00'
310   >>> p = create_string_buffer("Hello")      # create a buffer containing a NUL terminated string
311   >>> print sizeof(p), repr(p.raw)
312   6 'Hello\x00'
313   >>> print repr(p.value)
314   'Hello'
315   >>> p = create_string_buffer("Hello", 10)  # create a 10 byte buffer
316   >>> print sizeof(p), repr(p.raw)
317   10 'Hello\x00\x00\x00\x00\x00'
n318-   >>> p.value = "Hi"      
n320+   >>> p.value = "Hi"
319   >>> print sizeof(p), repr(p.raw)
320   10 'Hi\x00lo\x00\x00\x00\x00\x00'
321   >>>
322
323The ``create_string_buffer`` function replaces the ``c_buffer`` function (which
324is still available as an alias), as well as the ``c_string`` function from
325earlier ctypes releases.  To create a mutable memory block containing unicode
326characters of the C type ``wchar_t`` use the ``create_unicode_buffer`` function.
378   >>> bottles = Bottles(42)
379   >>> printf("%d bottles of beer\n", bottles)
380   42 bottles of beer
381   19
382   >>>
383
384If you don't want to store the instance's data in the :attr:`_as_parameter_`
385instance variable, you could define a ``property`` which makes the data
n386-avaiblable.
n388+available.
387
388
389.. _ctypes-specifying-required-argument-types:
390
391Specifying the required argument types (function prototypes)
392^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
393
394It is possible to specify the required argument types of functions exported from
417   12
418   >>>
419
420If you have defined your own classes which you pass to function calls, you have
421to implement a :meth:`from_param` class method for them to be able to use them
422in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
423the Python object passed to the function call, it should do a typecheck or
424whatever is needed to make sure this object is acceptable, and then return the
n425-object itself, it's :attr:`_as_parameter_` attribute, or whatever you want to
n427+object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
426pass as the C function argument in this case. Again, the result should be an
n427-integer, string, unicode, a ``ctypes`` instance, or something having the
n429+integer, string, unicode, a ``ctypes`` instance, or an object with an
428:attr:`_as_parameter_` attribute.
429
430
431.. _ctypes-return-types:
432
433Return types
434^^^^^^^^^^^^
435
579   0 0
580   >>>
581
582Nested structures can also be initialized in the constructor in several ways::
583
584   >>> r = RECT(POINT(1, 2), POINT(3, 4))
585   >>> r = RECT((1, 2), (3, 4))
586
n587-Fielddescriptors can be retrieved from the *class*, they are useful for
n589+Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
588-debugging because they can provide useful information::
590+for debugging because they can provide useful information::
589
590   >>> print POINT.x
591   <Field type=c_long, ofs=0, size=4>
592   >>> print POINT.y
593   <Field type=c_long, ofs=4, size=4>
594   >>>
595
596
597.. _ctypes-structureunion-alignment-byte-order:
598
599Structure/union alignment and byte order
600^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
601
602By default, Structure and Union fields are aligned in the same way the C
n603-compiler does it. It is possible to override this behaviour be specifying a
n605+compiler does it. It is possible to override this behavior be specifying a
604:attr:`_pack_` class attribute in the subclass definition. This must be set to a
605positive integer and specifies the maximum alignment for the fields. This is
606what ``#pragma pack(n)`` also does in MSVC.
607
608``ctypes`` uses the native byte order for Structures and Unions.  To build
609structures with non-native byte order, you can use one of the
610BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
611base classes.  These classes cannot contain pointer fields.
638
639Arrays are sequences, containing a fixed number of instances of the same type.
640
641The recommended way to create array types is by multiplying a data type with a
642positive integer::
643
644   TenPointsArrayType = POINT * 10
645
n646-Here is an example of an somewhat artifical data type, a structure containing 4
n648+Here is an example of an somewhat artificial data type, a structure containing 4
647POINTs among other stuff::
648
649   >>> from ctypes import *
650   >>> class POINT(Structure):
651   ...    _fields_ = ("x", c_int), ("y", c_int)
652   ...
653   >>> class MyStruct(Structure):
654   ...    _fields_ = [("a", c_int),
713Assigning another :class:`c_int` instance to the pointer's contents attribute
714would cause the pointer to point to the memory location where this is stored::
715
716   >>> i = c_int(99)
717   >>> pi.contents = i
718   >>> pi.contents
719   c_long(99)
720   >>>
n723+ 
724+.. XXX Document dereferencing pointers, and that it is preferred over the .contents attribute.
721
722Pointer instances can also be indexed with integers::
723
724   >>> pi[0]
725   99
726   >>>
727
728Assigning to an integer index changes the pointed to value::
760``NULL`` pointers have a ``False`` boolean value::
761
762   >>> null_ptr = POINTER(c_int)()
763   >>> print bool(null_ptr)
764   False
765   >>>
766
767``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
n768-non-\ ``NULL`` pointers would crash Python)::
n772+invalid non-\ ``NULL`` pointers would crash Python)::
769
770   >>> null_ptr[0]
771   Traceback (most recent call last):
772       ....
773   ValueError: NULL pointer access
774   >>>
775
776   >>> null_ptr[0] = 1234
806   3
807   >>>
808
809To set a POINTER type field to ``NULL``, you can assign ``None``::
810
811   >>> bar.values = None
812   >>>
813
n814-XXX list other conversions...
n818+.. XXX list other conversions...
815
n816-Sometimes you have instances of incompatible types.  In ``C``, you can cast one
n820+Sometimes you have instances of incompatible types.  In C, you can cast one
817type into another type.  ``ctypes`` provides a ``cast`` function which can be
818used in the same way.  The ``Bar`` structure defined above accepts
819``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
820but not instances of other types::
821
822   >>> bar.values = (c_byte * 4)()
823   Traceback (most recent call last):
824     File "<stdin>", line 1, in ?
899   >>> c1.next = pointer(c2)
900   >>> c2.next = pointer(c1)
901   >>> p = c1
902   >>> for i in range(8):
903   ...     print p.name,
904   ...     p = p.next[0]
905   ...
906   foo bar foo bar foo bar foo bar
n907-   >>>    
n911+   >>>
908
909
910.. _ctypes-callback-functions:
911
912Callback functions
913^^^^^^^^^^^^^^^^^^
914
915``ctypes`` allows to create C callable function pointers from Python callables.
1046   py_cmp_func 7 33
1047   py_cmp_func 1 7
1048   py_cmp_func 5 7
1049   >>>
1050
1051It is quite interesting to see that the Windows :func:`qsort` function needs
1052more comparisons than the linux version!
1053
n1054-As we can easily check, our array sorted now::
n1058+As we can easily check, our array is sorted now::
1055
1056   >>> for i in ia: print i,
1057   ...
1058   1 5 7 33 99
1059   >>>
1060
1061**Important note for callback functions:**
1062
1065crashing your program when a callback is made.
1066
1067
1068.. _ctypes-accessing-values-exported-from-dlls:
1069
1070Accessing values exported from dlls
1071^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1072
n1073-Sometimes, a dll not only exports functions, it also exports variables. An
n1077+Some shared libraries not only export functions, they also export variables. An
1074example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
1075to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
1076startup.
1077
1078``ctypes`` can access values like this with the :meth:`in_dll` class methods of
n1079-the type.  *pythonapi* Ã¬s a predefined symbol giving access to the Python C
n1083+the type.  *pythonapi* is a predefined symbol giving access to the Python C
1080api::
1081
1082   >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
1083   >>> print opt_flag
1084   c_long(0)
1085   >>>
1086
1087If the interpreter would have been started with :option:`-O`, the sample would
1129   ...
1130   __hello__ 104
1131   __phello__ -104
1132   __phello__.spam 104
1133   None 0
1134   >>>
1135
1136The fact that standard Python has a frozen module and a frozen package
n1137-(indicated by the negative size member) is not wellknown, it is only used for
n1141+(indicated by the negative size member) is not well known, it is only used for
1138testing. Try it out with ``import __hello__`` for example.
1139
1140
1141.. _ctypes-surprises:
1142
1143Surprises
1144^^^^^^^^^
1145
1162   1 2 3 4
1163   >>> # now swap the two points
1164   >>> rc.a, rc.b = rc.b, rc.a
1165   >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1166   3 4 3 4
1167   >>>
1168
1169Hm. We certainly expected the last statement to print ``3 4 1 2``. What
n1170-happended? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
n1174+happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
1171
1172   >>> temp0, temp1 = rc.b, rc.a
1173   >>> rc.a = temp0
1174   >>> rc.b = temp1
1175   >>>
1176
1177Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1178the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1179contents of ``temp0`` into ``rc`` 's buffer.  This, in turn, changes the
1180contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1181the expected effect.
1182
n1183-Keep in mind that retrieving subobjects from Structure, Unions, and Arrays
n1187+Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1184-doesn't *copy* the subobject, instead it retrieves a wrapper object accessing
1188+doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
1185the root-object's underlying buffer.
1186
1187Another example that may behave different from what one would expect is this::
1188
1189   >>> s = c_char_p()
1190   >>> s.value = "abc def ghi"
1191   >>> s.value
1192   'abc def ghi'
1193   >>> s.value is s.value
1194   False
1195   >>>
1196
1197Why is it printing ``False``?  ctypes instances are objects containing a memory
n1198-block plus some descriptors accessing the contents of the memory.  Storing a
n1202+block plus some :term:`descriptor`\s accessing the contents of the memory.
1199-Python object in the memory block does not store the object itself, instead the
1203+Storing a Python object in the memory block does not store the object itself,
1200-``contents`` of the object is stored. Accessing the contents again constructs a
1204+instead the ``contents`` of the object is stored.  Accessing the contents again
1201-new Python each time!
1205+constructs a new Python object each time!
1202
1203
1204.. _ctypes-variable-sized-data-types:
1205
1206Variable-sized data types
1207^^^^^^^^^^^^^^^^^^^^^^^^^
1208
1209``ctypes`` provides some support for variable-sized arrays and structures (this
1241   IndexError: invalid index
1242   >>>
1243
1244Another way to use variable-sized data types with ``ctypes`` is to use the
1245dynamic nature of Python, and (re-)define the data type after the required size
1246is already known, on a case by case basis.
1247
1248
n1249-.. _ctypes-bugs-todo-non-implemented-things:
1250- 
1251-Bugs, ToDo and non-implemented things
1252-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1253- 
1254-Enumeration types are not implemented. You can do it easily yourself, using
1255-:class:`c_int` as the base class.
1256- 
1257-``long double`` is not implemented.
1258- 
1259-.. % Local Variables:
1260-.. % compile-command: "make.bat"
1261-.. % End:
1262- 
1263- 
1264.. _ctypes-ctypes-reference:
1265
1266ctypes reference
1267----------------
1268
1269
1270.. _ctypes-finding-shared-libraries:
1271
1280shared library the most recent should be loaded), while the ctypes library
1281loaders act like when a program is run, and call the runtime loader directly.
1282
1283The ``ctypes.util`` module provides a function which can help to determine the
1284library to load.
1285
1286
1287.. data:: find_library(name)
n1277+   :module: ctypes.util
1288   :noindex:
1289
1290   Try to find a library and return a pathname.  *name* is the library name without
1291   any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1292   is the form used for the posix linker option :option:`-l`).  If no library can
1293   be found, returns ``None``.
1294
n1295-The exact functionality is system dependend.
n1285+The exact functionality is system dependent.
1296
1297On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
1298and objdump) to find the library file.  It returns the filename of the library
n1299-file.  Here are sone examples::
n1289+file.  Here are some examples::
1300
1301   >>> from ctypes.util import find_library
1302   >>> find_library("m")
1303   'libm.so.6'
1304   >>> find_library("c")
1305   'libc.so.6'
1306   >>> find_library("bz2")
1307   'libbz2.so.1.0'
1308   >>>
1309
1310On OS X, ``find_library`` tries several predefined naming schemes and paths to
n1311-locate the library, and returns a full pathname if successfull::
n1301+locate the library, and returns a full pathname if successful::
1312
1313   >>> from ctypes.util import find_library
1314   >>> find_library("c")
1315   '/usr/lib/libc.dylib'
1316   >>> find_library("m")
1317   '/usr/lib/libm.dylib'
1318   >>> find_library("bz2")
1319   '/usr/lib/libbz2.dylib'
1334
1335Loading shared libraries
1336^^^^^^^^^^^^^^^^^^^^^^^^
1337
1338There are several ways to loaded shared libraries into the Python process.  One
1339way is to instantiate one of the following classes:
1340
1341
n1342-.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None)
n1332+.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1343
1344   Instances of this class represent loaded shared libraries. Functions in these
1345   libraries use the standard C calling convention, and are assumed to return
1346   ``int``.
1347
1348
n1349-.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None)
n1339+.. class:: OleDLL(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 the windows specific :class:`HRESULT` code.  :class:`HRESULT`
1354   values contain information specifying whether the function call failed or
1355   succeeded, together with additional error code.  If the return value signals a
1356   failure, an :class:`WindowsError` is automatically raised.
1357
1358
n1359-.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None)
n1349+.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1360
1361   Windows only: Instances of this class represent loaded shared libraries,
1362   functions in these libraries use the ``stdcall`` calling convention, and are
1363   assumed to return ``int`` by default.
1364
1365   On Windows CE only the standard calling convention is used, for convenience the
1366   :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1367   platform.
1368
n1369-The Python GIL is released before calling any function exported by these
n1359+The Python :term:`global interpreter lock` is released before calling any
1370-libraries, and reaquired afterwards.
1360+function exported by these libraries, and reacquired afterwards.
1371
1372
1373.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1374
1375   Instances of this class behave like :class:`CDLL` instances, except that the
1376   Python GIL is *not* released during the function call, and after the function
1377   execution the Python error flag is checked. If the error flag is set, a Python
1378   exception is raised.
1379
1380   Thus, this is only useful to call Python C api functions directly.
1381
1382All these classes can be instantiated by calling them with at least one
1383argument, the pathname of the shared library.  If you have an existing handle to
n1384-an already loaded shard library, it can be passed as the ``handle`` named
n1374+an already loaded shared library, it can be passed as the ``handle`` named
1385parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
1386function is used to load the library into the process, and to get a handle to
1387it.
1388
1389The *mode* parameter can be used to specify how the library is loaded.  For
1390details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
1391
n1382+The *use_errno* parameter, when set to True, enables a ctypes mechanism that
1383+allows 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`
1385+variable; 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
1387+copy, the same happens immediately after the function call.
1388+ 
1389+The function :func:`ctypes.get_errno` returns the value of the ctypes private
1390+copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1391+to a new value and returns the former value.
1392+ 
1393+The *use_last_error* parameter, when set to True, enables the same mechanism for
1394+the 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
1397+copy of the windows error code.
1398+ 
1399+.. versionadded:: 2.6
1400+   The ``use_last_error`` and ``use_errno`` optional parameters
1401+   were added.
1392
1393.. data:: RTLD_GLOBAL
1394   :noindex:
1395
1396   Flag to use as *mode* parameter.  On platforms where this flag is not available,
1397   it is defined as the integer zero.
1398
1399
1406
1407.. data:: DEFAULT_MODE
1408   :noindex:
1409
1410   The default mode which is used to load shared libraries.  On OSX 10.3, this is
1411   *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1412
1413Instances of these classes have no public methods, however :meth:`__getattr__`
n1414-and :meth:`__getitem__` have special behaviour: functions exported by the shared
n1424+and :meth:`__getitem__` have special behavior: functions exported by the shared
1415library can be accessed as attributes of by index.  Please note that both
1416:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1417repeatedly returns the same object each time.
1418
1419The following public attributes are available, their name starts with an
1420underscore to not clash with exported function names:
1421
1422
1423.. attribute:: PyDLL._handle
1424
1425   The system handle used to access the library.
1426
1427
1428.. attribute:: PyDLL._name
1429
n1430-   The name of the library passed in the contructor.
n1440+   The name of the library passed in the constructor.
1431
1432Shared libraries can also be loaded by using one of the prefabricated objects,
1433which are instances of the :class:`LibraryLoader` class, either by calling the
1434:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1435loader instance.
1436
1437
1438.. class:: LibraryLoader(dlltype)
1439
1440   Class which loads shared libraries.  ``dlltype`` should be one of the
1441   :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1442
n1443-   :meth:`__getattr__` has special behaviour: It allows to load a shared library by
n1453+   :meth:`__getattr__` has special behavior: It allows to load a shared library by
1444   accessing it as attribute of a library loader instance.  The result is cached,
1445   so repeated attribute accesses return the same library each time.
1446
1447
n1448-.. method:: LibraryLoader.LoadLibrary(name)
n1458+   .. method:: LoadLibrary(name)
1449
n1450-   Load a shared library into the process and return it.  This method always
n1460+      Load a shared library into the process and return it.  This method always
1451-   returns a new instance of the library.
1461+      returns a new instance of the library.
1452
1453These prefabricated library loaders are available:
1454
1455
1456.. data:: cdll
1457   :noindex:
1458
1459   Creates :class:`CDLL` instances.
1500arguments, and return the default result type specified by the library loader.
1501They are instances of a private class:
1502
1503
1504.. class:: _FuncPtr
1505
1506   Base class for C callable foreign functions.
1507
n1508-Instances of foreign functions are also C compatible data types; they represent
n1518+   Instances of foreign functions are also C compatible data types; they
1509-C function pointers.
1519+   represent C function pointers.
1510
n1511-This behaviour can be customized by assigning to special attributes of the
n1521+   This behavior can be customized by assigning to special attributes of the
1512-foreign function object.
1522+   foreign function object.
1513
1514
n1515-.. attribute:: _FuncPtr.restype
n1525+   .. attribute:: restype
1516
n1517-   Assign a ctypes type to specify the result type of the foreign function.  Use
n1527+      Assign a ctypes type to specify the result type of the foreign function.
1518-   ``None`` for ``void`` a function not returning anything.
1528+      Use ``None`` for ``void`` a function not returning anything.
1519
n1520-   It is possible to assign a callable Python object that is not a ctypes type, in
n1530+      It is possible to assign a callable Python object that is not a ctypes
1521-   this case the function is assumed to return a C ``int``, and the callable will
1531+      type, in this case the function is assumed to return a C ``int``, and the
1522-   be called with this integer, allowing to do further processing or error
1532+      callable will be called with this integer, allowing to do further
1523-   checking.  Using this is deprecated, for more flexible postprocessing or error
1533+      processing or error checking.  Using this is deprecated, for more flexible
1524-   checking use a ctypes data type as :attr:`restype` and assign a callable to the
1534+      post processing or error checking use a ctypes data type as
1525-   :attr:`errcheck` attribute.
1535+      :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
1526
1527
n1528-.. attribute:: _FuncPtr.argtypes
n1538+   .. attribute:: argtypes
1529
n1530-   Assign a tuple of ctypes types to specify the argument types that the function
n1540+      Assign a tuple of ctypes types to specify the argument types that the
1531-   accepts.  Functions using the ``stdcall`` calling convention can only be called
1541+      function accepts.  Functions using the ``stdcall`` calling convention can
1532-   with the same number of arguments as the length of this tuple; functions using
1542+      only be called with the same number of arguments as the length of this
1533-   the C calling convention accept additional, unspecified arguments as well.
1543+      tuple; functions using the C calling convention accept additional,
1544+      unspecified arguments as well.
1534
n1535-   When a foreign function is called, each actual argument is passed to the
n1546+      When a foreign function is called, each actual argument is passed to the
1536-   :meth:`from_param` class method of the items in the :attr:`argtypes` tuple, this
1547+      :meth:`from_param` class method of the items in the :attr:`argtypes`
1537-   method allows to adapt the actual argument to an object that the foreign
1548+      tuple, this method allows to adapt the actual argument to an object that
1538-   function accepts.  For example, a :class:`c_char_p` item in the :attr:`argtypes`
1549+      the foreign function accepts.  For example, a :class:`c_char_p` item in
1539-   tuple will convert a unicode string passed as argument into an byte string using
1550+      the :attr:`argtypes` tuple will convert a unicode string passed as
1540-   ctypes conversion rules.
1551+      argument into an byte string using ctypes conversion rules.
1541
n1542-   New: It is now possible to put items in argtypes which are not ctypes types, but
n1553+      New: It is now possible to put items in argtypes which are not ctypes
1543-   each item must have a :meth:`from_param` method which returns a value usable as
1554+      types, but each item must have a :meth:`from_param` method which returns a
1544-   argument (integer, string, ctypes instance).  This allows to define adapters
1555+      value usable as argument (integer, string, ctypes instance).  This allows
1545-   that can adapt custom objects as function parameters.
1556+      to define adapters that can adapt custom objects as function parameters.
1546
1547
n1548-.. attribute:: _FuncPtr.errcheck
n1559+   .. attribute:: errcheck
1549
n1550-   Assign a Python function or another callable to this attribute. The callable
n1561+      Assign a Python function or another callable to this attribute. The
1551-   will be called with three or more arguments:
1562+      callable will be called with three or more arguments:
1552
n1553- 
1554-.. function:: callable(result, func, arguments)
1564+      .. function:: callable(result, func, arguments)
1555-   :noindex:
1565+         :noindex:
1556
n1557-   ``result`` is what the foreign function returns, as specified by the
n1567+         ``result`` is what the foreign function returns, as specified
1558-   :attr:`restype` attribute.
1568+         by the :attr:`restype` attribute.
1559
n1560-   ``func`` is the foreign function object itself, this allows to reuse the same
n1570+         ``func`` is the foreign function object itself, this allows
1561-   callable object to check or postprocess the results of several functions.
1571+         to reuse the same callable object to check or post process
1572+         the results of several functions.
1562
n1563-   ``arguments`` is a tuple containing the parameters originally passed to the
n1574+         ``arguments`` is a tuple containing the parameters originally
1564-   function call, this allows to specialize the behaviour on the arguments used.
1575+         passed to the function call, this allows to specialize the
1576+         behavior on the arguments used.
1565
n1566-   The object that this function returns will be returned from the foreign function
n1578+      The object that this function returns will be returned from the
1567-   call, but it can also check the result value and raise an exception if the
1579+      foreign function call, but it can also check the result value
1568-   foreign function call failed.
1580+      and raise an exception if the foreign function call failed.
1569
1570
1571.. exception:: ArgumentError()
1572
1573   This exception is raised when a foreign function call cannot convert one of the
1574   passed arguments.
1575
1576
1581
1582Foreign functions can also be created by instantiating function prototypes.
1583Function prototypes are similar to function prototypes in C; they describe a
1584function (return type, argument types, calling convention) without defining an
1585implementation.  The factory functions must be called with the desired result
1586type and the argument types of the function.
1587
1588
n1589-.. function:: CFUNCTYPE(restype, *argtypes)
n1601+.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1590
1591   The returned function prototype creates functions that use the standard C
n1592-   calling convention.  The function will release the GIL during the call.
n1604+   calling convention.  The function will release the GIL during the call.  If
1605+   *use_errno* is set to True, the ctypes private copy of the system
1606+   :data:`errno` variable is exchanged with the real :data:`errno` value bafore
1607+   and after the call; *use_last_error* does the same for the Windows error
1608+   code.
1593
n1610+   .. versionchanged:: 2.6
1611+      The optional *use_errno* and *use_last_error* parameters were added.
1594
n1595-.. function:: WINFUNCTYPE(restype, *argtypes)
n1613+ 
1614+.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1596
1597   Windows only: The returned function prototype creates functions that use the
n1598-   ``stdcall`` calling convention, except on Windows CE where :func:`WINFUNCTYPE`
n1617+   ``stdcall`` calling convention, except on Windows CE where
1599-   is the same as :func:`CFUNCTYPE`.  The function will release the GIL during the
1618+   :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`.  The function will
1600-   call.
1619+   release the GIL during the call.  *use_errno* and *use_last_error* have the
1620+   same meaning as above.
1601
1602
1603.. function:: PYFUNCTYPE(restype, *argtypes)
1604
1605   The returned function prototype creates functions that use the Python calling
1606   convention.  The function will *not* release the GIL during the call.
1607
n1608-Function prototypes created by the factory functions can be instantiated in
n1628+Function prototypes created by these factory functions can be instantiated in
1609-different ways, depending on the type and number of the parameters in the call.
1629+different ways, depending on the type and number of the parameters in the call:
1610
1611
n1612-.. function:: prototype(address)
n1632+   .. function:: prototype(address)
1613-   :noindex:
1633+      :noindex:
1634+      :module:
1614
n1615-   Returns a foreign function at the specified address.
n1636+      Returns a foreign function at the specified address which must be an integer.
1616
1617
n1618-.. function:: prototype(callable)
n1639+   .. function:: prototype(callable)
1619-   :noindex:
1640+      :noindex:
1641+      :module:
1620
n1621-   Create a C callable function (a callback function) from a Python ``callable``.
n1643+      Create a C callable function (a callback function) from a Python ``callable``.
1622
1623
n1624-.. function:: prototype(func_spec[, paramflags])
n1646+   .. function:: prototype(func_spec[, paramflags])
1625-   :noindex:
1647+      :noindex:
1648+      :module:
1626
n1627-   Returns a foreign function exported by a shared library. ``func_spec`` must be a
n1650+      Returns a foreign function exported by a shared library. ``func_spec`` must be a
1628-   2-tuple ``(name_or_ordinal, library)``. The first item is the name of the
1651+      2-tuple ``(name_or_ordinal, library)``. The first item is the name of the
1629-   exported function as string, or the ordinal of the exported function as small
1652+      exported function as string, or the ordinal of the exported function as small
1630-   integer.  The second item is the shared library instance.
1653+      integer.  The second item is the shared library instance.
1631
1632
n1633-.. function:: prototype(vtbl_index, name[, paramflags[, iid]])
n1656+   .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1634-   :noindex:
1657+      :noindex:
1658+      :module:
1635
n1636-   Returns a foreign function that will call a COM method. ``vtbl_index`` is the
n1660+      Returns a foreign function that will call a COM method. ``vtbl_index`` is the
1637-   index into the virtual function table, a small nonnegative integer. *name* is
1661+      index into the virtual function table, a small non-negative integer. *name* is
1638-   name of the COM method. *iid* is an optional pointer to the interface identifier
1662+      name of the COM method. *iid* is an optional pointer to the interface identifier
1639-   which is used in extended error reporting.
1663+      which is used in extended error reporting.
1640
n1641-   COM methods use a special calling convention: They require a pointer to the COM
n1665+      COM methods use a special calling convention: They require a pointer to the COM
1642-   interface as first argument, in addition to those parameters that are specified
1666+      interface as first argument, in addition to those parameters that are specified
1643-   in the :attr:`argtypes` tuple.
1667+      in the :attr:`argtypes` tuple.
1644
n1645-The optional *paramflags* parameter creates foreign function wrappers with much
n1669+   The optional *paramflags* parameter creates foreign function wrappers with much
1646-more functionality than the features described above.
1670+   more functionality than the features described above.
1647
n1648-*paramflags* must be a tuple of the same length as :attr:`argtypes`.
n1672+   *paramflags* must be a tuple of the same length as :attr:`argtypes`.
1649
n1650-Each item in this tuple contains further information about a parameter, it must
n1674+   Each item in this tuple contains further information about a parameter, it must
1651-be a tuple containing 12, or 3 items.
1675+   be a tuple containing onetwo, or three items.
1652
n1653-The first item is an integer containing flags for the parameter:
n1677+   The first item is an integer containing a combination of direction
1678+   flags for the parameter:
1654
n1655- 
n1680+      1
1656-.. data:: 1
1657-   :noindex:
1658- 
1659-   Specifies an input parameter to the function.
1681+         Specifies an input parameter to the function.
1660
n1661- 
n1683+      2
1662-.. data:: 2
1663-   :noindex:
1664- 
1665-   Output parameter.  The foreign function fills in a value.
1684+         Output parameter.  The foreign function fills in a value.
1666
n1667- 
n1686+      4
1668-.. data:: 4
1669-   :noindex:
1670- 
1671-   Input parameter which defaults to the integer zero.
1687+         Input parameter which defaults to the integer zero.
1672
n1673-The optional second item is the parameter name as string.  If this is specified,
n1689+   The optional second item is the parameter name as string.  If this is specified,
1674-the foreign function can be called with named parameters.
1690+   the foreign function can be called with named parameters.
1675
n1676-The optional third item is the default value for this parameter.
n1692+   The optional third item is the default value for this parameter.
1677
1678This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
1679that it supports default parameters and named arguments. The C declaration from
1680the windows header file is this::
1681
1682   WINUSERAPI int WINAPI
1683   MessageBoxA(
1684       HWND hWnd ,
1685       LPCSTR lpText,
1686       LPCSTR lpCaption,
1687       UINT uType);
1688
n1689-Here is the wrapping with ``ctypes``:
n1705+Here is the wrapping with ``ctypes``::
1690
n1691-   ::
1692- 
1693-      >>> from ctypes import c_int, WINFUNCTYPE, windll
1707+   >>> from ctypes import c_int, WINFUNCTYPE, windll
1694-      >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1708+   >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1695-      >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, c_uint)
1709+   >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
1696-      >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1710+   >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1697-      >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1711+   >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1698-      >>>
1712+   >>>
1699
1700The MessageBox foreign function can now be called in these ways::
1701
1702   >>> MessageBox()
1703   >>> MessageBox(text="Spam, spam, spam")
1704   >>> MessageBox(flags=2, text="foo bar")
1705   >>>
1706
1708function retrieves the dimensions of a specified window by copying them into
1709``RECT`` structure that the caller has to supply.  Here is the C declaration::
1710
1711   WINUSERAPI BOOL WINAPI
1712   GetWindowRect(
1713        HWND hWnd,
1714        LPRECT lpRect);
1715
n1716-Here is the wrapping with ``ctypes``:
n1730+Here is the wrapping with ``ctypes``::
1717
n1718-   ::
1719- 
1720-      >>> from ctypes import POINTER, WINFUNCTYPE, windll
1732+   >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1721-      >>> from ctypes.wintypes import BOOL, HWND, RECT
1733+   >>> from ctypes.wintypes import BOOL, HWND, RECT
1722-      >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1734+   >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1723-      >>> paramflags = (1, "hwnd"), (2, "lprect")
1735+   >>> paramflags = (1, "hwnd"), (2, "lprect")
1724-      >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1736+   >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1725-      >>>
1737+   >>>
1726
1727Functions with output parameters will automatically return the output parameter
1728value if there is a single one, or a tuple containing the output parameter
1729values when there are more than one, so the GetWindowRect function now returns a
1730RECT instance, when called.
1731
1732Output parameters can be combined with the :attr:`errcheck` protocol to do
1733further output processing and error checking.  The win32 ``GetWindowRect`` api
1734function returns a ``BOOL`` to signal success or failure, so this function could
1735do the error checking, and raises an exception when the api call failed::
1736
1737   >>> def errcheck(result, func, args):
1738   ...     if not result:
1739   ...         raise WinError()
1740   ...     return args
n1753+   ...
1741   >>> GetWindowRect.errcheck = errcheck
1742   >>>
1743
1744If the :attr:`errcheck` function returns the argument tuple it receives
1745unchanged, ``ctypes`` continues the normal processing it does on the output
1746parameters.  If you want to return a tuple of window coordinates instead of a
1747``RECT`` instance, you can retrieve the fields in the function and return them
1748instead, the normal processing will no longer take place::
1749
1750   >>> def errcheck(result, func, args):
1751   ...     if not result:
1752   ...         raise WinError()
1753   ...     rc = args[1]
1754   ...     return rc.left, rc.top, rc.bottom, rc.right
n1755-   >>>
n1768+   ...
1756   >>> GetWindowRect.errcheck = errcheck
1757   >>>
1758
1759
1760.. _ctypes-utility-functions:
1761
1762Utility functions
1763^^^^^^^^^^^^^^^^^
1770
1771
1772.. function:: alignment(obj_or_type)
1773
1774   Returns the alignment requirements of a ctypes type. ``obj_or_type`` must be a
1775   ctypes type or instance.
1776
1777
n1778-.. function:: byref(obj)
n1791+.. function:: byref(obj[, offset])
1779
n1780-   Returns a light-weight pointer to ``obj``, which must be an instance of a ctypes
n1793+   Returns a light-weight pointer to ``obj``, which must be an
1794+   instance of a ctypes type.  ``offset`` defaults to zero, and must be
1795+   an integer that will be added to the internal pointer value.
1796+ 
1797+   ``byref(obj, offset)`` corresponds to this C code::
1798+ 
1799+      (((char *)&obj) + offset)
1800+ 
1781-   type. The returned object can only be used as a foreign function call parameter.
1801+   The returned object can only be used as a foreign function call
1782-   It behaves similar to ``pointer(obj)``, but the construction is a lot faster.
1802+   parameter.  It behaves similar to ``pointer(obj)``, but the
1803+   construction is a lot faster.
1783
n1805+   .. versionadded:: 2.6
1806+      The ``offset`` optional argument was added.
1784
1785.. function:: cast(obj, type)
1786
1787   This function is similar to the cast operator in C. It returns a new instance of
1788   ``type`` which points to the same memory block as ``obj``. ``type`` must be a
1789   pointer type, and ``obj`` must be an object that can be interpreted as a
1790   pointer.
1791
1822   be used.
1823
1824   If the first parameter is a 8-bit string, it is converted into an unicode string
1825   according to ctypes conversion rules.
1826
1827
1828.. function:: DllCanUnloadNow()
1829
n1830-   Windows only: This function is a hook which allows to implement inprocess COM
n1853+   Windows only: This function is a hook which allows to implement in-process COM
1831   servers with ctypes. It is called from the DllCanUnloadNow function that the
1832   _ctypes extension dll exports.
1833
1834
1835.. function:: DllGetClassObject()
1836
n1837-   Windows only: This function is a hook which allows to implement inprocess COM
n1860+   Windows only: This function is a hook which allows to implement in-process COM
1838   servers with ctypes. It is called from the DllGetClassObject function that the
1839   ``_ctypes`` extension dll exports.
1840
n1864+.. function:: find_library(name)
1865+   :module: ctypes.util
1866+ 
1867+   Try to find a library and return a pathname.  *name* is the library name
1868+   without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
1869+   number (this is the form used for the posix linker option :option:`-l`).  If
1870+   no library can be found, returns ``None``.
1871+ 
1872+   The exact functionality is system dependent.
1873+ 
1874+   .. versionchanged:: 2.6
1875+      Windows only: ``find_library("m")`` or
1876+      ``find_library("c")`` return the result of a call to
1877+      ``find_msvcrt()``.
1878+ 
1879+.. function:: find_msvcrt()
1880+   :module: ctypes.util
1881+ 
1882+   Windows only: return the filename of the VC runtype library used
1883+   by Python, and by the extension modules.  If the name of the
1884+   library cannot be determined, ``None`` is returned.
1885+ 
1886+   If you need to free memory, for example, allocated by an extension
1887+   module with a call to the ``free(void *)``, it is important that you
1888+   use the function in the same library that allocated the memory.
1889+ 
1890+   .. versionadded:: 2.6
1841
1842.. function:: FormatError([code])
1843
1844   Windows only: Returns a textual description of the error code. If no error code
1845   is specified, the last error code is used by calling the Windows api function
1846   GetLastError.
1847
1848
1849.. function:: GetLastError()
1850
1851   Windows only: Returns the last error code set by Windows in the calling thread.
n1902+   This function calls the Windows `GetLastError()` function directly,
1903+   it does not return the ctypes-private copy of the error code.
1852
n1905+.. function:: get_errno()
1906+ 
1907+   Returns the current value of the ctypes-private copy of the system
1908+   :data:`errno` variable in the calling thread.
1909+ 
1910+   .. versionadded:: 2.6
1911+ 
1912+.. function:: get_last_error()
1913+ 
1914+   Windows only: returns the current value of the ctypes-private copy of the system
1915+   :data:`LastError` variable in the calling thread.
1916+ 
1917+   .. versionadded:: 2.6
1853
1854.. function:: memmove(dst, src, count)
1855
1856   Same as the standard C memmove library function: copies *count* bytes from
1857   ``src`` to *dst*. *dst* and ``src`` must be integers or ctypes instances that
1858   can be converted to pointers.
1859
1860
1897   error handling on encoding/decoding errors. Examples of possible values are
1898   ``"strict"``, ``"replace"``, or ``"ignore"``.
1899
1900   ``set_conversion_mode`` returns a 2-tuple containing the previous conversion
1901   rules. On windows, the initial conversion rules are ``('mbcs', 'ignore')``, on
1902   other systems ``('ascii', 'strict')``.
1903
1904
n1970+.. function:: set_errno(value)
1971+ 
1972+   Set the current value of the ctypes-private copy of the system :data:`errno`
1973+   variable in the calling thread to *value* and return the previous value.
1974+ 
1975+   .. versionadded:: 2.6
1976+ 
1977+.. function:: set_last_error(value)
1978+ 
1979+   Windows only: set the current value of the ctypes-private copy of the system
1980+   :data:`LastError` variable in the calling thread to *value* and return the
1981+   previous value.
1982+ 
1983+   .. versionadded:: 2.6
1984+ 
1905.. function:: sizeof(obj_or_type)
1906
1907   Returns the size in bytes of a ctypes type or instance memory buffer. Does the
1908   same as the C ``sizeof()`` function.
1909
1910
1911.. function:: string_at(address[, size])
1912
n1913-   This function returns the string starting at memory address address. If size is
n1993+   This function returns the string starting at memory address address. If size
1914-   specified, it is used as size, otherwise the string is assumed to be zero-
1994+   is specified, it is used as size, otherwise the string is assumed to be
1915-   terminated.
1995+   zero-terminated.
1916
1917
1918.. function:: WinError(code=None, descr=None)
1919
1920   Windows only: this function is probably the worst-named thing in ctypes. It
1921   creates an instance of WindowsError. If *code* is not specified,
1922   ``GetLastError`` is called to determine the error code. If ``descr`` is not
n1923-   spcified, :func:`FormatError` is called to get a textual description of the
n2003+   specified, :func:`FormatError` is called to get a textual description of the
1924   error.
1925
1926
1927.. function:: wstring_at(address)
1928
1929   This function returns the wide character string starting at memory address
1930   ``address`` as unicode string. If ``size`` is specified, it is used as the
n1931-   number of characters of the string, otherwise the string is assumed to be zero-
n2011+   number of characters of the string, otherwise the string is assumed to be
1932-   terminated.
2012+   zero-terminated.
1933
1934
1935.. _ctypes-data-types:
1936
1937Data types
1938^^^^^^^^^^
1939
1940
1942
1943   This non-public class is the common base class of all ctypes data types.  Among
1944   other things, all ctypes type instances contain a memory block that hold C
1945   compatible data; the address of the memory block is returned by the
1946   ``addressof()`` helper function. Another instance variable is exposed as
1947   :attr:`_objects`; this contains other Python objects that need to be kept alive
1948   in case the memory block contains pointers.
1949
n1950-Common methods of ctypes data types, these are all class methods (to be exact,
n2030+   Common methods of ctypes data types, these are all class methods (to be
1951-they are methods of the metaclass):
2031+   exact, they are methods of the :term:`metaclass`):
1952
1953
n2034+   .. method:: _CData.from_buffer(source[, offset])
2035+ 
2036+      This method returns a ctypes instance that shares the buffer of
2037+      the ``source`` object.  The ``source`` object must support the
2038+      writeable buffer interface.  The optional ``offset`` parameter
2039+      specifies an offset into the source buffer in bytes; the default
2040+      is zero.  If the source buffer is not large enough a ValueError
2041+      is raised.
2042+ 
2043+      .. versionadded:: 2.6
2044+ 
2045+   .. method:: _CData.from_buffer_copy(source[, offset])
2046+ 
2047+      This method creates a ctypes instance, copying the buffer from
2048+      the source object buffer which must be readable.  The optional
2049+      ``offset`` parameter specifies an offset into the source buffer
2050+      in bytes; the default is zero.  If the source buffer is not
2051+      large enough a ValueError is raised.
2052+ 
2053+      .. versionadded:: 2.6
2054+ 
2055+ 
1954-.. method:: _CData.from_address(address)
2056+   .. method:: from_address(address)
1955
n1956-   This method returns a ctypes type instance using the memory specified by address
n2058+      This method returns a ctypes type instance using the memory specified by
1957-   which must be an integer.
2059+      address which must be an integer.
1958
1959
n1960-.. method:: _CData.from_param(obj)
n2062+   .. method:: from_param(obj)
1961
n1962-   This method adapts obj to a ctypes type.  It is called with the actual object
n2064+      This method adapts *obj* to a ctypes type.  It is called with the actual
1963-   used in a foreign function call, when the type is present in the foreign
2065+      object used in a foreign function call when the type is present in the
1964-   functions :attr:`argtypes` tuple; it must return an object that can be used as
2066+      foreign function's :attr:`argtypes` tuple; it must return an object that
1965-   function call parameter.
2067+      can be used as a function call parameter.
1966
n1967-   All ctypes data types have a default implementation of this classmethod,
n2069+      All ctypes data types have a default implementation of this classmethod
1968-   normally it returns ``obj`` if that is an instance of the type.  Some types
2070+      that normally returns ``obj`` if that is an instance of the type.  Some
1969-   accept other objects as well.
2071+      types accept other objects as well.
1970
1971
n1972-.. method:: _CData.in_dll(name, library)
n2074+   .. method:: in_dll(library, name)
1973
n1974-   This method returns a ctypes type instance exported by a shared library. *name*
n2076+      This method returns a ctypes type instance exported by a shared
1975-   is the name of the symbol that exports the data, ``library`` is the loaded
2077+      library. *name* is the name of the symbol that exports the data, *library*
1976-   shared library.
2078+      is the loaded shared library.
1977
n2080+ 
1978-Common instance variables of ctypes data types:
2081+   Common instance variables of ctypes data types:
1979
1980
n1981-.. attribute:: _CData._b_base_
n2084+   .. attribute:: _b_base_
1982
n1983-   Sometimes ctypes data instances do not own the memory block they contain,
n2086+      Sometimes ctypes data instances do not own the memory block they contain,
1984-   instead they share part of the memory block of a base object.  The
2087+      instead they share part of the memory block of a base object.  The
1985-   :attr:`_b_base_` readonly member is the root ctypes object that owns the memory
2088+      :attr:`_b_base_` read-only member is the root ctypes object that owns the
1986-   block.
2089+      memory block.
1987
1988
n1989-.. attribute:: _CData._b_needsfree_
n2092+   .. attribute:: _b_needsfree_
1990
n1991-   This readonly variable is true when the ctypes data instance has allocated the
n2094+      This read-only variable is true when the ctypes data instance has
1992-   memory block itself, false otherwise.
2095+      allocated the memory block itself, false otherwise.
1993
1994
n1995-.. attribute:: _CData._objects
n2098+   .. attribute:: _objects
1996
n1997-   This member is either ``None`` or a dictionary containing Python objects that
n2100+      This member is either ``None`` or a dictionary containing Python objects
1998-   need to be kept alive so that the memory block contents is kept valid.  This
2101+      that need to be kept alive so that the memory block contents is kept
1999-   object is only exposed for debugging; never modify the contents of this
2102+      valid.  This object is only exposed for debugging; never modify the
2000-   dictionary.
2103+      contents of this dictionary.
2001
2002
n2003-.. _ctypes-fundamental-data-types:
n2106+.. _ctypes-fundamental-data-types-2:
2004
2005Fundamental data types
2006^^^^^^^^^^^^^^^^^^^^^^
2007
2008
2009.. class:: _SimpleCData
2010
2011   This non-public class is the base class of all fundamental ctypes data types. It
2012   is mentioned here because it contains the common attributes of the fundamental
2013   ctypes data types.  ``_SimpleCData`` is a subclass of ``_CData``, so it inherits
2014   their methods and attributes.
2015
n2119+   .. versionchanged:: 2.6
2120+      ctypes data types that are not and do not contain pointers can
2121+      now be pickled.
2122+ 
2016-Instances have a single attribute:
2123+   Instances have a single attribute:
2017
2018
n2019-.. attribute:: _SimpleCData.value
n2126+   .. attribute:: value
2020
n2021-   This attribute contains the actual value of the instance. For integer and
n2128+      This attribute contains the actual value of the instance. For integer and
2022-   pointer types, it is an integer, for character types, it is a single character
2129+      pointer types, it is an integer, for character types, it is a single
2023-   string, for character pointer types it is a Python string or unicode string.
2130+      character string, for character pointer types it is a Python string or
2131+      unicode string.
2024
n2025-   When the ``value`` attribute is retrieved from a ctypes instance, usually a new
n2133+      When the ``value`` attribute is retrieved from a ctypes instance, usually
2026-   object is returned each time.  ``ctypes`` does *not* implement original object
2134+      a new object is returned each time.  ``ctypes`` does *not* implement
2027-   return, always a new object is constructed.  The same is true for all other
2135+      original object return, always a new object is constructed.  The same is
2028-   ctypes object instances.
2136+      true for all other ctypes object instances.
2029
2030Fundamental data types, when returned as foreign function call results, or, for
2031example, by retrieving structure field members or array items, are transparently
2032converted to native Python types.  In other words, if a foreign function has a
2033:attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
2034*not* a :class:`c_char_p` instance.
2035
n2036-Subclasses of fundamental data types do *not* inherit this behaviour. So, if a
n2144+Subclasses of fundamental data types do *not* inherit this behavior. So, if a
2037foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2038receive an instance of this subclass from the function call. Of course, you can
2039get the value of the pointer by accessing the ``value`` attribute.
2040
2041These are the fundamental ctypes data types:
2042
2043
2044.. class:: c_byte
2062
2063
2064.. class:: c_double
2065
2066   Represents the C double datatype. The constructor accepts an optional float
2067   initializer.
2068
2069
n2178+.. class:: c_longdouble
2179+ 
2180+   Represents the C long double datatype. The constructor accepts an
2181+   optional float initializer.  On platforms where ``sizeof(long
2182+   double) == sizeof(double)`` it is an alias to :class:`c_double`.
2183+ 
2184+   .. versionadded:: 2.6
2185+ 
2070.. class:: c_float
2071
n2072-   Represents the C double datatype. The constructor accepts an optional float
n2188+   Represents the C float datatype. The constructor accepts an optional float
2073   initializer.
2074
2075
2076.. class:: c_int
2077
2078   Represents the C signed int datatype. The constructor accepts an optional
2079   integer initializer; no overflow checking is done. On platforms where
2080   ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
2193
2194   Represents the C ``wchar_t`` datatype, and interprets the value as a single
2195   character unicode string. The constructor accepts an optional string
2196   initializer, the length of the string must be exactly one character.
2197
2198
2199.. class:: c_wchar_p
2200
n2201-   Represents the C ``wchar_t *`` datatype, which must be a pointer to a zero-
n2317+   Represents the C ``wchar_t *`` datatype, which must be a pointer to a
2202-   terminated wide character string. The constructor accepts an integer address, or
2318+   zero-terminated wide character string. The constructor accepts an integer
2203-   a string.
2319+   address, or a string.
2320+ 
2321+ 
2322+.. class:: c_bool
2323+ 
2324+   Represent the C ``bool`` datatype (more accurately, _Bool from C99). Its value
2325+   can be True or False, and the constructor accepts any object that has a truth
2326+   value.
2327+ 
2328+   .. versionadded:: 2.6
2204
2205
2206.. class:: HRESULT
2207
2208   Windows only: Represents a :class:`HRESULT` value, which contains success or
2209   error information for a function or method call.
2210
n2211-``py_object`` : classdesc\*
2212
n2337+.. class:: py_object
2338+ 
2213-   Represents the C ``PyObject *`` datatype.  Calling this with an without an
2339+   Represents the C ``PyObject *`` datatype.  Calling this without an argument
2214-   argument creates a ``NULL`` ``PyObject *`` pointer.
2340+   creates a ``NULL`` ``PyObject *`` pointer.
2215- 
2216
2217The ``ctypes.wintypes`` module provides quite some other Windows specific data
2218types, for example ``HWND``, ``WPARAM``, or ``DWORD``. Some useful structures
2219like ``MSG`` or ``RECT`` are also defined.
2220
2221
2222.. _ctypes-structured-data-types:
2223
2242Structures with non-native byte order cannot contain pointer type fields, or any
2243other data types containing pointer type fields.
2244
2245
2246.. class:: Structure(*args, **kw)
2247
2248   Abstract base class for structures in *native* byte order.
2249
n2250-Concrete structure and union types must be created by subclassing one of these
n2375+   Concrete structure and union types must be created by subclassing one of these
2251-types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
2376+   types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
2252-create descriptors which allow reading and writing the fields by direct
2377+   create :term:`descriptor`\s which allow reading and writing the fields by direct
2253-attribute accesses.  These are the
2378+   attribute accesses.  These are the
2254
2255
n2256-.. attribute:: Structure._fields_
n2381+   .. attribute:: _fields_
2257
n2258-   A sequence defining the structure fields.  The items must be 2-tuples or
n2383+      A sequence defining the structure fields.  The items must be 2-tuples or
2259-   3-tuples.  The first item is the name of the field, the second item specifies
2384+      3-tuples.  The first item is the name of the field, the second item
2260-   the type of the field; it can be any ctypes data type.
2385+      specifies the type of the field; it can be any ctypes data type.
2261
n2262-   For integer type fields like :class:`c_int`, a third optional item can be given.
n2387+      For integer type fields like :class:`c_int`, a third optional item can be
2263-   It must be a small positive integer defining the bit width of the field.
2388+      given.  It must be a small positive integer defining the bit width of the
2389+      field.
2264
n2265-   Field names must be unique within one structure or union.  This is not checked,
n2391+      Field names must be unique within one structure or union.  This is not
2266-   only one field can be accessed when names are repeated.
2392+      checked, only one field can be accessed when names are repeated.
2267
n2268-   It is possible to define the :attr:`_fields_` class variable *after* the class
n2394+      It is possible to define the :attr:`_fields_` class variable *after* the
2269-   statement that defines the Structure subclass, this allows to create data types
2395+      class statement that defines the Structure subclass, this allows to create
2270-   that directly or indirectly reference themselves::
2396+      data types that directly or indirectly reference themselves::
2271
n2272-      class List(Structure):
n2398+         class List(Structure):
2273-          pass
2399+             pass
2274-      List._fields_ = [("pnext", POINTER(List)),
2400+         List._fields_ = [("pnext", POINTER(List)),
2275-                       ...
2401+                          ...
2276-                      ]
2402+                         ]
2277
n2278-   The :attr:`_fields_` class variable must, however, be defined before the type is
n2404+      The :attr:`_fields_` class variable must, however, be defined before the
2279-   first used (an instance is created, ``sizeof()`` is called on it, and so on).
2405+      type is first used (an instance is created, ``sizeof()`` is called on it,
2280-   Later assignments to the :attr:`_fields_` class variable will raise an
2406+      and so on).  Later assignments to the :attr:`_fields_` class variable will
2281-   AttributeError.
2407+      raise an AttributeError.
2282
n2283-   Structure and union subclass constructors accept both positional and named
n2409+      Structure and union subclass constructors accept both positional and named
2284-   arguments.  Positional arguments are used to initialize the fields in the same
2410+      arguments.  Positional arguments are used to initialize the fields in the
2285-   order as they appear in the :attr:`_fields_` definition, named arguments are
2411+      same order as they appear in the :attr:`_fields_` definition, named
2286-   used to initialize the fields with the corresponding name.
2412+      arguments are used to initialize the fields with the corresponding name.
2287
n2288-   It is possible to defined sub-subclasses of structure types, they inherit the
n2414+      It is possible to defined sub-subclasses of structure types, they inherit
2289-   fields of the base class plus the :attr:`_fields_` defined in the sub-subclass,
2415+      the fields of the base class plus the :attr:`_fields_` defined in the
2290-   if any.
2416+      sub-subclass, if any.
2291
2292
n2293-.. attribute:: Structure._pack_
n2419+   .. attribute:: _pack_
2294
n2295-   An optional small integer that allows to override the alignment of structure
n2421+      An optional small integer that allows to override the alignment of
2296-   fields in the instance.  :attr:`_pack_` must already be defined when
2422+      structure fields in the instance.  :attr:`_pack_` must already be defined
2297-   :attr:`_fields_` is assigned, otherwise it will have no effect.
2423+      when :attr:`_fields_` is assigned, otherwise it will have no effect.
2298
2299
n2300-.. attribute:: Structure._anonymous_
n2426+   .. attribute:: _anonymous_
2301
n2302-   An optional sequence that lists the names of unnamed (anonymous) fields.
n2428+      An optional sequence that lists the names of unnamed (anonymous) fields.
2303-   ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
2429+      ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
2304-   otherwise it will have no effect.
2430+      otherwise it will have no effect.
2305
n2306-   The fields listed in this variable must be structure or union type fields.
n2432+      The fields listed in this variable must be structure or union type fields.
2307-   ``ctypes`` will create descriptors in the structure type that allows to access
2433+      ``ctypes`` will create descriptors in the structure type that allows to
2308-   the nested fields directly, without the need to create the structure or union
2434+      access the nested fields directly, without the need to create the
2309-   field.
2435+      structure or union field.
2310
n2311-   Here is an example type (Windows)::
n2437+      Here is an example type (Windows)::
2312
n2313-      class _U(Union):
n2439+         class _U(Union):
2314-          _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2440+             _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2315-                      ("lpadesc", POINTER(ARRAYDESC)),
2441+                         ("lpadesc", POINTER(ARRAYDESC)),
2316-                      ("hreftype", HREFTYPE)]
2442+                         ("hreftype", HREFTYPE)]
2317
n2318-      class TYPEDESC(Structure):
n2444+         class TYPEDESC(Structure):
2319-          _fields_ = [("u", _U),
2445+             _fields_ = [("u", _U),
2320-                      ("vt", VARTYPE)]
2446+                         ("vt", VARTYPE)]
2321
n2322-          _anonymous_ = ("u",)
n2448+             _anonymous_ = ("u",)
2323
n2324-   The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field specifies
n2450+      The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2325-   which one of the union fields is valid.  Since the ``u`` field is defined as
2451+      specifies which one of the union fields is valid.  Since the ``u`` field
2326-   anonymous field, it is now possible to access the members directly off the
2452+      is defined as anonymous field, it is now possible to access the members
2327-   TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` are equivalent, but the
2453+      directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2328-   former is faster since it does not need to create a temporary union instance::
2454+      are equivalent, but the former is faster since it does not need to create
2455+      a temporary union instance::
2329
n2330-      td = TYPEDESC()
n2457+         td = TYPEDESC()
2331-      td.vt = VT_PTR
2458+         td.vt = VT_PTR
2332-      td.lptdesc = POINTER(some_type)
2459+         td.lptdesc = POINTER(some_type)
2333-      td.u.lptdesc = POINTER(some_type)
2460+         td.u.lptdesc = POINTER(some_type)
2334
2335It is possible to defined sub-subclasses of structures, they inherit the fields
2336of the base class.  If the subclass definition has a separate :attr:`_fields_`
2337variable, the fields specified in this are appended to the fields of the base
2338class.
2339
2340Structure and union constructors accept both positional and keyword arguments.
2341Positional arguments are used to initialize member fields in the same order as
2345:attr:`_fields_`.
2346
2347
2348.. _ctypes-arrays-pointers:
2349
2350Arrays and pointers
2351^^^^^^^^^^^^^^^^^^^
2352
t2353-XXX
t2480+Not yet written - please see the sections :ref:`ctypes-pointers` and
2481+section :ref:`ctypes-arrays` in the tutorial.
2354
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op