Issue 2188: Documentation hint about disabling proxy detection.
[python.git] / Doc / library / ctypes.rst
blob52569a75927a74d59fe1033a19628e288d22ffab
2 :mod:`ctypes` --- A foreign function library for Python.
3 ========================================================
5 .. module:: ctypes
6    :synopsis: A foreign function library for Python.
7 .. moduleauthor:: Thomas Heller <theller@python.net>
10 .. versionadded:: 2.5
12 ``ctypes`` is a foreign function library for Python.  It provides C compatible
13 data types, and allows calling functions in dlls/shared libraries.  It can be
14 used to wrap these libraries in pure Python.
17 .. _ctypes-ctypes-tutorial:
19 ctypes tutorial
20 ---------------
22 Note: The code samples in this tutorial use ``doctest`` to make sure that they
23 actually work.  Since some code samples behave differently under Linux, Windows,
24 or Mac OS X, they contain doctest directives in comments.
26 Note: Some code sample references the ctypes :class:`c_int` type. This type is
27 an alias to the :class:`c_long` type on 32-bit systems.  So, you should not be
28 confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
29 they are actually the same type.
32 .. _ctypes-loading-dynamic-link-libraries:
34 Loading dynamic link libraries
35 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
37 ``ctypes`` exports the *cdll*, and on Windows also *windll* and *oledll* objects
38 to load dynamic link libraries.
40 You load libraries by accessing them as attributes of these objects. *cdll*
41 loads libraries which export functions using the standard ``cdecl`` calling
42 convention, while *windll* libraries call functions using the ``stdcall``
43 calling convention. *oledll* also uses the ``stdcall`` calling convention, and
44 assumes the functions return a Windows :class:`HRESULT` error code. The error
45 code is used to automatically raise :class:`WindowsError` Python exceptions when
46 the function call fails.
48 Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
49 library containing most standard C functions, and uses the cdecl calling
50 convention::
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    >>>
60 Windows appends the usual '.dll' file suffix automatically.
62 On Linux, it is required to specify the filename *including* the extension to
63 load a library, so attribute access does not work. Either the
64 :meth:`LoadLibrary` method of the dll loaders should be used, or you should load
65 the library by creating an instance of CDLL by calling the constructor::
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    >>>
74 .. XXX Add section for Mac OS X.
77 .. _ctypes-accessing-functions-from-loaded-dlls:
79 Accessing functions from loaded dlls
80 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
82 Functions are accessed as attributes of dll objects::
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    >>>
97 Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
98 as well as UNICODE versions of a function. The UNICODE version is exported with
99 an ``W`` appended to the name, while the ANSI version is exported with an ``A``
100 appended 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
102 macro is used to expose one of them as ``GetModuleHandle`` depending on whether
103 UNICODE is defined or not::
105    /* ANSI version */
106    HMODULE GetModuleHandleA(LPCSTR lpModuleName);
107    /* UNICODE version */
108    HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
110 *windll* does not try to select one of them by magic, you must access the
111 version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
112 explicitly, and then call it with normal strings or unicode strings
113 respectively.
115 Sometimes, dlls export functions with names which aren't valid Python
116 identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use ``getattr``
117 to retrieve the function::
119    >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
120    <_FuncPtr object at 0x...>
121    >>>
123 On Windows, some dlls export functions not by name but by ordinal. These
124 functions can be accessed by indexing the dll object with the ordinal number::
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    >>>
137 .. _ctypes-calling-functions:
139 Calling functions
140 ^^^^^^^^^^^^^^^^^
142 You can call these functions like any other Python callable. This example uses
143 the ``time()`` function, which returns system time in seconds since the Unix
144 epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
145 handle.
147 This example calls both functions with a NULL pointer (``None`` should be used
148 as the NULL pointer)::
150    >>> print libc.time(None) # doctest: +SKIP
151    1150640792
152    >>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
153    0x1d000000
154    >>>
156 ``ctypes`` tries to protect you from calling functions with the wrong number of
157 arguments or the wrong calling convention.  Unfortunately this only works on
158 Windows.  It does this by examining the stack after the function returns, so
159 although an error is raised the function *has* been called::
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    >>>
171 The same exception is raised when you call an ``stdcall`` function with the
172 ``cdecl`` calling convention, or vice versa::
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    >>>
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    >>>
186 To find out the correct calling convention you have to look into the C header
187 file or the documentation for the function you want to call.
189 On Windows, ``ctypes`` uses win32 structured exception handling to prevent
190 crashes from general protection faults when functions are called with invalid
191 argument values::
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    >>>
199 There are, however, enough ways to crash Python with ``ctypes``, so you should
200 be careful anyway.
202 ``None``, integers, longs, byte strings and unicode strings are the only native
203 Python 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
205 passed 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
207 default C ``int`` type, their value is masked to fit into the C type.
209 Before we move on calling functions with other parameter types, we have to learn
210 more about ``ctypes`` data types.
213 .. _ctypes-fundamental-data-types:
215 Fundamental data types
216 ^^^^^^^^^^^^^^^^^^^^^^
218 ``ctypes`` defines a number of primitive C compatible data types :
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    +----------------------+--------------------------------+----------------------------+
262 All these types can be created by calling them with an optional initializer of
263 the correct type and value::
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    >>>
273 Since these types are mutable, their value can also be changed afterwards::
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    >>>
285 Assigning 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
287 point to, *not the contents* of the memory block (of course not, because Python
288 strings are immutable)::
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    >>>
301 You should be careful, however, not to pass them to functions expecting pointers
302 to mutable memory. If you need mutable memory blocks, ctypes has a
303 ``create_string_buffer`` function which creates these in various ways.  The
304 current memory block contents can be accessed (or changed) with the ``raw``
305 property; if you want to access it as NUL terminated string, use the ``value``
306 property::
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    >>>
325 The ``create_string_buffer`` function replaces the ``c_buffer`` function (which
326 is still available as an alias), as well as the ``c_string`` function from
327 earlier ctypes releases.  To create a mutable memory block containing unicode
328 characters of the C type ``wchar_t`` use the ``create_unicode_buffer`` function.
331 .. _ctypes-calling-functions-continued:
333 Calling functions, continued
334 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
336 Note 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
338 within *IDLE* or *PythonWin*::
340    >>> printf = libc.printf
341    >>> printf("Hello, %s\n", "World!")
342    Hello, World!
343    14
344    >>> printf("Hello, %S", u"World!")
345    Hello, World!
346    13
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    >>>
356 As has been mentioned before, all Python types except integers, strings, and
357 unicode strings have to be wrapped in their corresponding ``ctypes`` type, so
358 that they can be converted to the required C data type::
360    >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
361    Integer 1234, double 3.1400001049
362    31
363    >>>
366 .. _ctypes-calling-functions-with-own-custom-data-types:
368 Calling functions with your own custom data types
369 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
371 You can also customize ``ctypes`` argument conversion to allow instances of your
372 own classes be used as function arguments. ``ctypes`` looks for an
373 :attr:`_as_parameter_` attribute and uses this as the function argument. Of
374 course, it must be one of integer, string, or unicode::
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    >>>
386 If you don't want to store the instance's data in the :attr:`_as_parameter_`
387 instance variable, you could define a ``property`` which makes the data
388 available.
391 .. _ctypes-specifying-required-argument-types:
393 Specifying the required argument types (function prototypes)
394 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
396 It is possible to specify the required argument types of functions exported from
397 DLLs by setting the :attr:`argtypes` attribute.
399 :attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
400 probably not a good example here, because it takes a variable number and
401 different types of parameters depending on the format string, on the other hand
402 this is quite handy to experiment with this feature)::
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    >>>
410 Specifying a format protects against incompatible argument types (just as a
411 prototype for a C function), and tries to convert the arguments to valid types::
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", "X", 2, 3)
418    X 2 3.00000012
419    12
420    >>>
422 If you have defined your own classes which you pass to function calls, you have
423 to implement a :meth:`from_param` class method for them to be able to use them
424 in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
425 the Python object passed to the function call, it should do a typecheck or
426 whatever is needed to make sure this object is acceptable, and then return the
427 object itself, it's :attr:`_as_parameter_` attribute, or whatever you want to
428 pass as the C function argument in this case. Again, the result should be an
429 integer, string, unicode, a ``ctypes`` instance, or something having the
430 :attr:`_as_parameter_` attribute.
433 .. _ctypes-return-types:
435 Return types
436 ^^^^^^^^^^^^
438 By default functions are assumed to return the C ``int`` type.  Other return
439 types can be specified by setting the :attr:`restype` attribute of the function
440 object.
442 Here is a more advanced example, it uses the ``strchr`` function, which expects
443 a string pointer and a char, and returns a pointer to a string::
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    >>>
455 If 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
457 single character Python string into a C char::
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    >>>
473 You can also use a callable Python object (a function or a class for example) as
474 the :attr:`restype` attribute, if the foreign function returns an integer.  The
475 callable will be called with the ``integer`` the C function returns, and the
476 result of this call will be used as the result of your function call. This is
477 useful to check for error return values and automatically raise an exception::
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    >>>
496 ``WinError`` is a function which will call Windows ``FormatMessage()`` api to
497 get 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.
501 Please note that a much more powerful error checking mechanism is available
502 through the :attr:`errcheck` attribute; see the reference manual for details.
505 .. _ctypes-passing-pointers:
507 Passing pointers (or: passing parameters by reference)
508 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
510 Sometimes a C api function expects a *pointer* to a data type as parameter,
511 probably to write into the corresponding location, or if the data is too large
512 to be passed by value. This is also known as *passing parameters by reference*.
514 ``ctypes`` exports the :func:`byref` function which is used to pass parameters
515 by reference.  The same effect can be achieved with the ``pointer`` function,
516 although ``pointer`` does a lot more work since it constructs a real pointer
517 object, so it is faster to use :func:`byref` if you don't need the pointer
518 object in Python itself::
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    >>>
533 .. _ctypes-structures-unions:
535 Structures and unions
536 ^^^^^^^^^^^^^^^^^^^^^
538 Structures and unions must derive from the :class:`Structure` and :class:`Union`
539 base classes which are defined in the ``ctypes`` module. Each subclass must
540 define a :attr:`_fields_` attribute.  :attr:`_fields_` must be a list of
541 *2-tuples*, containing a *field name* and a *field type*.
543 The field type must be a ``ctypes`` type like :class:`c_int`, or any other
544 derived ``ctypes`` type: structure, union, array, pointer.
546 Here 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
548 constructor::
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    >>>
567 You can, however, build much more complicated structures. Structures can itself
568 contain other structures by using a structure as a field type.
570 Here is a RECT structure which contains two POINTs named ``upperleft`` and
571 ``lowerright``  ::
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    >>>
584 Nested structures can also be initialized in the constructor in several ways::
586    >>> r = RECT(POINT(1, 2), POINT(3, 4))
587    >>> r = RECT((1, 2), (3, 4))
589 Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
590 for debugging because they can provide useful information::
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    >>>
599 .. _ctypes-structureunion-alignment-byte-order:
601 Structure/union alignment and byte order
602 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
604 By default, Structure and Union fields are aligned in the same way the C
605 compiler 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
607 positive integer and specifies the maximum alignment for the fields. This is
608 what ``#pragma pack(n)`` also does in MSVC.
610 ``ctypes`` uses the native byte order for Structures and Unions.  To build
611 structures with non-native byte order, you can use one of the
612 BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
613 base classes.  These classes cannot contain pointer fields.
616 .. _ctypes-bit-fields-in-structures-unions:
618 Bit fields in structures and unions
619 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
621 It is possible to create structures and unions containing bit fields. Bit fields
622 are only possible for integer fields, the bit width is specified as the third
623 item in the :attr:`_fields_` tuples::
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    >>>
636 .. _ctypes-arrays:
638 Arrays
639 ^^^^^^
641 Arrays are sequences, containing a fixed number of instances of the same type.
643 The recommended way to create array types is by multiplying a data type with a
644 positive integer::
646    TenPointsArrayType = POINT * 10
648 Here is an example of an somewhat artificial data type, a structure containing 4
649 POINTs among other stuff::
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    >>>
664 Instances are created in the usual way, by calling the class::
666    arr = TenPointsArrayType()
667    for pt in arr:
668        print pt.x, pt.y
670 The above code print a series of ``0 0`` lines, because the array contents is
671 initialized to zeros.
673 Initializers of the correct type can also be specified::
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    >>>
686 .. _ctypes-pointers:
688 Pointers
689 ^^^^^^^^
691 Pointer instances are created by calling the ``pointer`` function on a
692 ``ctypes`` type::
694    >>> from ctypes import *
695    >>> i = c_int(42)
696    >>> pi = pointer(i)
697    >>>
699 Pointer instances have a ``contents`` attribute which returns the object to
700 which the pointer points, the ``i`` object above::
702    >>> pi.contents
703    c_long(42)
704    >>>
706 Note that ``ctypes`` does not have OOR (original object return), it constructs a
707 new, equivalent object each time you retrieve an attribute::
709    >>> pi.contents is i
710    False
711    >>> pi.contents is pi.contents
712    False
713    >>>
715 Assigning another :class:`c_int` instance to the pointer's contents attribute
716 would cause the pointer to point to the memory location where this is stored::
718    >>> i = c_int(99)
719    >>> pi.contents = i
720    >>> pi.contents
721    c_long(99)
722    >>>
724 Pointer instances can also be indexed with integers::
726    >>> pi[0]
727    99
728    >>>
730 Assigning to an integer index changes the pointed to value::
732    >>> print i
733    c_long(99)
734    >>> pi[0] = 22
735    >>> print i
736    c_long(22)
737    >>>
739 It is also possible to use indexes different from 0, but you must know what
740 you're doing, just as in C: You can access or change arbitrary memory locations.
741 Generally you only use this feature if you receive a pointer from a C function,
742 and you *know* that the pointer actually points to an array instead of a single
743 item.
745 Behind the scenes, the ``pointer`` function does more than simply create pointer
746 instances, it has to create pointer *types* first. This is done with the
747 ``POINTER`` function, which accepts any ``ctypes`` type, and returns a new
748 type::
750    >>> PI = POINTER(c_int)
751    >>> PI
752    <class 'ctypes.LP_c_long'>
753    >>> PI(42)
754    Traceback (most recent call last):
755      File "<stdin>", line 1, in ?
756    TypeError: expected c_long instead of int
757    >>> PI(c_int(42))
758    <ctypes.LP_c_long object at 0x...>
759    >>>
761 Calling the pointer type without an argument creates a ``NULL`` pointer.
762 ``NULL`` pointers have a ``False`` boolean value::
764    >>> null_ptr = POINTER(c_int)()
765    >>> print bool(null_ptr)
766    False
767    >>>
769 ``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
770 non-\ ``NULL`` pointers would crash Python)::
772    >>> null_ptr[0]
773    Traceback (most recent call last):
774        ....
775    ValueError: NULL pointer access
776    >>>
778    >>> null_ptr[0] = 1234
779    Traceback (most recent call last):
780        ....
781    ValueError: NULL pointer access
782    >>>
785 .. _ctypes-type-conversions:
787 Type conversions
788 ^^^^^^^^^^^^^^^^
790 Usually, ctypes does strict type checking.  This means, if you have
791 ``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
792 a member field in a structure definition, only instances of exactly the same
793 type are accepted.  There are some exceptions to this rule, where ctypes accepts
794 other objects.  For example, you can pass compatible array instances instead of
795 pointer types.  So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
797    >>> class Bar(Structure):
798    ...     _fields_ = [("count", c_int), ("values", POINTER(c_int))]
799    ...
800    >>> bar = Bar()
801    >>> bar.values = (c_int * 3)(1, 2, 3)
802    >>> bar.count = 3
803    >>> for i in range(bar.count):
804    ...     print bar.values[i]
805    ...
806    1
807    2
808    3
809    >>>
811 To set a POINTER type field to ``NULL``, you can assign ``None``::
813    >>> bar.values = None
814    >>>
816 XXX list other conversions...
818 Sometimes you have instances of incompatible types.  In ``C``, you can cast one
819 type into another type.  ``ctypes`` provides a ``cast`` function which can be
820 used in the same way.  The ``Bar`` structure defined above accepts
821 ``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
822 but not instances of other types::
824    >>> bar.values = (c_byte * 4)()
825    Traceback (most recent call last):
826      File "<stdin>", line 1, in ?
827    TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
828    >>>
830 For these cases, the ``cast`` function is handy.
832 The ``cast`` function can be used to cast a ctypes instance into a pointer to a
833 different ctypes data type.  ``cast`` takes two parameters, a ctypes object that
834 is or can be converted to a pointer of some kind, and a ctypes pointer type.  It
835 returns an instance of the second argument, which references the same memory
836 block as the first argument::
838    >>> a = (c_byte * 4)()
839    >>> cast(a, POINTER(c_int))
840    <ctypes.LP_c_long object at ...>
841    >>>
843 So, ``cast`` can be used to assign to the ``values`` field of ``Bar`` the
844 structure::
846    >>> bar = Bar()
847    >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
848    >>> print bar.values[0]
849    0
850    >>>
853 .. _ctypes-incomplete-types:
855 Incomplete Types
856 ^^^^^^^^^^^^^^^^
858 *Incomplete Types* are structures, unions or arrays whose members are not yet
859 specified. In C, they are specified by forward declarations, which are defined
860 later::
862    struct cell; /* forward declaration */
864    struct {
865        char *name;
866        struct cell *next;
867    } cell;
869 The straightforward translation into ctypes code would be this, but it does not
870 work::
872    >>> class cell(Structure):
873    ...     _fields_ = [("name", c_char_p),
874    ...                 ("next", POINTER(cell))]
875    ...
876    Traceback (most recent call last):
877      File "<stdin>", line 1, in ?
878      File "<stdin>", line 2, in cell
879    NameError: name 'cell' is not defined
880    >>>
882 because the new ``class cell`` is not available in the class statement itself.
883 In ``ctypes``, we can define the ``cell`` class and set the :attr:`_fields_`
884 attribute later, after the class statement::
886    >>> from ctypes import *
887    >>> class cell(Structure):
888    ...     pass
889    ...
890    >>> cell._fields_ = [("name", c_char_p),
891    ...                  ("next", POINTER(cell))]
892    >>>
894 Lets try it. We create two instances of ``cell``, and let them point to each
895 other, and finally follow the pointer chain a few times::
897    >>> c1 = cell()
898    >>> c1.name = "foo"
899    >>> c2 = cell()
900    >>> c2.name = "bar"
901    >>> c1.next = pointer(c2)
902    >>> c2.next = pointer(c1)
903    >>> p = c1
904    >>> for i in range(8):
905    ...     print p.name,
906    ...     p = p.next[0]
907    ...
908    foo bar foo bar foo bar foo bar
909    >>>    
912 .. _ctypes-callback-functions:
914 Callback functions
915 ^^^^^^^^^^^^^^^^^^
917 ``ctypes`` allows to create C callable function pointers from Python callables.
918 These are sometimes called *callback functions*.
920 First, you must create a class for the callback function, the class knows the
921 calling convention, the return type, and the number and types of arguments this
922 function will receive.
924 The CFUNCTYPE factory function creates types for callback functions using the
925 normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
926 function creates types for callback functions using the stdcall calling
927 convention.
929 Both of these factory functions are called with the result type as first
930 argument, and the callback functions expected argument types as the remaining
931 arguments.
933 I will present an example here which uses the standard C library's :func:`qsort`
934 function, this is used to sort items with the help of a callback function.
935 :func:`qsort` will be used to sort an array of integers::
937    >>> IntArray5 = c_int * 5
938    >>> ia = IntArray5(5, 1, 7, 33, 99)
939    >>> qsort = libc.qsort
940    >>> qsort.restype = None
941    >>>
943 :func:`qsort` must be called with a pointer to the data to sort, the number of
944 items in the data array, the size of one item, and a pointer to the comparison
945 function, the callback. The callback will then be called with two pointers to
946 items, and it must return a negative integer if the first item is smaller than
947 the second, a zero if they are equal, and a positive integer else.
949 So our callback function receives pointers to integers, and must return an
950 integer. First we create the ``type`` for the callback function::
952    >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
953    >>>
955 For the first implementation of the callback function, we simply print the
956 arguments we get, and return 0 (incremental development ;-)::
958    >>> def py_cmp_func(a, b):
959    ...     print "py_cmp_func", a, b
960    ...     return 0
961    ...
962    >>>
964 Create the C callable callback::
966    >>> cmp_func = CMPFUNC(py_cmp_func)
967    >>>
969 And we're ready to go::
971    >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
972    py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
973    py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
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    >>>
984 We know how to access the contents of a pointer, so lets redefine our callback::
986    >>> def py_cmp_func(a, b):
987    ...     print "py_cmp_func", a[0], b[0]
988    ...     return 0
989    ...
990    >>> cmp_func = CMPFUNC(py_cmp_func)
991    >>>
993 Here is what we get on Windows::
995    >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
996    py_cmp_func 7 1
997    py_cmp_func 33 1
998    py_cmp_func 99 1
999    py_cmp_func 5 1
1000    py_cmp_func 7 5
1001    py_cmp_func 33 5
1002    py_cmp_func 99 5
1003    py_cmp_func 7 99
1004    py_cmp_func 33 99
1005    py_cmp_func 7 33
1006    >>>
1008 It is funny to see that on linux the sort function seems to work much more
1009 efficient, it is doing less comparisons::
1011    >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
1012    py_cmp_func 5 1
1013    py_cmp_func 33 99
1014    py_cmp_func 7 33
1015    py_cmp_func 5 7
1016    py_cmp_func 1 7
1017    >>>
1019 Ah, we're nearly done! The last step is to actually compare the two items and
1020 return a useful result::
1022    >>> def py_cmp_func(a, b):
1023    ...     print "py_cmp_func", a[0], b[0]
1024    ...     return a[0] - b[0]
1025    ...
1026    >>>
1028 Final run on Windows::
1030    >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
1031    py_cmp_func 33 7
1032    py_cmp_func 99 33
1033    py_cmp_func 5 99
1034    py_cmp_func 1 99
1035    py_cmp_func 33 7
1036    py_cmp_func 1 33
1037    py_cmp_func 5 33
1038    py_cmp_func 5 7
1039    py_cmp_func 1 7
1040    py_cmp_func 5 1
1041    >>>
1043 and on Linux::
1045    >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1046    py_cmp_func 5 1
1047    py_cmp_func 33 99
1048    py_cmp_func 7 33
1049    py_cmp_func 1 7
1050    py_cmp_func 5 7
1051    >>>
1053 It is quite interesting to see that the Windows :func:`qsort` function needs
1054 more comparisons than the linux version!
1056 As we can easily check, our array is sorted now::
1058    >>> for i in ia: print i,
1059    ...
1060    1 5 7 33 99
1061    >>>
1063 **Important note for callback functions:**
1065 Make sure you keep references to CFUNCTYPE objects as long as they are used from
1066 C code. ``ctypes`` doesn't, and if you don't, they may be garbage collected,
1067 crashing your program when a callback is made.
1070 .. _ctypes-accessing-values-exported-from-dlls:
1072 Accessing values exported from dlls
1073 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1075 Sometimes, a dll not only exports functions, it also exports variables. An
1076 example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
1077 to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
1078 startup.
1080 ``ctypes`` can access values like this with the :meth:`in_dll` class methods of
1081 the type.  *pythonapi* is a predefined symbol giving access to the Python C
1082 api::
1084    >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
1085    >>> print opt_flag
1086    c_long(0)
1087    >>>
1089 If the interpreter would have been started with :option:`-O`, the sample would
1090 have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1091 specified.
1093 An extended example which also demonstrates the use of pointers accesses the
1094 ``PyImport_FrozenModules`` pointer exported by Python.
1096 Quoting the Python docs: *This pointer is initialized to point to an array of
1097 "struct _frozen" records, terminated by one whose members are all NULL or zero.
1098 When a frozen module is imported, it is searched in this table. Third-party code
1099 could play tricks with this to provide a dynamically created collection of
1100 frozen modules.*
1102 So manipulating this pointer could even prove useful. To restrict the example
1103 size, we show only how this table can be read with ``ctypes``::
1105    >>> from ctypes import *
1106    >>>
1107    >>> class struct_frozen(Structure):
1108    ...     _fields_ = [("name", c_char_p),
1109    ...                 ("code", POINTER(c_ubyte)),
1110    ...                 ("size", c_int)]
1111    ...
1112    >>>
1114 We have defined the ``struct _frozen`` data type, so we can get the pointer to
1115 the table::
1117    >>> FrozenTable = POINTER(struct_frozen)
1118    >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1119    >>>
1121 Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1122 can iterate over it, but we just have to make sure that our loop terminates,
1123 because pointers have no size. Sooner or later it would probably crash with an
1124 access violation or whatever, so it's better to break out of the loop when we
1125 hit the NULL entry::
1127    >>> for item in table:
1128    ...    print item.name, item.size
1129    ...    if item.name is None:
1130    ...        break
1131    ...
1132    __hello__ 104
1133    __phello__ -104
1134    __phello__.spam 104
1135    None 0
1136    >>>
1138 The fact that standard Python has a frozen module and a frozen package
1139 (indicated by the negative size member) is not well known, it is only used for
1140 testing. Try it out with ``import __hello__`` for example.
1143 .. _ctypes-surprises:
1145 Surprises
1146 ^^^^^^^^^
1148 There are some edges in ``ctypes`` where you may be expect something else than
1149 what actually happens.
1151 Consider the following example::
1153    >>> from ctypes import *
1154    >>> class POINT(Structure):
1155    ...     _fields_ = ("x", c_int), ("y", c_int)
1156    ...
1157    >>> class RECT(Structure):
1158    ...     _fields_ = ("a", POINT), ("b", POINT)
1159    ...
1160    >>> p1 = POINT(1, 2)
1161    >>> p2 = POINT(3, 4)
1162    >>> rc = RECT(p1, p2)
1163    >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1164    1 2 3 4
1165    >>> # now swap the two points
1166    >>> rc.a, rc.b = rc.b, rc.a
1167    >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1168    3 4 3 4
1169    >>>
1171 Hm. We certainly expected the last statement to print ``3 4 1 2``. What
1172 happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
1174    >>> temp0, temp1 = rc.b, rc.a
1175    >>> rc.a = temp0
1176    >>> rc.b = temp1
1177    >>>
1179 Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1180 the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1181 contents of ``temp0`` into ``rc`` 's buffer.  This, in turn, changes the
1182 contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1183 the expected effect.
1185 Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1186 doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
1187 the root-object's underlying buffer.
1189 Another example that may behave different from what one would expect is this::
1191    >>> s = c_char_p()
1192    >>> s.value = "abc def ghi"
1193    >>> s.value
1194    'abc def ghi'
1195    >>> s.value is s.value
1196    False
1197    >>>
1199 Why is it printing ``False``?  ctypes instances are objects containing a memory
1200 block plus some :term:`descriptor`\s accessing the contents of the memory.
1201 Storing a Python object in the memory block does not store the object itself,
1202 instead the ``contents`` of the object is stored.  Accessing the contents again
1203 constructs a new Python object each time!
1206 .. _ctypes-variable-sized-data-types:
1208 Variable-sized data types
1209 ^^^^^^^^^^^^^^^^^^^^^^^^^
1211 ``ctypes`` provides some support for variable-sized arrays and structures (this
1212 was added in version 0.9.9.7).
1214 The ``resize`` function can be used to resize the memory buffer of an existing
1215 ctypes object.  The function takes the object as first argument, and the
1216 requested size in bytes as the second argument.  The memory block cannot be made
1217 smaller than the natural memory block specified by the objects type, a
1218 ``ValueError`` is raised if this is tried::
1220    >>> short_array = (c_short * 4)()
1221    >>> print sizeof(short_array)
1222    8
1223    >>> resize(short_array, 4)
1224    Traceback (most recent call last):
1225        ...
1226    ValueError: minimum size is 8
1227    >>> resize(short_array, 32)
1228    >>> sizeof(short_array)
1229    32
1230    >>> sizeof(type(short_array))
1231    8
1232    >>>
1234 This is nice and fine, but how would one access the additional elements
1235 contained in this array?  Since the type still only knows about 4 elements, we
1236 get errors accessing other elements::
1238    >>> short_array[:]
1239    [0, 0, 0, 0]
1240    >>> short_array[7]
1241    Traceback (most recent call last):
1242        ...
1243    IndexError: invalid index
1244    >>>
1246 Another way to use variable-sized data types with ``ctypes`` is to use the
1247 dynamic nature of Python, and (re-)define the data type after the required size
1248 is already known, on a case by case basis.
1251 .. _ctypes-bugs-todo-non-implemented-things:
1253 Bugs, ToDo and non-implemented things
1254 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1256 Enumeration types are not implemented. You can do it easily yourself, using
1257 :class:`c_int` as the base class.
1259 ``long double`` is not implemented.
1262 .. _ctypes-ctypes-reference:
1264 ctypes reference
1265 ----------------
1268 .. _ctypes-finding-shared-libraries:
1270 Finding shared libraries
1271 ^^^^^^^^^^^^^^^^^^^^^^^^
1273 When programming in a compiled language, shared libraries are accessed when
1274 compiling/linking a program, and when the program is run.
1276 The purpose of the ``find_library`` function is to locate a library in a way
1277 similar to what the compiler does (on platforms with several versions of a
1278 shared library the most recent should be loaded), while the ctypes library
1279 loaders act like when a program is run, and call the runtime loader directly.
1281 The ``ctypes.util`` module provides a function which can help to determine the
1282 library to load.
1285 .. data:: find_library(name)
1286    :noindex:
1288    Try to find a library and return a pathname.  *name* is the library name without
1289    any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1290    is the form used for the posix linker option :option:`-l`).  If no library can
1291    be found, returns ``None``.
1293 The exact functionality is system dependent.
1295 On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
1296 and objdump) to find the library file.  It returns the filename of the library
1297 file.  Here are some examples::
1299    >>> from ctypes.util import find_library
1300    >>> find_library("m")
1301    'libm.so.6'
1302    >>> find_library("c")
1303    'libc.so.6'
1304    >>> find_library("bz2")
1305    'libbz2.so.1.0'
1306    >>>
1308 On OS X, ``find_library`` tries several predefined naming schemes and paths to
1309 locate the library, and returns a full pathname if successful::
1311    >>> from ctypes.util import find_library
1312    >>> find_library("c")
1313    '/usr/lib/libc.dylib'
1314    >>> find_library("m")
1315    '/usr/lib/libm.dylib'
1316    >>> find_library("bz2")
1317    '/usr/lib/libbz2.dylib'
1318    >>> find_library("AGL")
1319    '/System/Library/Frameworks/AGL.framework/AGL'
1320    >>>
1322 On Windows, ``find_library`` searches along the system search path, and returns
1323 the full pathname, but since there is no predefined naming scheme a call like
1324 ``find_library("c")`` will fail and return ``None``.
1326 If wrapping a shared library with ``ctypes``, it *may* be better to determine
1327 the shared library name at development type, and hardcode that into the wrapper
1328 module instead of using ``find_library`` to locate the library at runtime.
1331 .. _ctypes-loading-shared-libraries:
1333 Loading shared libraries
1334 ^^^^^^^^^^^^^^^^^^^^^^^^
1336 There are several ways to loaded shared libraries into the Python process.  One
1337 way is to instantiate one of the following classes:
1340 .. class:: CDLL(name, mode=DEFAULT_MODE, handle=None)
1342    Instances of this class represent loaded shared libraries. Functions in these
1343    libraries use the standard C calling convention, and are assumed to return
1344    ``int``.
1347 .. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None)
1349    Windows only: Instances of this class represent loaded shared libraries,
1350    functions in these libraries use the ``stdcall`` calling convention, and are
1351    assumed to return the windows specific :class:`HRESULT` code.  :class:`HRESULT`
1352    values contain information specifying whether the function call failed or
1353    succeeded, together with additional error code.  If the return value signals a
1354    failure, an :class:`WindowsError` is automatically raised.
1357 .. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None)
1359    Windows only: Instances of this class represent loaded shared libraries,
1360    functions in these libraries use the ``stdcall`` calling convention, and are
1361    assumed to return ``int`` by default.
1363    On Windows CE only the standard calling convention is used, for convenience the
1364    :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1365    platform.
1367 The Python :term:`global interpreter lock` is released before calling any
1368 function exported by these libraries, and reacquired afterwards.
1371 .. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1373    Instances of this class behave like :class:`CDLL` instances, except that the
1374    Python GIL is *not* released during the function call, and after the function
1375    execution the Python error flag is checked. If the error flag is set, a Python
1376    exception is raised.
1378    Thus, this is only useful to call Python C api functions directly.
1380 All these classes can be instantiated by calling them with at least one
1381 argument, the pathname of the shared library.  If you have an existing handle to
1382 an already loaded shard library, it can be passed as the ``handle`` named
1383 parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
1384 function is used to load the library into the process, and to get a handle to
1387 The *mode* parameter can be used to specify how the library is loaded.  For
1388 details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
1391 .. data:: RTLD_GLOBAL
1392    :noindex:
1394    Flag to use as *mode* parameter.  On platforms where this flag is not available,
1395    it is defined as the integer zero.
1398 .. data:: RTLD_LOCAL
1399    :noindex:
1401    Flag to use as *mode* parameter.  On platforms where this is not available, it
1402    is the same as *RTLD_GLOBAL*.
1405 .. data:: DEFAULT_MODE
1406    :noindex:
1408    The default mode which is used to load shared libraries.  On OSX 10.3, this is
1409    *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1411 Instances of these classes have no public methods, however :meth:`__getattr__`
1412 and :meth:`__getitem__` have special behavior: functions exported by the shared
1413 library can be accessed as attributes of by index.  Please note that both
1414 :meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1415 repeatedly returns the same object each time.
1417 The following public attributes are available, their name starts with an
1418 underscore to not clash with exported function names:
1421 .. attribute:: PyDLL._handle
1423    The system handle used to access the library.
1426 .. attribute:: PyDLL._name
1428    The name of the library passed in the constructor.
1430 Shared libraries can also be loaded by using one of the prefabricated objects,
1431 which are instances of the :class:`LibraryLoader` class, either by calling the
1432 :meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1433 loader instance.
1436 .. class:: LibraryLoader(dlltype)
1438    Class which loads shared libraries.  ``dlltype`` should be one of the
1439    :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1441    :meth:`__getattr__` has special behavior: It allows to load a shared library by
1442    accessing it as attribute of a library loader instance.  The result is cached,
1443    so repeated attribute accesses return the same library each time.
1446 .. method:: LibraryLoader.LoadLibrary(name)
1448    Load a shared library into the process and return it.  This method always
1449    returns a new instance of the library.
1451 These prefabricated library loaders are available:
1454 .. data:: cdll
1455    :noindex:
1457    Creates :class:`CDLL` instances.
1460 .. data:: windll
1461    :noindex:
1463    Windows only: Creates :class:`WinDLL` instances.
1466 .. data:: oledll
1467    :noindex:
1469    Windows only: Creates :class:`OleDLL` instances.
1472 .. data:: pydll
1473    :noindex:
1475    Creates :class:`PyDLL` instances.
1477 For accessing the C Python api directly, a ready-to-use Python shared library
1478 object is available:
1481 .. data:: pythonapi
1482    :noindex:
1484    An instance of :class:`PyDLL` that exposes Python C api functions as attributes.
1485    Note that all these functions are assumed to return C ``int``, which is of
1486    course not always the truth, so you have to assign the correct :attr:`restype`
1487    attribute to use these functions.
1490 .. _ctypes-foreign-functions:
1492 Foreign functions
1493 ^^^^^^^^^^^^^^^^^
1495 As explained in the previous section, foreign functions can be accessed as
1496 attributes of loaded shared libraries.  The function objects created in this way
1497 by default accept any number of arguments, accept any ctypes data instances as
1498 arguments, and return the default result type specified by the library loader.
1499 They are instances of a private class:
1502 .. class:: _FuncPtr
1504    Base class for C callable foreign functions.
1506 Instances of foreign functions are also C compatible data types; they represent
1507 C function pointers.
1509 This behavior can be customized by assigning to special attributes of the
1510 foreign function object.
1513 .. attribute:: _FuncPtr.restype
1515    Assign a ctypes type to specify the result type of the foreign function.  Use
1516    ``None`` for ``void`` a function not returning anything.
1518    It is possible to assign a callable Python object that is not a ctypes type, in
1519    this case the function is assumed to return a C ``int``, and the callable will
1520    be called with this integer, allowing to do further processing or error
1521    checking.  Using this is deprecated, for more flexible post processing or error
1522    checking use a ctypes data type as :attr:`restype` and assign a callable to the
1523    :attr:`errcheck` attribute.
1526 .. attribute:: _FuncPtr.argtypes
1528    Assign a tuple of ctypes types to specify the argument types that the function
1529    accepts.  Functions using the ``stdcall`` calling convention can only be called
1530    with the same number of arguments as the length of this tuple; functions using
1531    the C calling convention accept additional, unspecified arguments as well.
1533    When a foreign function is called, each actual argument is passed to the
1534    :meth:`from_param` class method of the items in the :attr:`argtypes` tuple, this
1535    method allows to adapt the actual argument to an object that the foreign
1536    function accepts.  For example, a :class:`c_char_p` item in the :attr:`argtypes`
1537    tuple will convert a unicode string passed as argument into an byte string using
1538    ctypes conversion rules.
1540    New: It is now possible to put items in argtypes which are not ctypes types, but
1541    each item must have a :meth:`from_param` method which returns a value usable as
1542    argument (integer, string, ctypes instance).  This allows to define adapters
1543    that can adapt custom objects as function parameters.
1546 .. attribute:: _FuncPtr.errcheck
1548    Assign a Python function or another callable to this attribute. The callable
1549    will be called with three or more arguments:
1552 .. function:: callable(result, func, arguments)
1553    :noindex:
1555    ``result`` is what the foreign function returns, as specified by the
1556    :attr:`restype` attribute.
1558    ``func`` is the foreign function object itself, this allows to reuse the same
1559    callable object to check or post process the results of several functions.
1561    ``arguments`` is a tuple containing the parameters originally passed to the
1562    function call, this allows to specialize the behavior on the arguments used.
1564    The object that this function returns will be returned from the foreign function
1565    call, but it can also check the result value and raise an exception if the
1566    foreign function call failed.
1569 .. exception:: ArgumentError()
1571    This exception is raised when a foreign function call cannot convert one of the
1572    passed arguments.
1575 .. _ctypes-function-prototypes:
1577 Function prototypes
1578 ^^^^^^^^^^^^^^^^^^^
1580 Foreign functions can also be created by instantiating function prototypes.
1581 Function prototypes are similar to function prototypes in C; they describe a
1582 function (return type, argument types, calling convention) without defining an
1583 implementation.  The factory functions must be called with the desired result
1584 type and the argument types of the function.
1587 .. function:: CFUNCTYPE(restype, *argtypes)
1589    The returned function prototype creates functions that use the standard C
1590    calling convention.  The function will release the GIL during the call.
1593 .. function:: WINFUNCTYPE(restype, *argtypes)
1595    Windows only: The returned function prototype creates functions that use the
1596    ``stdcall`` calling convention, except on Windows CE where :func:`WINFUNCTYPE`
1597    is the same as :func:`CFUNCTYPE`.  The function will release the GIL during the
1598    call.
1601 .. function:: PYFUNCTYPE(restype, *argtypes)
1603    The returned function prototype creates functions that use the Python calling
1604    convention.  The function will *not* release the GIL during the call.
1606 Function prototypes created by the factory functions can be instantiated in
1607 different ways, depending on the type and number of the parameters in the call.
1610 .. function:: prototype(address)
1611    :noindex:
1613    Returns a foreign function at the specified address.
1616 .. function:: prototype(callable)
1617    :noindex:
1619    Create a C callable function (a callback function) from a Python ``callable``.
1622 .. function:: prototype(func_spec[, paramflags])
1623    :noindex:
1625    Returns a foreign function exported by a shared library. ``func_spec`` must be a
1626    2-tuple ``(name_or_ordinal, library)``. The first item is the name of the
1627    exported function as string, or the ordinal of the exported function as small
1628    integer.  The second item is the shared library instance.
1631 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1632    :noindex:
1634    Returns a foreign function that will call a COM method. ``vtbl_index`` is the
1635    index into the virtual function table, a small non-negative integer. *name* is
1636    name of the COM method. *iid* is an optional pointer to the interface identifier
1637    which is used in extended error reporting.
1639    COM methods use a special calling convention: They require a pointer to the COM
1640    interface as first argument, in addition to those parameters that are specified
1641    in the :attr:`argtypes` tuple.
1643 The optional *paramflags* parameter creates foreign function wrappers with much
1644 more functionality than the features described above.
1646 *paramflags* must be a tuple of the same length as :attr:`argtypes`.
1648 Each item in this tuple contains further information about a parameter, it must
1649 be a tuple containing 1, 2, or 3 items.
1651 The first item is an integer containing flags for the parameter:
1654 .. data:: 1
1655    :noindex:
1657    Specifies an input parameter to the function.
1660 .. data:: 2
1661    :noindex:
1663    Output parameter.  The foreign function fills in a value.
1666 .. data:: 4
1667    :noindex:
1669    Input parameter which defaults to the integer zero.
1671 The optional second item is the parameter name as string.  If this is specified,
1672 the foreign function can be called with named parameters.
1674 The optional third item is the default value for this parameter.
1676 This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
1677 that it supports default parameters and named arguments. The C declaration from
1678 the windows header file is this::
1680    WINUSERAPI int WINAPI
1681    MessageBoxA(
1682        HWND hWnd ,
1683        LPCSTR lpText,
1684        LPCSTR lpCaption,
1685        UINT uType);
1687 Here is the wrapping with ``ctypes``:
1689    ::
1691       >>> from ctypes import c_int, WINFUNCTYPE, windll
1692       >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1693       >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
1694       >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1695       >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1696       >>>
1698 The MessageBox foreign function can now be called in these ways::
1700    >>> MessageBox()
1701    >>> MessageBox(text="Spam, spam, spam")
1702    >>> MessageBox(flags=2, text="foo bar")
1703    >>>
1705 A second example demonstrates output parameters.  The win32 ``GetWindowRect``
1706 function retrieves the dimensions of a specified window by copying them into
1707 ``RECT`` structure that the caller has to supply.  Here is the C declaration::
1709    WINUSERAPI BOOL WINAPI
1710    GetWindowRect(
1711         HWND hWnd,
1712         LPRECT lpRect);
1714 Here is the wrapping with ``ctypes``:
1716    ::
1718       >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1719       >>> from ctypes.wintypes import BOOL, HWND, RECT
1720       >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1721       >>> paramflags = (1, "hwnd"), (2, "lprect")
1722       >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1723       >>>
1725 Functions with output parameters will automatically return the output parameter
1726 value if there is a single one, or a tuple containing the output parameter
1727 values when there are more than one, so the GetWindowRect function now returns a
1728 RECT instance, when called.
1730 Output parameters can be combined with the :attr:`errcheck` protocol to do
1731 further output processing and error checking.  The win32 ``GetWindowRect`` api
1732 function returns a ``BOOL`` to signal success or failure, so this function could
1733 do the error checking, and raises an exception when the api call failed::
1735    >>> def errcheck(result, func, args):
1736    ...     if not result:
1737    ...         raise WinError()
1738    ...     return args
1739    >>> GetWindowRect.errcheck = errcheck
1740    >>>
1742 If the :attr:`errcheck` function returns the argument tuple it receives
1743 unchanged, ``ctypes`` continues the normal processing it does on the output
1744 parameters.  If you want to return a tuple of window coordinates instead of a
1745 ``RECT`` instance, you can retrieve the fields in the function and return them
1746 instead, the normal processing will no longer take place::
1748    >>> def errcheck(result, func, args):
1749    ...     if not result:
1750    ...         raise WinError()
1751    ...     rc = args[1]
1752    ...     return rc.left, rc.top, rc.bottom, rc.right
1753    >>>
1754    >>> GetWindowRect.errcheck = errcheck
1755    >>>
1758 .. _ctypes-utility-functions:
1760 Utility functions
1761 ^^^^^^^^^^^^^^^^^
1764 .. function:: addressof(obj)
1766    Returns the address of the memory buffer as integer.  ``obj`` must be an
1767    instance of a ctypes type.
1770 .. function:: alignment(obj_or_type)
1772    Returns the alignment requirements of a ctypes type. ``obj_or_type`` must be a
1773    ctypes type or instance.
1776 .. function:: byref(obj)
1778    Returns a light-weight pointer to ``obj``, which must be an instance of a ctypes
1779    type. The returned object can only be used as a foreign function call parameter.
1780    It behaves similar to ``pointer(obj)``, but the construction is a lot faster.
1783 .. function:: cast(obj, type)
1785    This function is similar to the cast operator in C. It returns a new instance of
1786    ``type`` which points to the same memory block as ``obj``. ``type`` must be a
1787    pointer type, and ``obj`` must be an object that can be interpreted as a
1788    pointer.
1791 .. function:: create_string_buffer(init_or_size[, size])
1793    This function creates a mutable character buffer. The returned object is a
1794    ctypes array of :class:`c_char`.
1796    ``init_or_size`` must be an integer which specifies the size of the array, or a
1797    string which will be used to initialize the array items.
1799    If a string is specified as first argument, the buffer is made one item larger
1800    than the length of the string so that the last element in the array is a NUL
1801    termination character. An integer can be passed as second argument which allows
1802    to specify the size of the array if the length of the string should not be used.
1804    If the first parameter is a unicode string, it is converted into an 8-bit string
1805    according to ctypes conversion rules.
1808 .. function:: create_unicode_buffer(init_or_size[, size])
1810    This function creates a mutable unicode character buffer. The returned object is
1811    a ctypes array of :class:`c_wchar`.
1813    ``init_or_size`` must be an integer which specifies the size of the array, or a
1814    unicode string which will be used to initialize the array items.
1816    If a unicode string is specified as first argument, the buffer is made one item
1817    larger than the length of the string so that the last element in the array is a
1818    NUL termination character. An integer can be passed as second argument which
1819    allows to specify the size of the array if the length of the string should not
1820    be used.
1822    If the first parameter is a 8-bit string, it is converted into an unicode string
1823    according to ctypes conversion rules.
1826 .. function:: DllCanUnloadNow()
1828    Windows only: This function is a hook which allows to implement in-process COM
1829    servers with ctypes. It is called from the DllCanUnloadNow function that the
1830    _ctypes extension dll exports.
1833 .. function:: DllGetClassObject()
1835    Windows only: This function is a hook which allows to implement in-process COM
1836    servers with ctypes. It is called from the DllGetClassObject function that the
1837    ``_ctypes`` extension dll exports.
1840 .. function:: FormatError([code])
1842    Windows only: Returns a textual description of the error code. If no error code
1843    is specified, the last error code is used by calling the Windows api function
1844    GetLastError.
1847 .. function:: GetLastError()
1849    Windows only: Returns the last error code set by Windows in the calling thread.
1852 .. function:: memmove(dst, src, count)
1854    Same as the standard C memmove library function: copies *count* bytes from
1855    ``src`` to *dst*. *dst* and ``src`` must be integers or ctypes instances that
1856    can be converted to pointers.
1859 .. function:: memset(dst, c, count)
1861    Same as the standard C memset library function: fills the memory block at
1862    address *dst* with *count* bytes of value *c*. *dst* must be an integer
1863    specifying an address, or a ctypes instance.
1866 .. function:: POINTER(type)
1868    This factory function creates and returns a new ctypes pointer type. Pointer
1869    types are cached an reused internally, so calling this function repeatedly is
1870    cheap. type must be a ctypes type.
1873 .. function:: pointer(obj)
1875    This function creates a new pointer instance, pointing to ``obj``. The returned
1876    object is of the type POINTER(type(obj)).
1878    Note: If you just want to pass a pointer to an object to a foreign function
1879    call, you should use ``byref(obj)`` which is much faster.
1882 .. function:: resize(obj, size)
1884    This function resizes the internal memory buffer of obj, which must be an
1885    instance of a ctypes type. It is not possible to make the buffer smaller than
1886    the native size of the objects type, as given by sizeof(type(obj)), but it is
1887    possible to enlarge the buffer.
1890 .. function:: set_conversion_mode(encoding, errors)
1892    This function sets the rules that ctypes objects use when converting between
1893    8-bit strings and unicode strings. encoding must be a string specifying an
1894    encoding, like ``'utf-8'`` or ``'mbcs'``, errors must be a string specifying the
1895    error handling on encoding/decoding errors. Examples of possible values are
1896    ``"strict"``, ``"replace"``, or ``"ignore"``.
1898    ``set_conversion_mode`` returns a 2-tuple containing the previous conversion
1899    rules. On windows, the initial conversion rules are ``('mbcs', 'ignore')``, on
1900    other systems ``('ascii', 'strict')``.
1903 .. function:: sizeof(obj_or_type)
1905    Returns the size in bytes of a ctypes type or instance memory buffer. Does the
1906    same as the C ``sizeof()`` function.
1909 .. function:: string_at(address[, size])
1911    This function returns the string starting at memory address address. If size
1912    is specified, it is used as size, otherwise the string is assumed to be
1913    zero-terminated.
1916 .. function:: WinError(code=None, descr=None)
1918    Windows only: this function is probably the worst-named thing in ctypes. It
1919    creates an instance of WindowsError. If *code* is not specified,
1920    ``GetLastError`` is called to determine the error code. If ``descr`` is not
1921    specified, :func:`FormatError` is called to get a textual description of the
1922    error.
1925 .. function:: wstring_at(address)
1927    This function returns the wide character string starting at memory address
1928    ``address`` as unicode string. If ``size`` is specified, it is used as the
1929    number of characters of the string, otherwise the string is assumed to be
1930    zero-terminated.
1933 .. _ctypes-data-types:
1935 Data types
1936 ^^^^^^^^^^
1939 .. class:: _CData
1941    This non-public class is the common base class of all ctypes data types.  Among
1942    other things, all ctypes type instances contain a memory block that hold C
1943    compatible data; the address of the memory block is returned by the
1944    ``addressof()`` helper function. Another instance variable is exposed as
1945    :attr:`_objects`; this contains other Python objects that need to be kept alive
1946    in case the memory block contains pointers.
1948 Common methods of ctypes data types, these are all class methods (to be exact,
1949 they are methods of the :term:`metaclass`):
1952 .. method:: _CData.from_address(address)
1954    This method returns a ctypes type instance using the memory specified by address
1955    which must be an integer.
1958 .. method:: _CData.from_param(obj)
1960    This method adapts obj to a ctypes type.  It is called with the actual object
1961    used in a foreign function call, when the type is present in the foreign
1962    functions :attr:`argtypes` tuple; it must return an object that can be used as
1963    function call parameter.
1965    All ctypes data types have a default implementation of this classmethod,
1966    normally it returns ``obj`` if that is an instance of the type.  Some types
1967    accept other objects as well.
1970 .. method:: _CData.in_dll(library, name)
1972    This method returns a ctypes type instance exported by a shared library. *name*
1973    is the name of the symbol that exports the data, *library* is the loaded shared
1974    library.
1976 Common instance variables of ctypes data types:
1979 .. attribute:: _CData._b_base_
1981    Sometimes ctypes data instances do not own the memory block they contain,
1982    instead they share part of the memory block of a base object.  The
1983    :attr:`_b_base_` read-only member is the root ctypes object that owns the memory
1984    block.
1987 .. attribute:: _CData._b_needsfree_
1989    This read-only variable is true when the ctypes data instance has allocated the
1990    memory block itself, false otherwise.
1993 .. attribute:: _CData._objects
1995    This member is either ``None`` or a dictionary containing Python objects that
1996    need to be kept alive so that the memory block contents is kept valid.  This
1997    object is only exposed for debugging; never modify the contents of this
1998    dictionary.
2001 .. _ctypes-fundamental-data-types-2:
2003 Fundamental data types
2004 ^^^^^^^^^^^^^^^^^^^^^^
2007 .. class:: _SimpleCData
2009    This non-public class is the base class of all fundamental ctypes data types. It
2010    is mentioned here because it contains the common attributes of the fundamental
2011    ctypes data types.  ``_SimpleCData`` is a subclass of ``_CData``, so it inherits
2012    their methods and attributes.
2014    .. versionchanged:: 2.6
2015       ctypes data types that are not and do not contain pointers can
2016       now be pickled.
2018 Instances have a single attribute:
2021 .. attribute:: _SimpleCData.value
2023    This attribute contains the actual value of the instance. For integer and
2024    pointer types, it is an integer, for character types, it is a single character
2025    string, for character pointer types it is a Python string or unicode string.
2027    When the ``value`` attribute is retrieved from a ctypes instance, usually a new
2028    object is returned each time.  ``ctypes`` does *not* implement original object
2029    return, always a new object is constructed.  The same is true for all other
2030    ctypes object instances.
2032 Fundamental data types, when returned as foreign function call results, or, for
2033 example, by retrieving structure field members or array items, are transparently
2034 converted to native Python types.  In other words, if a foreign function has a
2035 :attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
2036 *not* a :class:`c_char_p` instance.
2038 Subclasses of fundamental data types do *not* inherit this behavior. So, if a
2039 foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2040 receive an instance of this subclass from the function call. Of course, you can
2041 get the value of the pointer by accessing the ``value`` attribute.
2043 These are the fundamental ctypes data types:
2046 .. class:: c_byte
2048    Represents the C signed char datatype, and interprets the value as small
2049    integer. The constructor accepts an optional integer initializer; no overflow
2050    checking is done.
2053 .. class:: c_char
2055    Represents the C char datatype, and interprets the value as a single character.
2056    The constructor accepts an optional string initializer, the length of the string
2057    must be exactly one character.
2060 .. class:: c_char_p
2062    Represents the C char \* datatype, which must be a pointer to a zero-terminated
2063    string. The constructor accepts an integer address, or a string.
2066 .. class:: c_double
2068    Represents the C double datatype. The constructor accepts an optional float
2069    initializer.
2072 .. class:: c_longdouble
2074    Represents the C long double datatype. The constructor accepts an
2075    optional float initializer.  On platforms where ``sizeof(long
2076    double) == sizeof(double)`` it is an alias to :class:`c_double`.
2079 .. class:: c_float
2081    Represents the C float datatype. The constructor accepts an optional float
2082    initializer.
2085 .. class:: c_int
2087    Represents the C signed int datatype. The constructor accepts an optional
2088    integer initializer; no overflow checking is done. On platforms where
2089    ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
2092 .. class:: c_int8
2094    Represents the C 8-bit ``signed int`` datatype. Usually an alias for
2095    :class:`c_byte`.
2098 .. class:: c_int16
2100    Represents the C 16-bit signed int datatype. Usually an alias for
2101    :class:`c_short`.
2104 .. class:: c_int32
2106    Represents the C 32-bit signed int datatype. Usually an alias for
2107    :class:`c_int`.
2110 .. class:: c_int64
2112    Represents the C 64-bit ``signed int`` datatype. Usually an alias for
2113    :class:`c_longlong`.
2116 .. class:: c_long
2118    Represents the C ``signed long`` datatype. The constructor accepts an optional
2119    integer initializer; no overflow checking is done.
2122 .. class:: c_longlong
2124    Represents the C ``signed long long`` datatype. The constructor accepts an
2125    optional integer initializer; no overflow checking is done.
2128 .. class:: c_short
2130    Represents the C ``signed short`` datatype. The constructor accepts an optional
2131    integer initializer; no overflow checking is done.
2134 .. class:: c_size_t
2136    Represents the C ``size_t`` datatype.
2139 .. class:: c_ubyte
2141    Represents the C ``unsigned char`` datatype, it interprets the value as small
2142    integer. The constructor accepts an optional integer initializer; no overflow
2143    checking is done.
2146 .. class:: c_uint
2148    Represents the C ``unsigned int`` datatype. The constructor accepts an optional
2149    integer initializer; no overflow checking is done. On platforms where
2150    ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
2153 .. class:: c_uint8
2155    Represents the C 8-bit unsigned int datatype. Usually an alias for
2156    :class:`c_ubyte`.
2159 .. class:: c_uint16
2161    Represents the C 16-bit unsigned int datatype. Usually an alias for
2162    :class:`c_ushort`.
2165 .. class:: c_uint32
2167    Represents the C 32-bit unsigned int datatype. Usually an alias for
2168    :class:`c_uint`.
2171 .. class:: c_uint64
2173    Represents the C 64-bit unsigned int datatype. Usually an alias for
2174    :class:`c_ulonglong`.
2177 .. class:: c_ulong
2179    Represents the C ``unsigned long`` datatype. The constructor accepts an optional
2180    integer initializer; no overflow checking is done.
2183 .. class:: c_ulonglong
2185    Represents the C ``unsigned long long`` datatype. The constructor accepts an
2186    optional integer initializer; no overflow checking is done.
2189 .. class:: c_ushort
2191    Represents the C ``unsigned short`` datatype. The constructor accepts an
2192    optional integer initializer; no overflow checking is done.
2195 .. class:: c_void_p
2197    Represents the C ``void *`` type. The value is represented as integer. The
2198    constructor accepts an optional integer initializer.
2201 .. class:: c_wchar
2203    Represents the C ``wchar_t`` datatype, and interprets the value as a single
2204    character unicode string. The constructor accepts an optional string
2205    initializer, the length of the string must be exactly one character.
2208 .. class:: c_wchar_p
2210    Represents the C ``wchar_t *`` datatype, which must be a pointer to a
2211    zero-terminated wide character string. The constructor accepts an integer
2212    address, or a string.
2215 .. class:: c_bool
2217    Represent the C ``bool`` datatype (more accurately, _Bool from C99). Its value
2218    can be True or False, and the constructor accepts any object that has a truth
2219    value.
2221    .. versionadded:: 2.6
2224 .. class:: HRESULT
2226    Windows only: Represents a :class:`HRESULT` value, which contains success or
2227    error information for a function or method call.
2230 .. class:: py_object
2232    Represents the C ``PyObject *`` datatype.  Calling this without an argument
2233    creates a ``NULL`` ``PyObject *`` pointer.
2235 The ``ctypes.wintypes`` module provides quite some other Windows specific data
2236 types, for example ``HWND``, ``WPARAM``, or ``DWORD``. Some useful structures
2237 like ``MSG`` or ``RECT`` are also defined.
2240 .. _ctypes-structured-data-types:
2242 Structured data types
2243 ^^^^^^^^^^^^^^^^^^^^^
2246 .. class:: Union(*args, **kw)
2248    Abstract base class for unions in native byte order.
2251 .. class:: BigEndianStructure(*args, **kw)
2253    Abstract base class for structures in *big endian* byte order.
2256 .. class:: LittleEndianStructure(*args, **kw)
2258    Abstract base class for structures in *little endian* byte order.
2260 Structures with non-native byte order cannot contain pointer type fields, or any
2261 other data types containing pointer type fields.
2264 .. class:: Structure(*args, **kw)
2266    Abstract base class for structures in *native* byte order.
2268 Concrete structure and union types must be created by subclassing one of these
2269 types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
2270 create :term:`descriptor`\s which allow reading and writing the fields by direct
2271 attribute accesses.  These are the
2274 .. attribute:: Structure._fields_
2276    A sequence defining the structure fields.  The items must be 2-tuples or
2277    3-tuples.  The first item is the name of the field, the second item specifies
2278    the type of the field; it can be any ctypes data type.
2280    For integer type fields like :class:`c_int`, a third optional item can be given.
2281    It must be a small positive integer defining the bit width of the field.
2283    Field names must be unique within one structure or union.  This is not checked,
2284    only one field can be accessed when names are repeated.
2286    It is possible to define the :attr:`_fields_` class variable *after* the class
2287    statement that defines the Structure subclass, this allows to create data types
2288    that directly or indirectly reference themselves::
2290       class List(Structure):
2291           pass
2292       List._fields_ = [("pnext", POINTER(List)),
2293                        ...
2294                       ]
2296    The :attr:`_fields_` class variable must, however, be defined before the type is
2297    first used (an instance is created, ``sizeof()`` is called on it, and so on).
2298    Later assignments to the :attr:`_fields_` class variable will raise an
2299    AttributeError.
2301    Structure and union subclass constructors accept both positional and named
2302    arguments.  Positional arguments are used to initialize the fields in the same
2303    order as they appear in the :attr:`_fields_` definition, named arguments are
2304    used to initialize the fields with the corresponding name.
2306    It is possible to defined sub-subclasses of structure types, they inherit the
2307    fields of the base class plus the :attr:`_fields_` defined in the sub-subclass,
2308    if any.
2311 .. attribute:: Structure._pack_
2313    An optional small integer that allows to override the alignment of structure
2314    fields in the instance.  :attr:`_pack_` must already be defined when
2315    :attr:`_fields_` is assigned, otherwise it will have no effect.
2318 .. attribute:: Structure._anonymous_
2320    An optional sequence that lists the names of unnamed (anonymous) fields.
2321    ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
2322    otherwise it will have no effect.
2324    The fields listed in this variable must be structure or union type fields.
2325    ``ctypes`` will create descriptors in the structure type that allows to access
2326    the nested fields directly, without the need to create the structure or union
2327    field.
2329    Here is an example type (Windows)::
2331       class _U(Union):
2332           _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2333                       ("lpadesc", POINTER(ARRAYDESC)),
2334                       ("hreftype", HREFTYPE)]
2336       class TYPEDESC(Structure):
2337           _fields_ = [("u", _U),
2338                       ("vt", VARTYPE)]
2340           _anonymous_ = ("u",)
2342    The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field specifies
2343    which one of the union fields is valid.  Since the ``u`` field is defined as
2344    anonymous field, it is now possible to access the members directly off the
2345    TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` are equivalent, but the
2346    former is faster since it does not need to create a temporary union instance::
2348       td = TYPEDESC()
2349       td.vt = VT_PTR
2350       td.lptdesc = POINTER(some_type)
2351       td.u.lptdesc = POINTER(some_type)
2353 It is possible to defined sub-subclasses of structures, they inherit the fields
2354 of the base class.  If the subclass definition has a separate :attr:`_fields_`
2355 variable, the fields specified in this are appended to the fields of the base
2356 class.
2358 Structure and union constructors accept both positional and keyword arguments.
2359 Positional arguments are used to initialize member fields in the same order as
2360 they are appear in :attr:`_fields_`.  Keyword arguments in the constructor are
2361 interpreted as attribute assignments, so they will initialize :attr:`_fields_`
2362 with the same name, or create new attributes for names not present in
2363 :attr:`_fields_`.
2366 .. _ctypes-arrays-pointers:
2368 Arrays and pointers
2369 ^^^^^^^^^^^^^^^^^^^
2371 Not yet written - please see the sections :ref:`ctypes-pointers` and
2372 section :ref:`ctypes-arrays` in the tutorial.