• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`ctypes` --- A foreign function library for Python
2=======================================================
3
4.. module:: ctypes
5   :synopsis: A foreign function library for Python.
6
7.. moduleauthor:: Thomas Heller <theller@python.net>
8
9--------------
10
11:mod:`ctypes` is a foreign function library for Python.  It provides C compatible
12data types, and allows calling functions in DLLs or shared libraries.  It can be
13used to wrap these libraries in pure Python.
14
15
16.. _ctypes-ctypes-tutorial:
17
18ctypes tutorial
19---------------
20
21Note: The code samples in this tutorial use :mod:`doctest` to make sure that
22they actually work.  Since some code samples behave differently under Linux,
23Windows, or Mac OS X, they contain doctest directives in comments.
24
25Note: Some code samples reference the ctypes :class:`c_int` type.  On platforms
26where ``sizeof(long) == sizeof(int)`` it is an alias to :class:`c_long`.
27So, you should not be confused if :class:`c_long` is printed if you would expect
28:class:`c_int` --- they are actually the same type.
29
30.. _ctypes-loading-dynamic-link-libraries:
31
32Loading dynamic link libraries
33^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
34
35:mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll*
36objects, for loading dynamic link libraries.
37
38You load libraries by accessing them as attributes of these objects. *cdll*
39loads libraries which export functions using the standard ``cdecl`` calling
40convention, while *windll* libraries call functions using the ``stdcall``
41calling convention. *oledll* also uses the ``stdcall`` calling convention, and
42assumes the functions return a Windows :c:type:`HRESULT` error code. The error
43code is used to automatically raise an :class:`OSError` exception when the
44function call fails.
45
46.. versionchanged:: 3.3
47   Windows errors used to raise :exc:`WindowsError`, which is now an alias
48   of :exc:`OSError`.
49
50
51Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
52library containing most standard C functions, and uses the cdecl calling
53convention::
54
55   >>> from ctypes import *
56   >>> print(windll.kernel32)  # doctest: +WINDOWS
57   <WinDLL 'kernel32', handle ... at ...>
58   >>> print(cdll.msvcrt)      # doctest: +WINDOWS
59   <CDLL 'msvcrt', handle ... at ...>
60   >>> libc = cdll.msvcrt      # doctest: +WINDOWS
61   >>>
62
63Windows appends the usual ``.dll`` file suffix automatically.
64
65.. note::
66    Accessing the standard C library through ``cdll.msvcrt`` will use an
67    outdated version of the library that may be incompatible with the one
68    being used by Python. Where possible, use native Python functionality,
69    or else import and use the ``msvcrt`` module.
70
71On Linux, it is required to specify the filename *including* the extension to
72load a library, so attribute access can not be used to load libraries. Either the
73:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
74the library by creating an instance of CDLL by calling the constructor::
75
76   >>> cdll.LoadLibrary("libc.so.6")  # doctest: +LINUX
77   <CDLL 'libc.so.6', handle ... at ...>
78   >>> libc = CDLL("libc.so.6")       # doctest: +LINUX
79   >>> libc                           # doctest: +LINUX
80   <CDLL 'libc.so.6', handle ... at ...>
81   >>>
82
83.. XXX Add section for Mac OS X.
84
85
86.. _ctypes-accessing-functions-from-loaded-dlls:
87
88Accessing functions from loaded dlls
89^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
90
91Functions are accessed as attributes of dll objects::
92
93   >>> from ctypes import *
94   >>> libc.printf
95   <_FuncPtr object at 0x...>
96   >>> print(windll.kernel32.GetModuleHandleA)  # doctest: +WINDOWS
97   <_FuncPtr object at 0x...>
98   >>> print(windll.kernel32.MyOwnFunction)     # doctest: +WINDOWS
99   Traceback (most recent call last):
100     File "<stdin>", line 1, in <module>
101     File "ctypes.py", line 239, in __getattr__
102       func = _StdcallFuncPtr(name, self)
103   AttributeError: function 'MyOwnFunction' not found
104   >>>
105
106Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
107as well as UNICODE versions of a function. The UNICODE version is exported with
108an ``W`` appended to the name, while the ANSI version is exported with an ``A``
109appended to the name. The win32 ``GetModuleHandle`` function, which returns a
110*module handle* for a given module name, has the following C prototype, and a
111macro is used to expose one of them as ``GetModuleHandle`` depending on whether
112UNICODE is defined or not::
113
114   /* ANSI version */
115   HMODULE GetModuleHandleA(LPCSTR lpModuleName);
116   /* UNICODE version */
117   HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
118
119*windll* does not try to select one of them by magic, you must access the
120version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
121explicitly, and then call it with bytes or string objects respectively.
122
123Sometimes, dlls export functions with names which aren't valid Python
124identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
125:func:`getattr` to retrieve the function::
126
127   >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  # doctest: +WINDOWS
128   <_FuncPtr object at 0x...>
129   >>>
130
131On Windows, some dlls export functions not by name but by ordinal. These
132functions can be accessed by indexing the dll object with the ordinal number::
133
134   >>> cdll.kernel32[1]  # doctest: +WINDOWS
135   <_FuncPtr object at 0x...>
136   >>> cdll.kernel32[0]  # doctest: +WINDOWS
137   Traceback (most recent call last):
138     File "<stdin>", line 1, in <module>
139     File "ctypes.py", line 310, in __getitem__
140       func = _StdcallFuncPtr(name, self)
141   AttributeError: function ordinal 0 not found
142   >>>
143
144
145.. _ctypes-calling-functions:
146
147Calling functions
148^^^^^^^^^^^^^^^^^
149
150You can call these functions like any other Python callable. This example uses
151the ``time()`` function, which returns system time in seconds since the Unix
152epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
153handle.
154
155This example calls both functions with a ``NULL`` pointer (``None`` should be used
156as the ``NULL`` pointer)::
157
158   >>> print(libc.time(None))  # doctest: +SKIP
159   1150640792
160   >>> print(hex(windll.kernel32.GetModuleHandleA(None)))  # doctest: +WINDOWS
161   0x1d000000
162   >>>
163
164:exc:`ValueError` is raised when you call an ``stdcall`` function with the
165``cdecl`` calling convention, or vice versa::
166
167   >>> cdll.kernel32.GetModuleHandleA(None)  # doctest: +WINDOWS
168   Traceback (most recent call last):
169     File "<stdin>", line 1, in <module>
170   ValueError: Procedure probably called with not enough arguments (4 bytes missing)
171   >>>
172
173   >>> windll.msvcrt.printf(b"spam")  # doctest: +WINDOWS
174   Traceback (most recent call last):
175     File "<stdin>", line 1, in <module>
176   ValueError: Procedure probably called with too many arguments (4 bytes in excess)
177   >>>
178
179To find out the correct calling convention you have to look into the C header
180file or the documentation for the function you want to call.
181
182On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
183crashes from general protection faults when functions are called with invalid
184argument values::
185
186   >>> windll.kernel32.GetModuleHandleA(32)  # doctest: +WINDOWS
187   Traceback (most recent call last):
188     File "<stdin>", line 1, in <module>
189   OSError: exception: access violation reading 0x00000020
190   >>>
191
192There are, however, enough ways to crash Python with :mod:`ctypes`, so you
193should be careful anyway.  The :mod:`faulthandler` module can be helpful in
194debugging crashes (e.g. from segmentation faults produced by erroneous C library
195calls).
196
197``None``, integers, bytes objects and (unicode) strings are the only native
198Python objects that can directly be used as parameters in these function calls.
199``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are passed
200as pointer to the memory block that contains their data (:c:type:`char *` or
201:c:type:`wchar_t *`).  Python integers are passed as the platforms default C
202:c:type:`int` type, their value is masked to fit into the C type.
203
204Before we move on calling functions with other parameter types, we have to learn
205more about :mod:`ctypes` data types.
206
207
208.. _ctypes-fundamental-data-types:
209
210Fundamental data types
211^^^^^^^^^^^^^^^^^^^^^^
212
213:mod:`ctypes` defines a number of primitive C compatible data types:
214
215+----------------------+------------------------------------------+----------------------------+
216| ctypes type          | C type                                   | Python type                |
217+======================+==========================================+============================+
218| :class:`c_bool`      | :c:type:`_Bool`                          | bool (1)                   |
219+----------------------+------------------------------------------+----------------------------+
220| :class:`c_char`      | :c:type:`char`                           | 1-character bytes object   |
221+----------------------+------------------------------------------+----------------------------+
222| :class:`c_wchar`     | :c:type:`wchar_t`                        | 1-character string         |
223+----------------------+------------------------------------------+----------------------------+
224| :class:`c_byte`      | :c:type:`char`                           | int                        |
225+----------------------+------------------------------------------+----------------------------+
226| :class:`c_ubyte`     | :c:type:`unsigned char`                  | int                        |
227+----------------------+------------------------------------------+----------------------------+
228| :class:`c_short`     | :c:type:`short`                          | int                        |
229+----------------------+------------------------------------------+----------------------------+
230| :class:`c_ushort`    | :c:type:`unsigned short`                 | int                        |
231+----------------------+------------------------------------------+----------------------------+
232| :class:`c_int`       | :c:type:`int`                            | int                        |
233+----------------------+------------------------------------------+----------------------------+
234| :class:`c_uint`      | :c:type:`unsigned int`                   | int                        |
235+----------------------+------------------------------------------+----------------------------+
236| :class:`c_long`      | :c:type:`long`                           | int                        |
237+----------------------+------------------------------------------+----------------------------+
238| :class:`c_ulong`     | :c:type:`unsigned long`                  | int                        |
239+----------------------+------------------------------------------+----------------------------+
240| :class:`c_longlong`  | :c:type:`__int64` or :c:type:`long long` | int                        |
241+----------------------+------------------------------------------+----------------------------+
242| :class:`c_ulonglong` | :c:type:`unsigned __int64` or            | int                        |
243|                      | :c:type:`unsigned long long`             |                            |
244+----------------------+------------------------------------------+----------------------------+
245| :class:`c_size_t`    | :c:type:`size_t`                         | int                        |
246+----------------------+------------------------------------------+----------------------------+
247| :class:`c_ssize_t`   | :c:type:`ssize_t` or                     | int                        |
248|                      | :c:type:`Py_ssize_t`                     |                            |
249+----------------------+------------------------------------------+----------------------------+
250| :class:`c_float`     | :c:type:`float`                          | float                      |
251+----------------------+------------------------------------------+----------------------------+
252| :class:`c_double`    | :c:type:`double`                         | float                      |
253+----------------------+------------------------------------------+----------------------------+
254| :class:`c_longdouble`| :c:type:`long double`                    | float                      |
255+----------------------+------------------------------------------+----------------------------+
256| :class:`c_char_p`    | :c:type:`char *` (NUL terminated)        | bytes object or ``None``   |
257+----------------------+------------------------------------------+----------------------------+
258| :class:`c_wchar_p`   | :c:type:`wchar_t *` (NUL terminated)     | string or ``None``         |
259+----------------------+------------------------------------------+----------------------------+
260| :class:`c_void_p`    | :c:type:`void *`                         | int or ``None``            |
261+----------------------+------------------------------------------+----------------------------+
262
263(1)
264   The constructor accepts any object with a truth value.
265
266All these types can be created by calling them with an optional initializer of
267the correct type and value::
268
269   >>> c_int()
270   c_long(0)
271   >>> c_wchar_p("Hello, World")
272   c_wchar_p(140018365411392)
273   >>> c_ushort(-3)
274   c_ushort(65533)
275   >>>
276
277Since these types are mutable, their value can also be changed afterwards::
278
279   >>> i = c_int(42)
280   >>> print(i)
281   c_long(42)
282   >>> print(i.value)
283   42
284   >>> i.value = -99
285   >>> print(i.value)
286   -99
287   >>>
288
289Assigning a new value to instances of the pointer types :class:`c_char_p`,
290:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
291point to, *not the contents* of the memory block (of course not, because Python
292bytes objects are immutable)::
293
294   >>> s = "Hello, World"
295   >>> c_s = c_wchar_p(s)
296   >>> print(c_s)
297   c_wchar_p(139966785747344)
298   >>> print(c_s.value)
299   Hello World
300   >>> c_s.value = "Hi, there"
301   >>> print(c_s)              # the memory location has changed
302   c_wchar_p(139966783348904)
303   >>> print(c_s.value)
304   Hi, there
305   >>> print(s)                # first object is unchanged
306   Hello, World
307   >>>
308
309You should be careful, however, not to pass them to functions expecting pointers
310to mutable memory. If you need mutable memory blocks, ctypes has a
311:func:`create_string_buffer` function which creates these in various ways.  The
312current memory block contents can be accessed (or changed) with the ``raw``
313property; if you want to access it as NUL terminated string, use the ``value``
314property::
315
316   >>> from ctypes import *
317   >>> p = create_string_buffer(3)            # create a 3 byte buffer, initialized to NUL bytes
318   >>> print(sizeof(p), repr(p.raw))
319   3 b'\x00\x00\x00'
320   >>> p = create_string_buffer(b"Hello")     # create a buffer containing a NUL terminated string
321   >>> print(sizeof(p), repr(p.raw))
322   6 b'Hello\x00'
323   >>> print(repr(p.value))
324   b'Hello'
325   >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
326   >>> print(sizeof(p), repr(p.raw))
327   10 b'Hello\x00\x00\x00\x00\x00'
328   >>> p.value = b"Hi"
329   >>> print(sizeof(p), repr(p.raw))
330   10 b'Hi\x00lo\x00\x00\x00\x00\x00'
331   >>>
332
333The :func:`create_string_buffer` function replaces the :func:`c_buffer` function
334(which is still available as an alias), as well as the :func:`c_string` function
335from earlier ctypes releases.  To create a mutable memory block containing
336unicode characters of the C type :c:type:`wchar_t` use the
337:func:`create_unicode_buffer` function.
338
339
340.. _ctypes-calling-functions-continued:
341
342Calling functions, continued
343^^^^^^^^^^^^^^^^^^^^^^^^^^^^
344
345Note that printf prints to the real standard output channel, *not* to
346:data:`sys.stdout`, so these examples will only work at the console prompt, not
347from within *IDLE* or *PythonWin*::
348
349   >>> printf = libc.printf
350   >>> printf(b"Hello, %s\n", b"World!")
351   Hello, World!
352   14
353   >>> printf(b"Hello, %S\n", "World!")
354   Hello, World!
355   14
356   >>> printf(b"%d bottles of beer\n", 42)
357   42 bottles of beer
358   19
359   >>> printf(b"%f bottles of beer\n", 42.5)
360   Traceback (most recent call last):
361     File "<stdin>", line 1, in <module>
362   ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
363   >>>
364
365As has been mentioned before, all Python types except integers, strings, and
366bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so
367that they can be converted to the required C data type::
368
369   >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
370   An int 1234, a double 3.140000
371   31
372   >>>
373
374
375.. _ctypes-calling-functions-with-own-custom-data-types:
376
377Calling functions with your own custom data types
378^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
379
380You can also customize :mod:`ctypes` argument conversion to allow instances of
381your own classes be used as function arguments.  :mod:`ctypes` looks for an
382:attr:`_as_parameter_` attribute and uses this as the function argument.  Of
383course, it must be one of integer, string, or bytes::
384
385   >>> class Bottles:
386   ...     def __init__(self, number):
387   ...         self._as_parameter_ = number
388   ...
389   >>> bottles = Bottles(42)
390   >>> printf(b"%d bottles of beer\n", bottles)
391   42 bottles of beer
392   19
393   >>>
394
395If you don't want to store the instance's data in the :attr:`_as_parameter_`
396instance variable, you could define a :class:`property` which makes the
397attribute available on request.
398
399
400.. _ctypes-specifying-required-argument-types:
401
402Specifying the required argument types (function prototypes)
403^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
404
405It is possible to specify the required argument types of functions exported from
406DLLs by setting the :attr:`argtypes` attribute.
407
408:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
409probably not a good example here, because it takes a variable number and
410different types of parameters depending on the format string, on the other hand
411this is quite handy to experiment with this feature)::
412
413   >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
414   >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
415   String 'Hi', Int 10, Double 2.200000
416   37
417   >>>
418
419Specifying a format protects against incompatible argument types (just as a
420prototype for a C function), and tries to convert the arguments to valid types::
421
422   >>> printf(b"%d %d %d", 1, 2, 3)
423   Traceback (most recent call last):
424     File "<stdin>", line 1, in <module>
425   ArgumentError: argument 2: exceptions.TypeError: wrong type
426   >>> printf(b"%s %d %f\n", b"X", 2, 3)
427   X 2 3.000000
428   13
429   >>>
430
431If you have defined your own classes which you pass to function calls, you have
432to implement a :meth:`from_param` class method for them to be able to use them
433in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
434the Python object passed to the function call, it should do a typecheck or
435whatever is needed to make sure this object is acceptable, and then return the
436object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
437pass as the C function argument in this case. Again, the result should be an
438integer, string, bytes, a :mod:`ctypes` instance, or an object with an
439:attr:`_as_parameter_` attribute.
440
441
442.. _ctypes-return-types:
443
444Return types
445^^^^^^^^^^^^
446
447By default functions are assumed to return the C :c:type:`int` type.  Other
448return types can be specified by setting the :attr:`restype` attribute of the
449function object.
450
451Here is a more advanced example, it uses the ``strchr`` function, which expects
452a string pointer and a char, and returns a pointer to a string::
453
454   >>> strchr = libc.strchr
455   >>> strchr(b"abcdef", ord("d"))  # doctest: +SKIP
456   8059983
457   >>> strchr.restype = c_char_p    # c_char_p is a pointer to a string
458   >>> strchr(b"abcdef", ord("d"))
459   b'def'
460   >>> print(strchr(b"abcdef", ord("x")))
461   None
462   >>>
463
464If you want to avoid the ``ord("x")`` calls above, you can set the
465:attr:`argtypes` attribute, and the second argument will be converted from a
466single character Python bytes object into a C char::
467
468   >>> strchr.restype = c_char_p
469   >>> strchr.argtypes = [c_char_p, c_char]
470   >>> strchr(b"abcdef", b"d")
471   'def'
472   >>> strchr(b"abcdef", b"def")
473   Traceback (most recent call last):
474     File "<stdin>", line 1, in <module>
475   ArgumentError: argument 2: exceptions.TypeError: one character string expected
476   >>> print(strchr(b"abcdef", b"x"))
477   None
478   >>> strchr(b"abcdef", b"d")
479   'def'
480   >>>
481
482You can also use a callable Python object (a function or a class for example) as
483the :attr:`restype` attribute, if the foreign function returns an integer.  The
484callable will be called with the *integer* the C function returns, and the
485result of this call will be used as the result of your function call. This is
486useful to check for error return values and automatically raise an exception::
487
488   >>> GetModuleHandle = windll.kernel32.GetModuleHandleA  # doctest: +WINDOWS
489   >>> def ValidHandle(value):
490   ...     if value == 0:
491   ...         raise WinError()
492   ...     return value
493   ...
494   >>>
495   >>> GetModuleHandle.restype = ValidHandle  # doctest: +WINDOWS
496   >>> GetModuleHandle(None)  # doctest: +WINDOWS
497   486539264
498   >>> GetModuleHandle("something silly")  # doctest: +WINDOWS
499   Traceback (most recent call last):
500     File "<stdin>", line 1, in <module>
501     File "<stdin>", line 3, in ValidHandle
502   OSError: [Errno 126] The specified module could not be found.
503   >>>
504
505``WinError`` is a function which will call Windows ``FormatMessage()`` api to
506get the string representation of an error code, and *returns* an exception.
507``WinError`` takes an optional error code parameter, if no one is used, it calls
508:func:`GetLastError` to retrieve it.
509
510Please note that a much more powerful error checking mechanism is available
511through the :attr:`errcheck` attribute; see the reference manual for details.
512
513
514.. _ctypes-passing-pointers:
515
516Passing pointers (or: passing parameters by reference)
517^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
518
519Sometimes a C api function expects a *pointer* to a data type as parameter,
520probably to write into the corresponding location, or if the data is too large
521to be passed by value. This is also known as *passing parameters by reference*.
522
523:mod:`ctypes` exports the :func:`byref` function which is used to pass parameters
524by reference.  The same effect can be achieved with the :func:`pointer` function,
525although :func:`pointer` does a lot more work since it constructs a real pointer
526object, so it is faster to use :func:`byref` if you don't need the pointer
527object in Python itself::
528
529   >>> i = c_int()
530   >>> f = c_float()
531   >>> s = create_string_buffer(b'\000' * 32)
532   >>> print(i.value, f.value, repr(s.value))
533   0 0.0 b''
534   >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
535   ...             byref(i), byref(f), s)
536   3
537   >>> print(i.value, f.value, repr(s.value))
538   1 3.1400001049 b'Hello'
539   >>>
540
541
542.. _ctypes-structures-unions:
543
544Structures and unions
545^^^^^^^^^^^^^^^^^^^^^
546
547Structures and unions must derive from the :class:`Structure` and :class:`Union`
548base classes which are defined in the :mod:`ctypes` module. Each subclass must
549define a :attr:`_fields_` attribute.  :attr:`_fields_` must be a list of
550*2-tuples*, containing a *field name* and a *field type*.
551
552The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
553derived :mod:`ctypes` type: structure, union, array, pointer.
554
555Here is a simple example of a POINT structure, which contains two integers named
556*x* and *y*, and also shows how to initialize a structure in the constructor::
557
558   >>> from ctypes import *
559   >>> class POINT(Structure):
560   ...     _fields_ = [("x", c_int),
561   ...                 ("y", c_int)]
562   ...
563   >>> point = POINT(10, 20)
564   >>> print(point.x, point.y)
565   10 20
566   >>> point = POINT(y=5)
567   >>> print(point.x, point.y)
568   0 5
569   >>> POINT(1, 2, 3)
570   Traceback (most recent call last):
571     File "<stdin>", line 1, in <module>
572   TypeError: too many initializers
573   >>>
574
575You can, however, build much more complicated structures.  A structure can
576itself contain other structures by using a structure as a field type.
577
578Here is a RECT structure which contains two POINTs named *upperleft* and
579*lowerright*::
580
581   >>> class RECT(Structure):
582   ...     _fields_ = [("upperleft", POINT),
583   ...                 ("lowerright", POINT)]
584   ...
585   >>> rc = RECT(point)
586   >>> print(rc.upperleft.x, rc.upperleft.y)
587   0 5
588   >>> print(rc.lowerright.x, rc.lowerright.y)
589   0 0
590   >>>
591
592Nested structures can also be initialized in the constructor in several ways::
593
594   >>> r = RECT(POINT(1, 2), POINT(3, 4))
595   >>> r = RECT((1, 2), (3, 4))
596
597Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
598for debugging because they can provide useful information::
599
600   >>> print(POINT.x)
601   <Field type=c_long, ofs=0, size=4>
602   >>> print(POINT.y)
603   <Field type=c_long, ofs=4, size=4>
604   >>>
605
606
607.. _ctypes-structureunion-alignment-byte-order:
608
609.. warning::
610
611   :mod:`ctypes` does not support passing unions or structures with bit-fields
612   to functions by value.  While this may work on 32-bit x86, it's not
613   guaranteed by the library to work in the general case.  Unions and
614   structures with bit-fields should always be passed to functions by pointer.
615
616Structure/union alignment and byte order
617^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
618
619By default, Structure and Union fields are aligned in the same way the C
620compiler does it. It is possible to override this behavior by specifying a
621:attr:`_pack_` class attribute in the subclass definition. This must be set to a
622positive integer and specifies the maximum alignment for the fields. This is
623what ``#pragma pack(n)`` also does in MSVC.
624
625:mod:`ctypes` uses the native byte order for Structures and Unions.  To build
626structures with non-native byte order, you can use one of the
627:class:`BigEndianStructure`, :class:`LittleEndianStructure`,
628:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes.  These
629classes cannot contain pointer fields.
630
631
632.. _ctypes-bit-fields-in-structures-unions:
633
634Bit fields in structures and unions
635^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
636
637It is possible to create structures and unions containing bit fields. Bit fields
638are only possible for integer fields, the bit width is specified as the third
639item in the :attr:`_fields_` tuples::
640
641   >>> class Int(Structure):
642   ...     _fields_ = [("first_16", c_int, 16),
643   ...                 ("second_16", c_int, 16)]
644   ...
645   >>> print(Int.first_16)
646   <Field type=c_long, ofs=0:0, bits=16>
647   >>> print(Int.second_16)
648   <Field type=c_long, ofs=0:16, bits=16>
649   >>>
650
651
652.. _ctypes-arrays:
653
654Arrays
655^^^^^^
656
657Arrays are sequences, containing a fixed number of instances of the same type.
658
659The recommended way to create array types is by multiplying a data type with a
660positive integer::
661
662   TenPointsArrayType = POINT * 10
663
664Here is an example of a somewhat artificial data type, a structure containing 4
665POINTs among other stuff::
666
667   >>> from ctypes import *
668   >>> class POINT(Structure):
669   ...     _fields_ = ("x", c_int), ("y", c_int)
670   ...
671   >>> class MyStruct(Structure):
672   ...     _fields_ = [("a", c_int),
673   ...                 ("b", c_float),
674   ...                 ("point_array", POINT * 4)]
675   >>>
676   >>> print(len(MyStruct().point_array))
677   4
678   >>>
679
680Instances are created in the usual way, by calling the class::
681
682   arr = TenPointsArrayType()
683   for pt in arr:
684       print(pt.x, pt.y)
685
686The above code print a series of ``0 0`` lines, because the array contents is
687initialized to zeros.
688
689Initializers of the correct type can also be specified::
690
691   >>> from ctypes import *
692   >>> TenIntegers = c_int * 10
693   >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
694   >>> print(ii)
695   <c_long_Array_10 object at 0x...>
696   >>> for i in ii: print(i, end=" ")
697   ...
698   1 2 3 4 5 6 7 8 9 10
699   >>>
700
701
702.. _ctypes-pointers:
703
704Pointers
705^^^^^^^^
706
707Pointer instances are created by calling the :func:`pointer` function on a
708:mod:`ctypes` type::
709
710   >>> from ctypes import *
711   >>> i = c_int(42)
712   >>> pi = pointer(i)
713   >>>
714
715Pointer instances have a :attr:`~_Pointer.contents` attribute which
716returns the object to which the pointer points, the ``i`` object above::
717
718   >>> pi.contents
719   c_long(42)
720   >>>
721
722Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
723new, equivalent object each time you retrieve an attribute::
724
725   >>> pi.contents is i
726   False
727   >>> pi.contents is pi.contents
728   False
729   >>>
730
731Assigning another :class:`c_int` instance to the pointer's contents attribute
732would cause the pointer to point to the memory location where this is stored::
733
734   >>> i = c_int(99)
735   >>> pi.contents = i
736   >>> pi.contents
737   c_long(99)
738   >>>
739
740.. XXX Document dereferencing pointers, and that it is preferred over the
741   .contents attribute.
742
743Pointer instances can also be indexed with integers::
744
745   >>> pi[0]
746   99
747   >>>
748
749Assigning to an integer index changes the pointed to value::
750
751   >>> print(i)
752   c_long(99)
753   >>> pi[0] = 22
754   >>> print(i)
755   c_long(22)
756   >>>
757
758It is also possible to use indexes different from 0, but you must know what
759you're doing, just as in C: You can access or change arbitrary memory locations.
760Generally you only use this feature if you receive a pointer from a C function,
761and you *know* that the pointer actually points to an array instead of a single
762item.
763
764Behind the scenes, the :func:`pointer` function does more than simply create
765pointer instances, it has to create pointer *types* first. This is done with the
766:func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a
767new type::
768
769   >>> PI = POINTER(c_int)
770   >>> PI
771   <class 'ctypes.LP_c_long'>
772   >>> PI(42)
773   Traceback (most recent call last):
774     File "<stdin>", line 1, in <module>
775   TypeError: expected c_long instead of int
776   >>> PI(c_int(42))
777   <ctypes.LP_c_long object at 0x...>
778   >>>
779
780Calling the pointer type without an argument creates a ``NULL`` pointer.
781``NULL`` pointers have a ``False`` boolean value::
782
783   >>> null_ptr = POINTER(c_int)()
784   >>> print(bool(null_ptr))
785   False
786   >>>
787
788:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
789invalid non-\ ``NULL`` pointers would crash Python)::
790
791   >>> null_ptr[0]
792   Traceback (most recent call last):
793       ....
794   ValueError: NULL pointer access
795   >>>
796
797   >>> null_ptr[0] = 1234
798   Traceback (most recent call last):
799       ....
800   ValueError: NULL pointer access
801   >>>
802
803
804.. _ctypes-type-conversions:
805
806Type conversions
807^^^^^^^^^^^^^^^^
808
809Usually, ctypes does strict type checking.  This means, if you have
810``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
811a member field in a structure definition, only instances of exactly the same
812type are accepted.  There are some exceptions to this rule, where ctypes accepts
813other objects.  For example, you can pass compatible array instances instead of
814pointer types.  So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
815
816   >>> class Bar(Structure):
817   ...     _fields_ = [("count", c_int), ("values", POINTER(c_int))]
818   ...
819   >>> bar = Bar()
820   >>> bar.values = (c_int * 3)(1, 2, 3)
821   >>> bar.count = 3
822   >>> for i in range(bar.count):
823   ...     print(bar.values[i])
824   ...
825   1
826   2
827   3
828   >>>
829
830In addition, if a function argument is explicitly declared to be a pointer type
831(such as ``POINTER(c_int)``) in :attr:`argtypes`, an object of the pointed
832type (``c_int`` in this case) can be passed to the function.  ctypes will apply
833the required :func:`byref` conversion in this case automatically.
834
835To set a POINTER type field to ``NULL``, you can assign ``None``::
836
837   >>> bar.values = None
838   >>>
839
840.. XXX list other conversions...
841
842Sometimes you have instances of incompatible types.  In C, you can cast one type
843into another type.  :mod:`ctypes` provides a :func:`cast` function which can be
844used in the same way.  The ``Bar`` structure defined above accepts
845``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
846but not instances of other types::
847
848   >>> bar.values = (c_byte * 4)()
849   Traceback (most recent call last):
850     File "<stdin>", line 1, in <module>
851   TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
852   >>>
853
854For these cases, the :func:`cast` function is handy.
855
856The :func:`cast` function can be used to cast a ctypes instance into a pointer
857to a different ctypes data type.  :func:`cast` takes two parameters, a ctypes
858object that is or can be converted to a pointer of some kind, and a ctypes
859pointer type.  It returns an instance of the second argument, which references
860the same memory block as the first argument::
861
862   >>> a = (c_byte * 4)()
863   >>> cast(a, POINTER(c_int))
864   <ctypes.LP_c_long object at ...>
865   >>>
866
867So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the
868structure::
869
870   >>> bar = Bar()
871   >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
872   >>> print(bar.values[0])
873   0
874   >>>
875
876
877.. _ctypes-incomplete-types:
878
879Incomplete Types
880^^^^^^^^^^^^^^^^
881
882*Incomplete Types* are structures, unions or arrays whose members are not yet
883specified. In C, they are specified by forward declarations, which are defined
884later::
885
886   struct cell; /* forward declaration */
887
888   struct cell {
889       char *name;
890       struct cell *next;
891   };
892
893The straightforward translation into ctypes code would be this, but it does not
894work::
895
896   >>> class cell(Structure):
897   ...     _fields_ = [("name", c_char_p),
898   ...                 ("next", POINTER(cell))]
899   ...
900   Traceback (most recent call last):
901     File "<stdin>", line 1, in <module>
902     File "<stdin>", line 2, in cell
903   NameError: name 'cell' is not defined
904   >>>
905
906because the new ``class cell`` is not available in the class statement itself.
907In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_`
908attribute later, after the class statement::
909
910   >>> from ctypes import *
911   >>> class cell(Structure):
912   ...     pass
913   ...
914   >>> cell._fields_ = [("name", c_char_p),
915   ...                  ("next", POINTER(cell))]
916   >>>
917
918Let's try it. We create two instances of ``cell``, and let them point to each
919other, and finally follow the pointer chain a few times::
920
921   >>> c1 = cell()
922   >>> c1.name = "foo"
923   >>> c2 = cell()
924   >>> c2.name = "bar"
925   >>> c1.next = pointer(c2)
926   >>> c2.next = pointer(c1)
927   >>> p = c1
928   >>> for i in range(8):
929   ...     print(p.name, end=" ")
930   ...     p = p.next[0]
931   ...
932   foo bar foo bar foo bar foo bar
933   >>>
934
935
936.. _ctypes-callback-functions:
937
938Callback functions
939^^^^^^^^^^^^^^^^^^
940
941:mod:`ctypes` allows creating C callable function pointers from Python callables.
942These are sometimes called *callback functions*.
943
944First, you must create a class for the callback function. The class knows the
945calling convention, the return type, and the number and types of arguments this
946function will receive.
947
948The :func:`CFUNCTYPE` factory function creates types for callback functions
949using the ``cdecl`` calling convention. On Windows, the :func:`WINFUNCTYPE`
950factory function creates types for callback functions using the ``stdcall``
951calling convention.
952
953Both of these factory functions are called with the result type as first
954argument, and the callback functions expected argument types as the remaining
955arguments.
956
957I will present an example here which uses the standard C library's
958:c:func:`qsort` function, that is used to sort items with the help of a callback
959function.  :c:func:`qsort` will be used to sort an array of integers::
960
961   >>> IntArray5 = c_int * 5
962   >>> ia = IntArray5(5, 1, 7, 33, 99)
963   >>> qsort = libc.qsort
964   >>> qsort.restype = None
965   >>>
966
967:func:`qsort` must be called with a pointer to the data to sort, the number of
968items in the data array, the size of one item, and a pointer to the comparison
969function, the callback. The callback will then be called with two pointers to
970items, and it must return a negative integer if the first item is smaller than
971the second, a zero if they are equal, and a positive integer otherwise.
972
973So our callback function receives pointers to integers, and must return an
974integer. First we create the ``type`` for the callback function::
975
976   >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
977   >>>
978
979To get started, here is a simple callback that shows the values it gets
980passed::
981
982   >>> def py_cmp_func(a, b):
983   ...     print("py_cmp_func", a[0], b[0])
984   ...     return 0
985   ...
986   >>> cmp_func = CMPFUNC(py_cmp_func)
987   >>>
988
989The result::
990
991   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func)  # doctest: +LINUX
992   py_cmp_func 5 1
993   py_cmp_func 33 99
994   py_cmp_func 7 33
995   py_cmp_func 5 7
996   py_cmp_func 1 7
997   >>>
998
999Now we can actually compare the two items and return a useful result::
1000
1001   >>> def py_cmp_func(a, b):
1002   ...     print("py_cmp_func", a[0], b[0])
1003   ...     return a[0] - b[0]
1004   ...
1005   >>>
1006   >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1007   py_cmp_func 5 1
1008   py_cmp_func 33 99
1009   py_cmp_func 7 33
1010   py_cmp_func 1 7
1011   py_cmp_func 5 7
1012   >>>
1013
1014As we can easily check, our array is sorted now::
1015
1016   >>> for i in ia: print(i, end=" ")
1017   ...
1018   1 5 7 33 99
1019   >>>
1020
1021The function factories can be used as decorator factories, so we may as well
1022write::
1023
1024   >>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
1025   ... def py_cmp_func(a, b):
1026   ...     print("py_cmp_func", a[0], b[0])
1027   ...     return a[0] - b[0]
1028   ...
1029   >>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)
1030   py_cmp_func 5 1
1031   py_cmp_func 33 99
1032   py_cmp_func 7 33
1033   py_cmp_func 1 7
1034   py_cmp_func 5 7
1035   >>>
1036
1037.. note::
1038
1039   Make sure you keep references to :func:`CFUNCTYPE` objects as long as they
1040   are used from C code. :mod:`ctypes` doesn't, and if you don't, they may be
1041   garbage collected, crashing your program when a callback is made.
1042
1043   Also, note that if the callback function is called in a thread created
1044   outside of Python's control (e.g. by the foreign code that calls the
1045   callback), ctypes creates a new dummy Python thread on every invocation. This
1046   behavior is correct for most purposes, but it means that values stored with
1047   :class:`threading.local` will *not* survive across different callbacks, even when
1048   those calls are made from the same C thread.
1049
1050.. _ctypes-accessing-values-exported-from-dlls:
1051
1052Accessing values exported from dlls
1053^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1054
1055Some shared libraries not only export functions, they also export variables. An
1056example in the Python library itself is the :c:data:`Py_OptimizeFlag`, an integer
1057set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
1058startup.
1059
1060:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of
1061the type.  *pythonapi* is a predefined symbol giving access to the Python C
1062api::
1063
1064   >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
1065   >>> print(opt_flag)
1066   c_long(0)
1067   >>>
1068
1069If the interpreter would have been started with :option:`-O`, the sample would
1070have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1071specified.
1072
1073An extended example which also demonstrates the use of pointers accesses the
1074:c:data:`PyImport_FrozenModules` pointer exported by Python.
1075
1076Quoting the docs for that value:
1077
1078   This pointer is initialized to point to an array of :c:type:`struct _frozen`
1079   records, terminated by one whose members are all ``NULL`` or zero.  When a frozen
1080   module is imported, it is searched in this table.  Third-party code could play
1081   tricks with this to provide a dynamically created collection of frozen modules.
1082
1083So manipulating this pointer could even prove useful. To restrict the example
1084size, we show only how this table can be read with :mod:`ctypes`::
1085
1086   >>> from ctypes import *
1087   >>>
1088   >>> class struct_frozen(Structure):
1089   ...     _fields_ = [("name", c_char_p),
1090   ...                 ("code", POINTER(c_ubyte)),
1091   ...                 ("size", c_int)]
1092   ...
1093   >>>
1094
1095We have defined the :c:type:`struct _frozen` data type, so we can get the pointer
1096to the table::
1097
1098   >>> FrozenTable = POINTER(struct_frozen)
1099   >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1100   >>>
1101
1102Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1103can iterate over it, but we just have to make sure that our loop terminates,
1104because pointers have no size. Sooner or later it would probably crash with an
1105access violation or whatever, so it's better to break out of the loop when we
1106hit the ``NULL`` entry::
1107
1108   >>> for item in table:
1109   ...     if item.name is None:
1110   ...         break
1111   ...     print(item.name.decode("ascii"), item.size)
1112   ...
1113   _frozen_importlib 31764
1114   _frozen_importlib_external 41499
1115   __hello__ 161
1116   __phello__ -161
1117   __phello__.spam 161
1118   >>>
1119
1120The fact that standard Python has a frozen module and a frozen package
1121(indicated by the negative ``size`` member) is not well known, it is only used
1122for testing. Try it out with ``import __hello__`` for example.
1123
1124
1125.. _ctypes-surprises:
1126
1127Surprises
1128^^^^^^^^^
1129
1130There are some edges in :mod:`ctypes` where you might expect something other
1131than what actually happens.
1132
1133Consider the following example::
1134
1135   >>> from ctypes import *
1136   >>> class POINT(Structure):
1137   ...     _fields_ = ("x", c_int), ("y", c_int)
1138   ...
1139   >>> class RECT(Structure):
1140   ...     _fields_ = ("a", POINT), ("b", POINT)
1141   ...
1142   >>> p1 = POINT(1, 2)
1143   >>> p2 = POINT(3, 4)
1144   >>> rc = RECT(p1, p2)
1145   >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
1146   1 2 3 4
1147   >>> # now swap the two points
1148   >>> rc.a, rc.b = rc.b, rc.a
1149   >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
1150   3 4 3 4
1151   >>>
1152
1153Hm. We certainly expected the last statement to print ``3 4 1 2``. What
1154happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
1155
1156   >>> temp0, temp1 = rc.b, rc.a
1157   >>> rc.a = temp0
1158   >>> rc.b = temp1
1159   >>>
1160
1161Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1162the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1163contents of ``temp0`` into ``rc`` 's buffer.  This, in turn, changes the
1164contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1165the expected effect.
1166
1167Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1168doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
1169the root-object's underlying buffer.
1170
1171Another example that may behave differently from what one would expect is this::
1172
1173   >>> s = c_char_p()
1174   >>> s.value = b"abc def ghi"
1175   >>> s.value
1176   b'abc def ghi'
1177   >>> s.value is s.value
1178   False
1179   >>>
1180
1181.. note::
1182
1183   Objects instantiated from :class:`c_char_p` can only have their value set to bytes
1184   or integers.
1185
1186Why is it printing ``False``?  ctypes instances are objects containing a memory
1187block plus some :term:`descriptor`\s accessing the contents of the memory.
1188Storing a Python object in the memory block does not store the object itself,
1189instead the ``contents`` of the object is stored.  Accessing the contents again
1190constructs a new Python object each time!
1191
1192
1193.. _ctypes-variable-sized-data-types:
1194
1195Variable-sized data types
1196^^^^^^^^^^^^^^^^^^^^^^^^^
1197
1198:mod:`ctypes` provides some support for variable-sized arrays and structures.
1199
1200The :func:`resize` function can be used to resize the memory buffer of an
1201existing ctypes object.  The function takes the object as first argument, and
1202the requested size in bytes as the second argument.  The memory block cannot be
1203made smaller than the natural memory block specified by the objects type, a
1204:exc:`ValueError` is raised if this is tried::
1205
1206   >>> short_array = (c_short * 4)()
1207   >>> print(sizeof(short_array))
1208   8
1209   >>> resize(short_array, 4)
1210   Traceback (most recent call last):
1211       ...
1212   ValueError: minimum size is 8
1213   >>> resize(short_array, 32)
1214   >>> sizeof(short_array)
1215   32
1216   >>> sizeof(type(short_array))
1217   8
1218   >>>
1219
1220This is nice and fine, but how would one access the additional elements
1221contained in this array?  Since the type still only knows about 4 elements, we
1222get errors accessing other elements::
1223
1224   >>> short_array[:]
1225   [0, 0, 0, 0]
1226   >>> short_array[7]
1227   Traceback (most recent call last):
1228       ...
1229   IndexError: invalid index
1230   >>>
1231
1232Another way to use variable-sized data types with :mod:`ctypes` is to use the
1233dynamic nature of Python, and (re-)define the data type after the required size
1234is already known, on a case by case basis.
1235
1236
1237.. _ctypes-ctypes-reference:
1238
1239ctypes reference
1240----------------
1241
1242
1243.. _ctypes-finding-shared-libraries:
1244
1245Finding shared libraries
1246^^^^^^^^^^^^^^^^^^^^^^^^
1247
1248When programming in a compiled language, shared libraries are accessed when
1249compiling/linking a program, and when the program is run.
1250
1251The purpose of the :func:`find_library` function is to locate a library in a way
1252similar to what the compiler or runtime loader does (on platforms with several
1253versions of a shared library the most recent should be loaded), while the ctypes
1254library loaders act like when a program is run, and call the runtime loader
1255directly.
1256
1257The :mod:`ctypes.util` module provides a function which can help to determine
1258the library to load.
1259
1260
1261.. data:: find_library(name)
1262   :module: ctypes.util
1263   :noindex:
1264
1265   Try to find a library and return a pathname.  *name* is the library name without
1266   any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1267   is the form used for the posix linker option :option:`!-l`).  If no library can
1268   be found, returns ``None``.
1269
1270The exact functionality is system dependent.
1271
1272On Linux, :func:`find_library` tries to run external programs
1273(``/sbin/ldconfig``, ``gcc``, ``objdump`` and ``ld``) to find the library file.
1274It returns the filename of the library file.
1275
1276.. versionchanged:: 3.6
1277   On Linux, the value of the environment variable ``LD_LIBRARY_PATH`` is used
1278   when searching for libraries, if a library cannot be found by any other means.
1279
1280Here are some examples::
1281
1282   >>> from ctypes.util import find_library
1283   >>> find_library("m")
1284   'libm.so.6'
1285   >>> find_library("c")
1286   'libc.so.6'
1287   >>> find_library("bz2")
1288   'libbz2.so.1.0'
1289   >>>
1290
1291On OS X, :func:`find_library` tries several predefined naming schemes and paths
1292to locate the library, and returns a full pathname if successful::
1293
1294   >>> from ctypes.util import find_library
1295   >>> find_library("c")
1296   '/usr/lib/libc.dylib'
1297   >>> find_library("m")
1298   '/usr/lib/libm.dylib'
1299   >>> find_library("bz2")
1300   '/usr/lib/libbz2.dylib'
1301   >>> find_library("AGL")
1302   '/System/Library/Frameworks/AGL.framework/AGL'
1303   >>>
1304
1305On Windows, :func:`find_library` searches along the system search path, and
1306returns the full pathname, but since there is no predefined naming scheme a call
1307like ``find_library("c")`` will fail and return ``None``.
1308
1309If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
1310the shared library name at development time, and hardcode that into the wrapper
1311module instead of using :func:`find_library` to locate the library at runtime.
1312
1313
1314.. _ctypes-loading-shared-libraries:
1315
1316Loading shared libraries
1317^^^^^^^^^^^^^^^^^^^^^^^^
1318
1319There are several ways to load shared libraries into the Python process.  One
1320way is to instantiate one of the following classes:
1321
1322
1323.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0)
1324
1325   Instances of this class represent loaded shared libraries. Functions in these
1326   libraries use the standard C calling convention, and are assumed to return
1327   :c:type:`int`.
1328
1329
1330.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0)
1331
1332   Windows only: Instances of this class represent loaded shared libraries,
1333   functions in these libraries use the ``stdcall`` calling convention, and are
1334   assumed to return the windows specific :class:`HRESULT` code.  :class:`HRESULT`
1335   values contain information specifying whether the function call failed or
1336   succeeded, together with additional error code.  If the return value signals a
1337   failure, an :class:`OSError` is automatically raised.
1338
1339   .. versionchanged:: 3.3
1340      :exc:`WindowsError` used to be raised.
1341
1342
1343.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0)
1344
1345   Windows only: Instances of this class represent loaded shared libraries,
1346   functions in these libraries use the ``stdcall`` calling convention, and are
1347   assumed to return :c:type:`int` by default.
1348
1349   On Windows CE only the standard calling convention is used, for convenience the
1350   :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1351   platform.
1352
1353The Python :term:`global interpreter lock` is released before calling any
1354function exported by these libraries, and reacquired afterwards.
1355
1356
1357.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1358
1359   Instances of this class behave like :class:`CDLL` instances, except that the
1360   Python GIL is *not* released during the function call, and after the function
1361   execution the Python error flag is checked. If the error flag is set, a Python
1362   exception is raised.
1363
1364   Thus, this is only useful to call Python C api functions directly.
1365
1366All these classes can be instantiated by calling them with at least one
1367argument, the pathname of the shared library.  If you have an existing handle to
1368an already loaded shared library, it can be passed as the ``handle`` named
1369parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary``
1370function is used to load the library into the process, and to get a handle to
1371it.
1372
1373The *mode* parameter can be used to specify how the library is loaded.  For
1374details, consult the :manpage:`dlopen(3)` manpage.  On Windows, *mode* is
1375ignored.  On posix systems, RTLD_NOW is always added, and is not
1376configurable.
1377
1378The *use_errno* parameter, when set to true, enables a ctypes mechanism that
1379allows accessing the system :data:`errno` error number in a safe way.
1380:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1381variable; if you call foreign functions created with ``use_errno=True`` then the
1382:data:`errno` value before the function call is swapped with the ctypes private
1383copy, the same happens immediately after the function call.
1384
1385The function :func:`ctypes.get_errno` returns the value of the ctypes private
1386copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1387to a new value and returns the former value.
1388
1389The *use_last_error* parameter, when set to true, enables the same mechanism for
1390the Windows error code which is managed by the :func:`GetLastError` and
1391:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1392:func:`ctypes.set_last_error` are used to request and change the ctypes private
1393copy of the windows error code.
1394
1395The *winmode* parameter is used on Windows to specify how the library is loaded
1396(since *mode* is ignored). It takes any value that is valid for the Win32 API
1397``LoadLibraryEx`` flags parameter. When omitted, the default is to use the flags
1398that result in the most secure DLL load to avoiding issues such as DLL
1399hijacking. Passing the full path to the DLL is the safest way to ensure the
1400correct library and dependencies are loaded.
1401
1402.. versionchanged:: 3.8
1403   Added *winmode* parameter.
1404
1405
1406.. data:: RTLD_GLOBAL
1407   :noindex:
1408
1409   Flag to use as *mode* parameter.  On platforms where this flag is not available,
1410   it is defined as the integer zero.
1411
1412
1413.. data:: RTLD_LOCAL
1414   :noindex:
1415
1416   Flag to use as *mode* parameter.  On platforms where this is not available, it
1417   is the same as *RTLD_GLOBAL*.
1418
1419
1420.. data:: DEFAULT_MODE
1421   :noindex:
1422
1423   The default mode which is used to load shared libraries.  On OSX 10.3, this is
1424   *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1425
1426Instances of these classes have no public methods.  Functions exported by the
1427shared library can be accessed as attributes or by index.  Please note that
1428accessing the function through an attribute caches the result and therefore
1429accessing it repeatedly returns the same object each time.  On the other hand,
1430accessing it through an index returns a new object each time::
1431
1432   >>> from ctypes import CDLL
1433   >>> libc = CDLL("libc.so.6")  # On Linux
1434   >>> libc.time == libc.time
1435   True
1436   >>> libc['time'] == libc['time']
1437   False
1438
1439The following public attributes are available, their name starts with an
1440underscore to not clash with exported function names:
1441
1442
1443.. attribute:: PyDLL._handle
1444
1445   The system handle used to access the library.
1446
1447
1448.. attribute:: PyDLL._name
1449
1450   The name of the library passed in the constructor.
1451
1452Shared libraries can also be loaded by using one of the prefabricated objects,
1453which are instances of the :class:`LibraryLoader` class, either by calling the
1454:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1455loader instance.
1456
1457
1458.. class:: LibraryLoader(dlltype)
1459
1460   Class which loads shared libraries.  *dlltype* should be one of the
1461   :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1462
1463   :meth:`__getattr__` has special behavior: It allows loading a shared library by
1464   accessing it as attribute of a library loader instance.  The result is cached,
1465   so repeated attribute accesses return the same library each time.
1466
1467   .. method:: LoadLibrary(name)
1468
1469      Load a shared library into the process and return it.  This method always
1470      returns a new instance of the library.
1471
1472
1473These prefabricated library loaders are available:
1474
1475.. data:: cdll
1476   :noindex:
1477
1478   Creates :class:`CDLL` instances.
1479
1480
1481.. data:: windll
1482   :noindex:
1483
1484   Windows only: Creates :class:`WinDLL` instances.
1485
1486
1487.. data:: oledll
1488   :noindex:
1489
1490   Windows only: Creates :class:`OleDLL` instances.
1491
1492
1493.. data:: pydll
1494   :noindex:
1495
1496   Creates :class:`PyDLL` instances.
1497
1498
1499For accessing the C Python api directly, a ready-to-use Python shared library
1500object is available:
1501
1502.. data:: pythonapi
1503   :noindex:
1504
1505   An instance of :class:`PyDLL` that exposes Python C API functions as
1506   attributes.  Note that all these functions are assumed to return C
1507   :c:type:`int`, which is of course not always the truth, so you have to assign
1508   the correct :attr:`restype` attribute to use these functions.
1509
1510.. audit-event:: ctypes.dlopen name ctypes.LibraryLoader
1511
1512   Loading a library through any of these objects raises an
1513   :ref:`auditing event <auditing>` ``ctypes.dlopen`` with string argument
1514   ``name``, the name used to load the library.
1515
1516.. audit-event:: ctypes.dlsym library,name ctypes.LibraryLoader
1517
1518   Accessing a function on a loaded library raises an auditing event
1519   ``ctypes.dlsym`` with arguments ``library`` (the library object) and ``name``
1520   (the symbol's name as a string or integer).
1521
1522.. audit-event:: ctypes.dlsym/handle handle,name ctypes.LibraryLoader
1523
1524   In cases when only the library handle is available rather than the object,
1525   accessing a function raises an auditing event ``ctypes.dlsym/handle`` with
1526   arguments ``handle`` (the raw library handle) and ``name``.
1527
1528.. _ctypes-foreign-functions:
1529
1530Foreign functions
1531^^^^^^^^^^^^^^^^^
1532
1533As explained in the previous section, foreign functions can be accessed as
1534attributes of loaded shared libraries.  The function objects created in this way
1535by default accept any number of arguments, accept any ctypes data instances as
1536arguments, and return the default result type specified by the library loader.
1537They are instances of a private class:
1538
1539
1540.. class:: _FuncPtr
1541
1542   Base class for C callable foreign functions.
1543
1544   Instances of foreign functions are also C compatible data types; they
1545   represent C function pointers.
1546
1547   This behavior can be customized by assigning to special attributes of the
1548   foreign function object.
1549
1550   .. attribute:: restype
1551
1552      Assign a ctypes type to specify the result type of the foreign function.
1553      Use ``None`` for :c:type:`void`, a function not returning anything.
1554
1555      It is possible to assign a callable Python object that is not a ctypes
1556      type, in this case the function is assumed to return a C :c:type:`int`, and
1557      the callable will be called with this integer, allowing further
1558      processing or error checking.  Using this is deprecated, for more flexible
1559      post processing or error checking use a ctypes data type as
1560      :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
1561
1562   .. attribute:: argtypes
1563
1564      Assign a tuple of ctypes types to specify the argument types that the
1565      function accepts.  Functions using the ``stdcall`` calling convention can
1566      only be called with the same number of arguments as the length of this
1567      tuple; functions using the C calling convention accept additional,
1568      unspecified arguments as well.
1569
1570      When a foreign function is called, each actual argument is passed to the
1571      :meth:`from_param` class method of the items in the :attr:`argtypes`
1572      tuple, this method allows adapting the actual argument to an object that
1573      the foreign function accepts.  For example, a :class:`c_char_p` item in
1574      the :attr:`argtypes` tuple will convert a string passed as argument into
1575      a bytes object using ctypes conversion rules.
1576
1577      New: It is now possible to put items in argtypes which are not ctypes
1578      types, but each item must have a :meth:`from_param` method which returns a
1579      value usable as argument (integer, string, ctypes instance).  This allows
1580      defining adapters that can adapt custom objects as function parameters.
1581
1582   .. attribute:: errcheck
1583
1584      Assign a Python function or another callable to this attribute. The
1585      callable will be called with three or more arguments:
1586
1587      .. function:: callable(result, func, arguments)
1588         :noindex:
1589         :module:
1590
1591         *result* is what the foreign function returns, as specified by the
1592         :attr:`restype` attribute.
1593
1594         *func* is the foreign function object itself, this allows reusing the
1595         same callable object to check or post process the results of several
1596         functions.
1597
1598         *arguments* is a tuple containing the parameters originally passed to
1599         the function call, this allows specializing the behavior on the
1600         arguments used.
1601
1602      The object that this function returns will be returned from the
1603      foreign function call, but it can also check the result value
1604      and raise an exception if the foreign function call failed.
1605
1606
1607.. exception:: ArgumentError
1608
1609   This exception is raised when a foreign function call cannot convert one of the
1610   passed arguments.
1611
1612
1613.. audit-event:: ctypes.seh_exception code foreign-functions
1614
1615   On Windows, when a foreign function call raises a system exception (for
1616   example, due to an access violation), it will be captured and replaced with
1617   a suitable Python exception. Further, an auditing event
1618   ``ctypes.seh_exception`` with argument ``code`` will be raised, allowing an
1619   audit hook to replace the exception with its own.
1620
1621.. audit-event:: ctypes.call_function func_pointer,arguments ctype-foreign-functions
1622
1623   Some ways to invoke foreign function calls may raise an auditing event
1624   ``ctypes.call_function`` with arguments ``function pointer`` and ``arguments``.
1625
1626.. _ctypes-function-prototypes:
1627
1628Function prototypes
1629^^^^^^^^^^^^^^^^^^^
1630
1631Foreign functions can also be created by instantiating function prototypes.
1632Function prototypes are similar to function prototypes in C; they describe a
1633function (return type, argument types, calling convention) without defining an
1634implementation.  The factory functions must be called with the desired result
1635type and the argument types of the function, and can be used as decorator
1636factories, and as such, be applied to functions through the ``@wrapper`` syntax.
1637See :ref:`ctypes-callback-functions` for examples.
1638
1639
1640.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1641
1642   The returned function prototype creates functions that use the standard C
1643   calling convention.  The function will release the GIL during the call.  If
1644   *use_errno* is set to true, the ctypes private copy of the system
1645   :data:`errno` variable is exchanged with the real :data:`errno` value before
1646   and after the call; *use_last_error* does the same for the Windows error
1647   code.
1648
1649
1650.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1651
1652   Windows only: The returned function prototype creates functions that use the
1653   ``stdcall`` calling convention, except on Windows CE where
1654   :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`.  The function will
1655   release the GIL during the call.  *use_errno* and *use_last_error* have the
1656   same meaning as above.
1657
1658
1659.. function:: PYFUNCTYPE(restype, *argtypes)
1660
1661   The returned function prototype creates functions that use the Python calling
1662   convention.  The function will *not* release the GIL during the call.
1663
1664Function prototypes created by these factory functions can be instantiated in
1665different ways, depending on the type and number of the parameters in the call:
1666
1667
1668   .. function:: prototype(address)
1669      :noindex:
1670      :module:
1671
1672      Returns a foreign function at the specified address which must be an integer.
1673
1674
1675   .. function:: prototype(callable)
1676      :noindex:
1677      :module:
1678
1679      Create a C callable function (a callback function) from a Python *callable*.
1680
1681
1682   .. function:: prototype(func_spec[, paramflags])
1683      :noindex:
1684      :module:
1685
1686      Returns a foreign function exported by a shared library. *func_spec* must
1687      be a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of
1688      the exported function as string, or the ordinal of the exported function
1689      as small integer.  The second item is the shared library instance.
1690
1691
1692   .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1693      :noindex:
1694      :module:
1695
1696      Returns a foreign function that will call a COM method. *vtbl_index* is
1697      the index into the virtual function table, a small non-negative
1698      integer. *name* is name of the COM method. *iid* is an optional pointer to
1699      the interface identifier which is used in extended error reporting.
1700
1701      COM methods use a special calling convention: They require a pointer to
1702      the COM interface as first argument, in addition to those parameters that
1703      are specified in the :attr:`argtypes` tuple.
1704
1705   The optional *paramflags* parameter creates foreign function wrappers with much
1706   more functionality than the features described above.
1707
1708   *paramflags* must be a tuple of the same length as :attr:`argtypes`.
1709
1710   Each item in this tuple contains further information about a parameter, it must
1711   be a tuple containing one, two, or three items.
1712
1713   The first item is an integer containing a combination of direction
1714   flags for the parameter:
1715
1716      1
1717         Specifies an input parameter to the function.
1718
1719      2
1720         Output parameter.  The foreign function fills in a value.
1721
1722      4
1723         Input parameter which defaults to the integer zero.
1724
1725   The optional second item is the parameter name as string.  If this is specified,
1726   the foreign function can be called with named parameters.
1727
1728   The optional third item is the default value for this parameter.
1729
1730This example demonstrates how to wrap the Windows ``MessageBoxW`` function so
1731that it supports default parameters and named arguments. The C declaration from
1732the windows header file is this::
1733
1734   WINUSERAPI int WINAPI
1735   MessageBoxW(
1736       HWND hWnd,
1737       LPCWSTR lpText,
1738       LPCWSTR lpCaption,
1739       UINT uType);
1740
1741Here is the wrapping with :mod:`ctypes`::
1742
1743   >>> from ctypes import c_int, WINFUNCTYPE, windll
1744   >>> from ctypes.wintypes import HWND, LPCWSTR, UINT
1745   >>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)
1746   >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0)
1747   >>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags)
1748
1749The ``MessageBox`` foreign function can now be called in these ways::
1750
1751   >>> MessageBox()
1752   >>> MessageBox(text="Spam, spam, spam")
1753   >>> MessageBox(flags=2, text="foo bar")
1754
1755A second example demonstrates output parameters.  The win32 ``GetWindowRect``
1756function retrieves the dimensions of a specified window by copying them into
1757``RECT`` structure that the caller has to supply.  Here is the C declaration::
1758
1759   WINUSERAPI BOOL WINAPI
1760   GetWindowRect(
1761        HWND hWnd,
1762        LPRECT lpRect);
1763
1764Here is the wrapping with :mod:`ctypes`::
1765
1766   >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1767   >>> from ctypes.wintypes import BOOL, HWND, RECT
1768   >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1769   >>> paramflags = (1, "hwnd"), (2, "lprect")
1770   >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1771   >>>
1772
1773Functions with output parameters will automatically return the output parameter
1774value if there is a single one, or a tuple containing the output parameter
1775values when there are more than one, so the GetWindowRect function now returns a
1776RECT instance, when called.
1777
1778Output parameters can be combined with the :attr:`errcheck` protocol to do
1779further output processing and error checking.  The win32 ``GetWindowRect`` api
1780function returns a ``BOOL`` to signal success or failure, so this function could
1781do the error checking, and raises an exception when the api call failed::
1782
1783   >>> def errcheck(result, func, args):
1784   ...     if not result:
1785   ...         raise WinError()
1786   ...     return args
1787   ...
1788   >>> GetWindowRect.errcheck = errcheck
1789   >>>
1790
1791If the :attr:`errcheck` function returns the argument tuple it receives
1792unchanged, :mod:`ctypes` continues the normal processing it does on the output
1793parameters.  If you want to return a tuple of window coordinates instead of a
1794``RECT`` instance, you can retrieve the fields in the function and return them
1795instead, the normal processing will no longer take place::
1796
1797   >>> def errcheck(result, func, args):
1798   ...     if not result:
1799   ...         raise WinError()
1800   ...     rc = args[1]
1801   ...     return rc.left, rc.top, rc.bottom, rc.right
1802   ...
1803   >>> GetWindowRect.errcheck = errcheck
1804   >>>
1805
1806
1807.. _ctypes-utility-functions:
1808
1809Utility functions
1810^^^^^^^^^^^^^^^^^
1811
1812.. function:: addressof(obj)
1813
1814   Returns the address of the memory buffer as integer.  *obj* must be an
1815   instance of a ctypes type.
1816
1817   .. audit-event:: ctypes.addressof obj ctypes.addressof
1818
1819
1820.. function:: alignment(obj_or_type)
1821
1822   Returns the alignment requirements of a ctypes type. *obj_or_type* must be a
1823   ctypes type or instance.
1824
1825
1826.. function:: byref(obj[, offset])
1827
1828   Returns a light-weight pointer to *obj*, which must be an instance of a
1829   ctypes type.  *offset* defaults to zero, and must be an integer that will be
1830   added to the internal pointer value.
1831
1832   ``byref(obj, offset)`` corresponds to this C code::
1833
1834      (((char *)&obj) + offset)
1835
1836   The returned object can only be used as a foreign function call parameter.
1837   It behaves similar to ``pointer(obj)``, but the construction is a lot faster.
1838
1839
1840.. function:: cast(obj, type)
1841
1842   This function is similar to the cast operator in C. It returns a new instance
1843   of *type* which points to the same memory block as *obj*.  *type* must be a
1844   pointer type, and *obj* must be an object that can be interpreted as a
1845   pointer.
1846
1847
1848.. function:: create_string_buffer(init_or_size, size=None)
1849
1850   This function creates a mutable character buffer. The returned object is a
1851   ctypes array of :class:`c_char`.
1852
1853   *init_or_size* must be an integer which specifies the size of the array, or a
1854   bytes object which will be used to initialize the array items.
1855
1856   If a bytes object is specified as first argument, the buffer is made one item
1857   larger than its length so that the last element in the array is a NUL
1858   termination character. An integer can be passed as second argument which allows
1859   specifying the size of the array if the length of the bytes should not be used.
1860
1861   .. audit-event:: ctypes.create_string_buffer init,size ctypes.create_string_buffer
1862
1863
1864.. function:: create_unicode_buffer(init_or_size, size=None)
1865
1866   This function creates a mutable unicode character buffer. The returned object is
1867   a ctypes array of :class:`c_wchar`.
1868
1869   *init_or_size* must be an integer which specifies the size of the array, or a
1870   string which will be used to initialize the array items.
1871
1872   If a string is specified as first argument, the buffer is made one item
1873   larger than the length of the string so that the last element in the array is a
1874   NUL termination character. An integer can be passed as second argument which
1875   allows specifying the size of the array if the length of the string should not
1876   be used.
1877
1878   .. audit-event:: ctypes.create_unicode_buffer init,size ctypes.create_unicode_buffer
1879
1880
1881.. function:: DllCanUnloadNow()
1882
1883   Windows only: This function is a hook which allows implementing in-process
1884   COM servers with ctypes.  It is called from the DllCanUnloadNow function that
1885   the _ctypes extension dll exports.
1886
1887
1888.. function:: DllGetClassObject()
1889
1890   Windows only: This function is a hook which allows implementing in-process
1891   COM servers with ctypes.  It is called from the DllGetClassObject function
1892   that the ``_ctypes`` extension dll exports.
1893
1894
1895.. function:: find_library(name)
1896   :module: ctypes.util
1897
1898   Try to find a library and return a pathname.  *name* is the library name
1899   without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
1900   number (this is the form used for the posix linker option :option:`!-l`).  If
1901   no library can be found, returns ``None``.
1902
1903   The exact functionality is system dependent.
1904
1905
1906.. function:: find_msvcrt()
1907   :module: ctypes.util
1908
1909   Windows only: return the filename of the VC runtime library used by Python,
1910   and by the extension modules.  If the name of the library cannot be
1911   determined, ``None`` is returned.
1912
1913   If you need to free memory, for example, allocated by an extension module
1914   with a call to the ``free(void *)``, it is important that you use the
1915   function in the same library that allocated the memory.
1916
1917
1918.. function:: FormatError([code])
1919
1920   Windows only: Returns a textual description of the error code *code*.  If no
1921   error code is specified, the last error code is used by calling the Windows
1922   api function GetLastError.
1923
1924
1925.. function:: GetLastError()
1926
1927   Windows only: Returns the last error code set by Windows in the calling thread.
1928   This function calls the Windows `GetLastError()` function directly,
1929   it does not return the ctypes-private copy of the error code.
1930
1931.. function:: get_errno()
1932
1933   Returns the current value of the ctypes-private copy of the system
1934   :data:`errno` variable in the calling thread.
1935
1936   .. audit-event:: ctypes.get_errno "" ctypes.get_errno
1937
1938.. function:: get_last_error()
1939
1940   Windows only: returns the current value of the ctypes-private copy of the system
1941   :data:`LastError` variable in the calling thread.
1942
1943   .. audit-event:: ctypes.get_last_error "" ctypes.get_last_error
1944
1945.. function:: memmove(dst, src, count)
1946
1947   Same as the standard C memmove library function: copies *count* bytes from
1948   *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can
1949   be converted to pointers.
1950
1951
1952.. function:: memset(dst, c, count)
1953
1954   Same as the standard C memset library function: fills the memory block at
1955   address *dst* with *count* bytes of value *c*. *dst* must be an integer
1956   specifying an address, or a ctypes instance.
1957
1958
1959.. function:: POINTER(type)
1960
1961   This factory function creates and returns a new ctypes pointer type. Pointer
1962   types are cached and reused internally, so calling this function repeatedly is
1963   cheap. *type* must be a ctypes type.
1964
1965
1966.. function:: pointer(obj)
1967
1968   This function creates a new pointer instance, pointing to *obj*. The returned
1969   object is of the type ``POINTER(type(obj))``.
1970
1971   Note: If you just want to pass a pointer to an object to a foreign function
1972   call, you should use ``byref(obj)`` which is much faster.
1973
1974
1975.. function:: resize(obj, size)
1976
1977   This function resizes the internal memory buffer of *obj*, which must be an
1978   instance of a ctypes type.  It is not possible to make the buffer smaller
1979   than the native size of the objects type, as given by ``sizeof(type(obj))``,
1980   but it is possible to enlarge the buffer.
1981
1982
1983.. function:: set_errno(value)
1984
1985   Set the current value of the ctypes-private copy of the system :data:`errno`
1986   variable in the calling thread to *value* and return the previous value.
1987
1988   .. audit-event:: ctypes.set_errno errno ctypes.set_errno
1989
1990
1991.. function:: set_last_error(value)
1992
1993   Windows only: set the current value of the ctypes-private copy of the system
1994   :data:`LastError` variable in the calling thread to *value* and return the
1995   previous value.
1996
1997   .. audit-event:: ctypes.set_last_error error ctypes.set_last_error
1998
1999
2000.. function:: sizeof(obj_or_type)
2001
2002   Returns the size in bytes of a ctypes type or instance memory buffer.
2003   Does the same as the C ``sizeof`` operator.
2004
2005
2006.. function:: string_at(address, size=-1)
2007
2008   This function returns the C string starting at memory address *address* as a bytes
2009   object. If size is specified, it is used as size, otherwise the string is assumed
2010   to be zero-terminated.
2011
2012   .. audit-event:: ctypes.string_at address,size ctypes.string_at
2013
2014
2015.. function:: WinError(code=None, descr=None)
2016
2017   Windows only: this function is probably the worst-named thing in ctypes. It
2018   creates an instance of OSError.  If *code* is not specified,
2019   ``GetLastError`` is called to determine the error code. If *descr* is not
2020   specified, :func:`FormatError` is called to get a textual description of the
2021   error.
2022
2023   .. versionchanged:: 3.3
2024      An instance of :exc:`WindowsError` used to be created.
2025
2026
2027.. function:: wstring_at(address, size=-1)
2028
2029   This function returns the wide character string starting at memory address
2030   *address* as a string.  If *size* is specified, it is used as the number of
2031   characters of the string, otherwise the string is assumed to be
2032   zero-terminated.
2033
2034   .. audit-event:: ctypes.wstring_at address,size ctypes.wstring_at
2035
2036
2037.. _ctypes-data-types:
2038
2039Data types
2040^^^^^^^^^^
2041
2042
2043.. class:: _CData
2044
2045   This non-public class is the common base class of all ctypes data types.
2046   Among other things, all ctypes type instances contain a memory block that
2047   hold C compatible data; the address of the memory block is returned by the
2048   :func:`addressof` helper function. Another instance variable is exposed as
2049   :attr:`_objects`; this contains other Python objects that need to be kept
2050   alive in case the memory block contains pointers.
2051
2052   Common methods of ctypes data types, these are all class methods (to be
2053   exact, they are methods of the :term:`metaclass`):
2054
2055   .. method:: _CData.from_buffer(source[, offset])
2056
2057      This method returns a ctypes instance that shares the buffer of the
2058      *source* object.  The *source* object must support the writeable buffer
2059      interface.  The optional *offset* parameter specifies an offset into the
2060      source buffer in bytes; the default is zero.  If the source buffer is not
2061      large enough a :exc:`ValueError` is raised.
2062
2063      .. audit-event:: ctypes.cdata/buffer pointer,size,offset ctypes._CData.from_buffer
2064
2065   .. method:: _CData.from_buffer_copy(source[, offset])
2066
2067      This method creates a ctypes instance, copying the buffer from the
2068      *source* object buffer which must be readable.  The optional *offset*
2069      parameter specifies an offset into the source buffer in bytes; the default
2070      is zero.  If the source buffer is not large enough a :exc:`ValueError` is
2071      raised.
2072
2073      .. audit-event:: ctypes.cdata/buffer pointer,size,offset ctypes._CData.from_buffer_copy
2074
2075   .. method:: from_address(address)
2076
2077      This method returns a ctypes type instance using the memory specified by
2078      *address* which must be an integer.
2079
2080      .. audit-event:: ctypes.cdata address ctypes._CData.from_address
2081
2082         This method, and others that indirectly call this method, raises an
2083         :ref:`auditing event <auditing>` ``ctypes.cdata`` with argument
2084         ``address``.
2085
2086   .. method:: from_param(obj)
2087
2088      This method adapts *obj* to a ctypes type.  It is called with the actual
2089      object used in a foreign function call when the type is present in the
2090      foreign function's :attr:`argtypes` tuple; it must return an object that
2091      can be used as a function call parameter.
2092
2093      All ctypes data types have a default implementation of this classmethod
2094      that normally returns *obj* if that is an instance of the type.  Some
2095      types accept other objects as well.
2096
2097   .. method:: in_dll(library, name)
2098
2099      This method returns a ctypes type instance exported by a shared
2100      library. *name* is the name of the symbol that exports the data, *library*
2101      is the loaded shared library.
2102
2103   Common instance variables of ctypes data types:
2104
2105   .. attribute:: _b_base_
2106
2107      Sometimes ctypes data instances do not own the memory block they contain,
2108      instead they share part of the memory block of a base object.  The
2109      :attr:`_b_base_` read-only member is the root ctypes object that owns the
2110      memory block.
2111
2112   .. attribute:: _b_needsfree_
2113
2114      This read-only variable is true when the ctypes data instance has
2115      allocated the memory block itself, false otherwise.
2116
2117   .. attribute:: _objects
2118
2119      This member is either ``None`` or a dictionary containing Python objects
2120      that need to be kept alive so that the memory block contents is kept
2121      valid.  This object is only exposed for debugging; never modify the
2122      contents of this dictionary.
2123
2124
2125.. _ctypes-fundamental-data-types-2:
2126
2127Fundamental data types
2128^^^^^^^^^^^^^^^^^^^^^^
2129
2130.. class:: _SimpleCData
2131
2132   This non-public class is the base class of all fundamental ctypes data
2133   types. It is mentioned here because it contains the common attributes of the
2134   fundamental ctypes data types.  :class:`_SimpleCData` is a subclass of
2135   :class:`_CData`, so it inherits their methods and attributes. ctypes data
2136   types that are not and do not contain pointers can now be pickled.
2137
2138   Instances have a single attribute:
2139
2140   .. attribute:: value
2141
2142      This attribute contains the actual value of the instance. For integer and
2143      pointer types, it is an integer, for character types, it is a single
2144      character bytes object or string, for character pointer types it is a
2145      Python bytes object or string.
2146
2147      When the ``value`` attribute is retrieved from a ctypes instance, usually
2148      a new object is returned each time.  :mod:`ctypes` does *not* implement
2149      original object return, always a new object is constructed.  The same is
2150      true for all other ctypes object instances.
2151
2152
2153Fundamental data types, when returned as foreign function call results, or, for
2154example, by retrieving structure field members or array items, are transparently
2155converted to native Python types.  In other words, if a foreign function has a
2156:attr:`restype` of :class:`c_char_p`, you will always receive a Python bytes
2157object, *not* a :class:`c_char_p` instance.
2158
2159.. XXX above is false, it actually returns a Unicode string
2160
2161Subclasses of fundamental data types do *not* inherit this behavior. So, if a
2162foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2163receive an instance of this subclass from the function call. Of course, you can
2164get the value of the pointer by accessing the ``value`` attribute.
2165
2166These are the fundamental ctypes data types:
2167
2168.. class:: c_byte
2169
2170   Represents the C :c:type:`signed char` datatype, and interprets the value as
2171   small integer.  The constructor accepts an optional integer initializer; no
2172   overflow checking is done.
2173
2174
2175.. class:: c_char
2176
2177   Represents the C :c:type:`char` datatype, and interprets the value as a single
2178   character.  The constructor accepts an optional string initializer, the
2179   length of the string must be exactly one character.
2180
2181
2182.. class:: c_char_p
2183
2184   Represents the C :c:type:`char *` datatype when it points to a zero-terminated
2185   string.  For a general character pointer that may also point to binary data,
2186   ``POINTER(c_char)`` must be used.  The constructor accepts an integer
2187   address, or a bytes object.
2188
2189
2190.. class:: c_double
2191
2192   Represents the C :c:type:`double` datatype.  The constructor accepts an
2193   optional float initializer.
2194
2195
2196.. class:: c_longdouble
2197
2198   Represents the C :c:type:`long double` datatype.  The constructor accepts an
2199   optional float initializer.  On platforms where ``sizeof(long double) ==
2200   sizeof(double)`` it is an alias to :class:`c_double`.
2201
2202.. class:: c_float
2203
2204   Represents the C :c:type:`float` datatype.  The constructor accepts an
2205   optional float initializer.
2206
2207
2208.. class:: c_int
2209
2210   Represents the C :c:type:`signed int` datatype.  The constructor accepts an
2211   optional integer initializer; no overflow checking is done.  On platforms
2212   where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
2213
2214
2215.. class:: c_int8
2216
2217   Represents the C 8-bit :c:type:`signed int` datatype.  Usually an alias for
2218   :class:`c_byte`.
2219
2220
2221.. class:: c_int16
2222
2223   Represents the C 16-bit :c:type:`signed int` datatype.  Usually an alias for
2224   :class:`c_short`.
2225
2226
2227.. class:: c_int32
2228
2229   Represents the C 32-bit :c:type:`signed int` datatype.  Usually an alias for
2230   :class:`c_int`.
2231
2232
2233.. class:: c_int64
2234
2235   Represents the C 64-bit :c:type:`signed int` datatype.  Usually an alias for
2236   :class:`c_longlong`.
2237
2238
2239.. class:: c_long
2240
2241   Represents the C :c:type:`signed long` datatype.  The constructor accepts an
2242   optional integer initializer; no overflow checking is done.
2243
2244
2245.. class:: c_longlong
2246
2247   Represents the C :c:type:`signed long long` datatype.  The constructor accepts
2248   an optional integer initializer; no overflow checking is done.
2249
2250
2251.. class:: c_short
2252
2253   Represents the C :c:type:`signed short` datatype.  The constructor accepts an
2254   optional integer initializer; no overflow checking is done.
2255
2256
2257.. class:: c_size_t
2258
2259   Represents the C :c:type:`size_t` datatype.
2260
2261
2262.. class:: c_ssize_t
2263
2264   Represents the C :c:type:`ssize_t` datatype.
2265
2266   .. versionadded:: 3.2
2267
2268
2269.. class:: c_ubyte
2270
2271   Represents the C :c:type:`unsigned char` datatype, it interprets the value as
2272   small integer.  The constructor accepts an optional integer initializer; no
2273   overflow checking is done.
2274
2275
2276.. class:: c_uint
2277
2278   Represents the C :c:type:`unsigned int` datatype.  The constructor accepts an
2279   optional integer initializer; no overflow checking is done.  On platforms
2280   where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
2281
2282
2283.. class:: c_uint8
2284
2285   Represents the C 8-bit :c:type:`unsigned int` datatype.  Usually an alias for
2286   :class:`c_ubyte`.
2287
2288
2289.. class:: c_uint16
2290
2291   Represents the C 16-bit :c:type:`unsigned int` datatype.  Usually an alias for
2292   :class:`c_ushort`.
2293
2294
2295.. class:: c_uint32
2296
2297   Represents the C 32-bit :c:type:`unsigned int` datatype.  Usually an alias for
2298   :class:`c_uint`.
2299
2300
2301.. class:: c_uint64
2302
2303   Represents the C 64-bit :c:type:`unsigned int` datatype.  Usually an alias for
2304   :class:`c_ulonglong`.
2305
2306
2307.. class:: c_ulong
2308
2309   Represents the C :c:type:`unsigned long` datatype.  The constructor accepts an
2310   optional integer initializer; no overflow checking is done.
2311
2312
2313.. class:: c_ulonglong
2314
2315   Represents the C :c:type:`unsigned long long` datatype.  The constructor
2316   accepts an optional integer initializer; no overflow checking is done.
2317
2318
2319.. class:: c_ushort
2320
2321   Represents the C :c:type:`unsigned short` datatype.  The constructor accepts
2322   an optional integer initializer; no overflow checking is done.
2323
2324
2325.. class:: c_void_p
2326
2327   Represents the C :c:type:`void *` type.  The value is represented as integer.
2328   The constructor accepts an optional integer initializer.
2329
2330
2331.. class:: c_wchar
2332
2333   Represents the C :c:type:`wchar_t` datatype, and interprets the value as a
2334   single character unicode string.  The constructor accepts an optional string
2335   initializer, the length of the string must be exactly one character.
2336
2337
2338.. class:: c_wchar_p
2339
2340   Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a
2341   zero-terminated wide character string.  The constructor accepts an integer
2342   address, or a string.
2343
2344
2345.. class:: c_bool
2346
2347   Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from
2348   C99).  Its value can be ``True`` or ``False``, and the constructor accepts any object
2349   that has a truth value.
2350
2351
2352.. class:: HRESULT
2353
2354   Windows only: Represents a :c:type:`HRESULT` value, which contains success or
2355   error information for a function or method call.
2356
2357
2358.. class:: py_object
2359
2360   Represents the C :c:type:`PyObject *` datatype.  Calling this without an
2361   argument creates a ``NULL`` :c:type:`PyObject *` pointer.
2362
2363The :mod:`ctypes.wintypes` module provides quite some other Windows specific
2364data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`.  Some
2365useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined.
2366
2367
2368.. _ctypes-structured-data-types:
2369
2370Structured data types
2371^^^^^^^^^^^^^^^^^^^^^
2372
2373
2374.. class:: Union(*args, **kw)
2375
2376   Abstract base class for unions in native byte order.
2377
2378
2379.. class:: BigEndianStructure(*args, **kw)
2380
2381   Abstract base class for structures in *big endian* byte order.
2382
2383
2384.. class:: LittleEndianStructure(*args, **kw)
2385
2386   Abstract base class for structures in *little endian* byte order.
2387
2388Structures with non-native byte order cannot contain pointer type fields, or any
2389other data types containing pointer type fields.
2390
2391
2392.. class:: Structure(*args, **kw)
2393
2394   Abstract base class for structures in *native* byte order.
2395
2396   Concrete structure and union types must be created by subclassing one of these
2397   types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
2398   create :term:`descriptor`\s which allow reading and writing the fields by direct
2399   attribute accesses.  These are the
2400
2401
2402   .. attribute:: _fields_
2403
2404      A sequence defining the structure fields.  The items must be 2-tuples or
2405      3-tuples.  The first item is the name of the field, the second item
2406      specifies the type of the field; it can be any ctypes data type.
2407
2408      For integer type fields like :class:`c_int`, a third optional item can be
2409      given.  It must be a small positive integer defining the bit width of the
2410      field.
2411
2412      Field names must be unique within one structure or union.  This is not
2413      checked, only one field can be accessed when names are repeated.
2414
2415      It is possible to define the :attr:`_fields_` class variable *after* the
2416      class statement that defines the Structure subclass, this allows creating
2417      data types that directly or indirectly reference themselves::
2418
2419         class List(Structure):
2420             pass
2421         List._fields_ = [("pnext", POINTER(List)),
2422                          ...
2423                         ]
2424
2425      The :attr:`_fields_` class variable must, however, be defined before the
2426      type is first used (an instance is created, :func:`sizeof` is called on it,
2427      and so on).  Later assignments to the :attr:`_fields_` class variable will
2428      raise an AttributeError.
2429
2430      It is possible to define sub-subclasses of structure types, they inherit
2431      the fields of the base class plus the :attr:`_fields_` defined in the
2432      sub-subclass, if any.
2433
2434
2435   .. attribute:: _pack_
2436
2437      An optional small integer that allows overriding the alignment of
2438      structure fields in the instance.  :attr:`_pack_` must already be defined
2439      when :attr:`_fields_` is assigned, otherwise it will have no effect.
2440
2441
2442   .. attribute:: _anonymous_
2443
2444      An optional sequence that lists the names of unnamed (anonymous) fields.
2445      :attr:`_anonymous_` must be already defined when :attr:`_fields_` is
2446      assigned, otherwise it will have no effect.
2447
2448      The fields listed in this variable must be structure or union type fields.
2449      :mod:`ctypes` will create descriptors in the structure type that allows
2450      accessing the nested fields directly, without the need to create the
2451      structure or union field.
2452
2453      Here is an example type (Windows)::
2454
2455         class _U(Union):
2456             _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2457                         ("lpadesc", POINTER(ARRAYDESC)),
2458                         ("hreftype", HREFTYPE)]
2459
2460         class TYPEDESC(Structure):
2461             _anonymous_ = ("u",)
2462             _fields_ = [("u", _U),
2463                         ("vt", VARTYPE)]
2464
2465
2466      The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2467      specifies which one of the union fields is valid.  Since the ``u`` field
2468      is defined as anonymous field, it is now possible to access the members
2469      directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2470      are equivalent, but the former is faster since it does not need to create
2471      a temporary union instance::
2472
2473         td = TYPEDESC()
2474         td.vt = VT_PTR
2475         td.lptdesc = POINTER(some_type)
2476         td.u.lptdesc = POINTER(some_type)
2477
2478   It is possible to define sub-subclasses of structures, they inherit the
2479   fields of the base class.  If the subclass definition has a separate
2480   :attr:`_fields_` variable, the fields specified in this are appended to the
2481   fields of the base class.
2482
2483   Structure and union constructors accept both positional and keyword
2484   arguments.  Positional arguments are used to initialize member fields in the
2485   same order as they are appear in :attr:`_fields_`.  Keyword arguments in the
2486   constructor are interpreted as attribute assignments, so they will initialize
2487   :attr:`_fields_` with the same name, or create new attributes for names not
2488   present in :attr:`_fields_`.
2489
2490
2491.. _ctypes-arrays-pointers:
2492
2493Arrays and pointers
2494^^^^^^^^^^^^^^^^^^^
2495
2496.. class:: Array(\*args)
2497
2498   Abstract base class for arrays.
2499
2500   The recommended way to create concrete array types is by multiplying any
2501   :mod:`ctypes` data type with a positive integer.  Alternatively, you can subclass
2502   this type and define :attr:`_length_` and :attr:`_type_` class variables.
2503   Array elements can be read and written using standard
2504   subscript and slice accesses; for slice reads, the resulting object is
2505   *not* itself an :class:`Array`.
2506
2507
2508   .. attribute:: _length_
2509
2510        A positive integer specifying the number of elements in the array.
2511        Out-of-range subscripts result in an :exc:`IndexError`. Will be
2512        returned by :func:`len`.
2513
2514
2515   .. attribute:: _type_
2516
2517        Specifies the type of each element in the array.
2518
2519
2520   Array subclass constructors accept positional arguments, used to
2521   initialize the elements in order.
2522
2523
2524.. class:: _Pointer
2525
2526   Private, abstract base class for pointers.
2527
2528   Concrete pointer types are created by calling :func:`POINTER` with the
2529   type that will be pointed to; this is done automatically by
2530   :func:`pointer`.
2531
2532   If a pointer points to an array, its elements can be read and
2533   written using standard subscript and slice accesses.  Pointer objects
2534   have no size, so :func:`len` will raise :exc:`TypeError`.  Negative
2535   subscripts will read from the memory *before* the pointer (as in C), and
2536   out-of-range subscripts will probably crash with an access violation (if
2537   you're lucky).
2538
2539
2540   .. attribute:: _type_
2541
2542        Specifies the type pointed to.
2543
2544   .. attribute:: contents
2545
2546        Returns the object to which to pointer points.  Assigning to this
2547        attribute changes the pointer to point to the assigned object.
2548
2549