blob: c1218ad32ec8c597819fe26ea8999c01f6362e7d [file] [log] [blame]
Georg Brandl71515ca2009-05-17 12:29:12 +00001:mod:`ctypes` --- A foreign function library for Python
2=======================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: ctypes
5 :synopsis: A foreign function library for Python.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Thomas Heller <theller@python.net>
8
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04009--------------
Georg Brandl116aa622007-08-15 14:28:22 +000010
Georg Brandl1d837bc2009-12-29 11:24:00 +000011:mod:`ctypes` is a foreign function library for Python. It provides C compatible
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000012data types, and allows calling functions in DLLs or shared libraries. It can be
Georg Brandl116aa622007-08-15 14:28:22 +000013used to wrap these libraries in pure Python.
14
15
16.. _ctypes-ctypes-tutorial:
17
18ctypes tutorial
19---------------
20
Georg Brandl1d837bc2009-12-29 11:24:00 +000021Note: 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.
Georg Brandl116aa622007-08-15 14:28:22 +000024
Berker Peksagd85a1e62016-06-02 12:17:51 -070025Note: Some code samples reference the ctypes :class:`c_int` type. On platforms
Berker Peksag8891dfe2016-06-02 15:28:00 -070026where ``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.
Georg Brandl116aa622007-08-15 14:28:22 +000029
30.. _ctypes-loading-dynamic-link-libraries:
31
32Loading dynamic link libraries
33^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
34
Georg Brandl8d8f1972009-06-08 13:27:23 +000035:mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll*
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000036objects, for loading dynamic link libraries.
Georg Brandl116aa622007-08-15 14:28:22 +000037
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
Georg Brandl60203b42010-10-06 10:11:56 +000042assumes the functions return a Windows :c:type:`HRESULT` error code. The error
Martin Panter7462b6492015-11-02 03:37:02 +000043code is used to automatically raise an :class:`OSError` exception when the
Georg Brandl1d837bc2009-12-29 11:24:00 +000044function call fails.
Georg Brandl116aa622007-08-15 14:28:22 +000045
Antoine Pitrou442ee032011-10-12 18:53:23 +020046.. versionchanged:: 3.3
47 Windows errors used to raise :exc:`WindowsError`, which is now an alias
48 of :exc:`OSError`.
49
50
Georg Brandl116aa622007-08-15 14:28:22 +000051Here 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 *
Serhiy Storchakadba90392016-05-10 12:01:23 +030056 >>> print(windll.kernel32) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000057 <WinDLL 'kernel32', handle ... at ...>
Serhiy Storchakadba90392016-05-10 12:01:23 +030058 >>> print(cdll.msvcrt) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000059 <CDLL 'msvcrt', handle ... at ...>
Serhiy Storchakadba90392016-05-10 12:01:23 +030060 >>> libc = cdll.msvcrt # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000061 >>>
62
Thomas Heller2fadaa22008-06-16 19:56:33 +000063Windows appends the usual ``.dll`` file suffix automatically.
Georg Brandl116aa622007-08-15 14:28:22 +000064
Steve Dowerd669b6b2016-03-12 08:25:22 -080065.. 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
Georg Brandl116aa622007-08-15 14:28:22 +000071On Linux, it is required to specify the filename *including* the extension to
Thomas Heller2fadaa22008-06-16 19:56:33 +000072load a library, so attribute access can not be used to load libraries. Either the
Georg Brandl116aa622007-08-15 14:28:22 +000073: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
Serhiy Storchakadba90392016-05-10 12:01:23 +030076 >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
Georg Brandl116aa622007-08-15 14:28:22 +000077 <CDLL 'libc.so.6', handle ... at ...>
Serhiy Storchakadba90392016-05-10 12:01:23 +030078 >>> libc = CDLL("libc.so.6") # doctest: +LINUX
79 >>> libc # doctest: +LINUX
Georg Brandl116aa622007-08-15 14:28:22 +000080 <CDLL 'libc.so.6', handle ... at ...>
81 >>>
82
Christian Heimes5b5e81c2007-12-31 16:14:33 +000083.. XXX Add section for Mac OS X.
Georg Brandl116aa622007-08-15 14:28:22 +000084
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...>
Serhiy Storchakadba90392016-05-10 12:01:23 +030096 >>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000097 <_FuncPtr object at 0x...>
Serhiy Storchakadba90392016-05-10 12:01:23 +030098 >>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000099 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530100 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000101 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``
Georg Brandl8d8f1972009-06-08 13:27:23 +0000121explicitly, and then call it with bytes or string objects respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123Sometimes, dlls export functions with names which aren't valid Python
Georg Brandl1d837bc2009-12-29 11:24:00 +0000124identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
125:func:`getattr` to retrieve the function::
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Serhiy Storchakadba90392016-05-10 12:01:23 +0300127 >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000128 <_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
Serhiy Storchakadba90392016-05-10 12:01:23 +0300134 >>> cdll.kernel32[1] # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000135 <_FuncPtr object at 0x...>
Serhiy Storchakadba90392016-05-10 12:01:23 +0300136 >>> cdll.kernel32[0] # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000137 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530138 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000139 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
Serhiy Storchakadba90392016-05-10 12:01:23 +0300158 >>> print(libc.time(None)) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000159 1150640792
Serhiy Storchakadba90392016-05-10 12:01:23 +0300160 >>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000161 0x1d000000
162 >>>
163
Mariattaf931fd12017-05-27 07:23:26 -0700164.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000165
Mariattaf931fd12017-05-27 07:23:26 -0700166 :mod:`ctypes` may raise a :exc:`ValueError` after calling the function, if
167 it detects that an invalid number of arguments were passed. This behavior
168 should not be relied upon. It is deprecated in 3.6.2, and will be removed
169 in 3.7.
Georg Brandl116aa622007-08-15 14:28:22 +0000170
Mariattaf931fd12017-05-27 07:23:26 -0700171:exc:`ValueError` is raised when you call an ``stdcall`` function with the
Georg Brandl116aa622007-08-15 14:28:22 +0000172``cdecl`` calling convention, or vice versa::
173
Serhiy Storchakadba90392016-05-10 12:01:23 +0300174 >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000175 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530176 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000177 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
178 >>>
179
Serhiy Storchakadba90392016-05-10 12:01:23 +0300180 >>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000181 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530182 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000183 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
184 >>>
185
186To find out the correct calling convention you have to look into the C header
187file or the documentation for the function you want to call.
188
Georg Brandl8d8f1972009-06-08 13:27:23 +0000189On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
Georg Brandl116aa622007-08-15 14:28:22 +0000190crashes from general protection faults when functions are called with invalid
191argument values::
192
Serhiy Storchakadba90392016-05-10 12:01:23 +0300193 >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000194 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530195 File "<stdin>", line 1, in <module>
Antoine Pitrou442ee032011-10-12 18:53:23 +0200196 OSError: exception: access violation reading 0x00000020
Georg Brandl116aa622007-08-15 14:28:22 +0000197 >>>
198
Georg Brandl1d837bc2009-12-29 11:24:00 +0000199There are, however, enough ways to crash Python with :mod:`ctypes`, so you
Georg Brandlb33c6eb2013-10-06 10:51:01 +0200200should be careful anyway. The :mod:`faulthandler` module can be helpful in
201debugging crashes (e.g. from segmentation faults produced by erroneous C library
202calls).
Georg Brandl116aa622007-08-15 14:28:22 +0000203
Georg Brandl8d8f1972009-06-08 13:27:23 +0000204``None``, integers, bytes objects and (unicode) strings are the only native
Georg Brandl116aa622007-08-15 14:28:22 +0000205Python objects that can directly be used as parameters in these function calls.
Georg Brandl1d837bc2009-12-29 11:24:00 +0000206``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are passed
Georg Brandl60203b42010-10-06 10:11:56 +0000207as pointer to the memory block that contains their data (:c:type:`char *` or
208:c:type:`wchar_t *`). Python integers are passed as the platforms default C
209:c:type:`int` type, their value is masked to fit into the C type.
Georg Brandl116aa622007-08-15 14:28:22 +0000210
211Before we move on calling functions with other parameter types, we have to learn
Georg Brandl8d8f1972009-06-08 13:27:23 +0000212more about :mod:`ctypes` data types.
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
215.. _ctypes-fundamental-data-types:
216
217Fundamental data types
218^^^^^^^^^^^^^^^^^^^^^^
219
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200220:mod:`ctypes` defines a number of primitive C compatible data types:
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Georg Brandl60203b42010-10-06 10:11:56 +0000222+----------------------+------------------------------------------+----------------------------+
223| ctypes type | C type | Python type |
224+======================+==========================================+============================+
Georg Brandlecdd63f2011-01-19 20:05:49 +0000225| :class:`c_bool` | :c:type:`_Bool` | bool (1) |
226+----------------------+------------------------------------------+----------------------------+
Georg Brandl60203b42010-10-06 10:11:56 +0000227| :class:`c_char` | :c:type:`char` | 1-character bytes object |
228+----------------------+------------------------------------------+----------------------------+
229| :class:`c_wchar` | :c:type:`wchar_t` | 1-character string |
230+----------------------+------------------------------------------+----------------------------+
231| :class:`c_byte` | :c:type:`char` | int |
232+----------------------+------------------------------------------+----------------------------+
233| :class:`c_ubyte` | :c:type:`unsigned char` | int |
234+----------------------+------------------------------------------+----------------------------+
235| :class:`c_short` | :c:type:`short` | int |
236+----------------------+------------------------------------------+----------------------------+
237| :class:`c_ushort` | :c:type:`unsigned short` | int |
238+----------------------+------------------------------------------+----------------------------+
239| :class:`c_int` | :c:type:`int` | int |
240+----------------------+------------------------------------------+----------------------------+
241| :class:`c_uint` | :c:type:`unsigned int` | int |
242+----------------------+------------------------------------------+----------------------------+
243| :class:`c_long` | :c:type:`long` | int |
244+----------------------+------------------------------------------+----------------------------+
245| :class:`c_ulong` | :c:type:`unsigned long` | int |
246+----------------------+------------------------------------------+----------------------------+
247| :class:`c_longlong` | :c:type:`__int64` or :c:type:`long long` | int |
248+----------------------+------------------------------------------+----------------------------+
249| :class:`c_ulonglong` | :c:type:`unsigned __int64` or | int |
250| | :c:type:`unsigned long long` | |
251+----------------------+------------------------------------------+----------------------------+
Antoine Pitrou52cc7222012-07-12 20:31:50 +0200252| :class:`c_size_t` | :c:type:`size_t` | int |
253+----------------------+------------------------------------------+----------------------------+
254| :class:`c_ssize_t` | :c:type:`ssize_t` or | int |
255| | :c:type:`Py_ssize_t` | |
256+----------------------+------------------------------------------+----------------------------+
Georg Brandl60203b42010-10-06 10:11:56 +0000257| :class:`c_float` | :c:type:`float` | float |
258+----------------------+------------------------------------------+----------------------------+
259| :class:`c_double` | :c:type:`double` | float |
260+----------------------+------------------------------------------+----------------------------+
261| :class:`c_longdouble`| :c:type:`long double` | float |
262+----------------------+------------------------------------------+----------------------------+
263| :class:`c_char_p` | :c:type:`char *` (NUL terminated) | bytes object or ``None`` |
264+----------------------+------------------------------------------+----------------------------+
265| :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | string or ``None`` |
266+----------------------+------------------------------------------+----------------------------+
267| :class:`c_void_p` | :c:type:`void *` | int or ``None`` |
268+----------------------+------------------------------------------+----------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Georg Brandlecdd63f2011-01-19 20:05:49 +0000270(1)
271 The constructor accepts any object with a truth value.
272
Georg Brandl116aa622007-08-15 14:28:22 +0000273All these types can be created by calling them with an optional initializer of
274the correct type and value::
275
276 >>> c_int()
277 c_long(0)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000278 >>> c_wchar_p("Hello, World")
Louie Lu0d637e22017-04-26 16:15:05 +0800279 c_wchar_p(140018365411392)
Georg Brandl116aa622007-08-15 14:28:22 +0000280 >>> c_ushort(-3)
281 c_ushort(65533)
282 >>>
283
284Since these types are mutable, their value can also be changed afterwards::
285
286 >>> i = c_int(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000287 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000288 c_long(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000289 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000290 42
291 >>> i.value = -99
Georg Brandl6911e3c2007-09-04 07:15:32 +0000292 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000293 -99
294 >>>
295
296Assigning a new value to instances of the pointer types :class:`c_char_p`,
297:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
298point to, *not the contents* of the memory block (of course not, because Python
Georg Brandl8d8f1972009-06-08 13:27:23 +0000299bytes objects are immutable)::
Georg Brandl116aa622007-08-15 14:28:22 +0000300
301 >>> s = "Hello, World"
Georg Brandl8d8f1972009-06-08 13:27:23 +0000302 >>> c_s = c_wchar_p(s)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000303 >>> print(c_s)
Louie Lu0d637e22017-04-26 16:15:05 +0800304 c_wchar_p(139966785747344)
305 >>> print(c_s.value)
306 Hello World
Georg Brandl116aa622007-08-15 14:28:22 +0000307 >>> c_s.value = "Hi, there"
Louie Lu0d637e22017-04-26 16:15:05 +0800308 >>> print(c_s) # the memory location has changed
309 c_wchar_p(139966783348904)
310 >>> print(c_s.value)
311 Hi, there
312 >>> print(s) # first object is unchanged
Georg Brandl116aa622007-08-15 14:28:22 +0000313 Hello, World
314 >>>
315
316You should be careful, however, not to pass them to functions expecting pointers
317to mutable memory. If you need mutable memory blocks, ctypes has a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000318:func:`create_string_buffer` function which creates these in various ways. The
Georg Brandl116aa622007-08-15 14:28:22 +0000319current memory block contents can be accessed (or changed) with the ``raw``
320property; if you want to access it as NUL terminated string, use the ``value``
321property::
322
323 >>> from ctypes import *
Georg Brandl8d8f1972009-06-08 13:27:23 +0000324 >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
Georg Brandl6911e3c2007-09-04 07:15:32 +0000325 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000326 3 b'\x00\x00\x00'
327 >>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string
Georg Brandl6911e3c2007-09-04 07:15:32 +0000328 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000329 6 b'Hello\x00'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000330 >>> print(repr(p.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000331 b'Hello'
332 >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000333 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000334 10 b'Hello\x00\x00\x00\x00\x00'
335 >>> p.value = b"Hi"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000336 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000337 10 b'Hi\x00lo\x00\x00\x00\x00\x00'
Georg Brandl116aa622007-08-15 14:28:22 +0000338 >>>
339
Georg Brandl1d837bc2009-12-29 11:24:00 +0000340The :func:`create_string_buffer` function replaces the :func:`c_buffer` function
341(which is still available as an alias), as well as the :func:`c_string` function
Georg Brandl8d8f1972009-06-08 13:27:23 +0000342from earlier ctypes releases. To create a mutable memory block containing
Georg Brandl60203b42010-10-06 10:11:56 +0000343unicode characters of the C type :c:type:`wchar_t` use the
Georg Brandl8d8f1972009-06-08 13:27:23 +0000344:func:`create_unicode_buffer` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346
347.. _ctypes-calling-functions-continued:
348
349Calling functions, continued
350^^^^^^^^^^^^^^^^^^^^^^^^^^^^
351
352Note that printf prints to the real standard output channel, *not* to
Georg Brandl8d8f1972009-06-08 13:27:23 +0000353:data:`sys.stdout`, so these examples will only work at the console prompt, not
354from within *IDLE* or *PythonWin*::
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356 >>> printf = libc.printf
Georg Brandl8d8f1972009-06-08 13:27:23 +0000357 >>> printf(b"Hello, %s\n", b"World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000358 Hello, World!
359 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000360 >>> printf(b"Hello, %S\n", "World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000361 Hello, World!
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000362 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000363 >>> printf(b"%d bottles of beer\n", 42)
Georg Brandl116aa622007-08-15 14:28:22 +0000364 42 bottles of beer
365 19
Georg Brandl8d8f1972009-06-08 13:27:23 +0000366 >>> printf(b"%f bottles of beer\n", 42.5)
Georg Brandl116aa622007-08-15 14:28:22 +0000367 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530368 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000369 ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
370 >>>
371
372As has been mentioned before, all Python types except integers, strings, and
Georg Brandl8d8f1972009-06-08 13:27:23 +0000373bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so
Georg Brandl116aa622007-08-15 14:28:22 +0000374that they can be converted to the required C data type::
375
Georg Brandl8d8f1972009-06-08 13:27:23 +0000376 >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000377 An int 1234, a double 3.140000
Georg Brandl116aa622007-08-15 14:28:22 +0000378 31
379 >>>
380
381
382.. _ctypes-calling-functions-with-own-custom-data-types:
383
384Calling functions with your own custom data types
385^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
386
Georg Brandl1d837bc2009-12-29 11:24:00 +0000387You can also customize :mod:`ctypes` argument conversion to allow instances of
388your own classes be used as function arguments. :mod:`ctypes` looks for an
389:attr:`_as_parameter_` attribute and uses this as the function argument. Of
Georg Brandl8d8f1972009-06-08 13:27:23 +0000390course, it must be one of integer, string, or bytes::
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Éric Araujo28053fb2010-11-22 03:09:19 +0000392 >>> class Bottles:
Georg Brandl116aa622007-08-15 14:28:22 +0000393 ... def __init__(self, number):
394 ... self._as_parameter_ = number
395 ...
396 >>> bottles = Bottles(42)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000397 >>> printf(b"%d bottles of beer\n", bottles)
Georg Brandl116aa622007-08-15 14:28:22 +0000398 42 bottles of beer
399 19
400 >>>
401
402If you don't want to store the instance's data in the :attr:`_as_parameter_`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000403instance variable, you could define a :class:`property` which makes the
404attribute available on request.
Georg Brandl116aa622007-08-15 14:28:22 +0000405
406
407.. _ctypes-specifying-required-argument-types:
408
409Specifying the required argument types (function prototypes)
410^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
411
412It is possible to specify the required argument types of functions exported from
413DLLs by setting the :attr:`argtypes` attribute.
414
415:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
416probably not a good example here, because it takes a variable number and
417different types of parameters depending on the format string, on the other hand
418this is quite handy to experiment with this feature)::
419
420 >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000421 >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
Georg Brandl116aa622007-08-15 14:28:22 +0000422 String 'Hi', Int 10, Double 2.200000
423 37
424 >>>
425
426Specifying a format protects against incompatible argument types (just as a
427prototype for a C function), and tries to convert the arguments to valid types::
428
Georg Brandl8d8f1972009-06-08 13:27:23 +0000429 >>> printf(b"%d %d %d", 1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000430 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530431 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000432 ArgumentError: argument 2: exceptions.TypeError: wrong type
Georg Brandl8d8f1972009-06-08 13:27:23 +0000433 >>> printf(b"%s %d %f\n", b"X", 2, 3)
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000434 X 2 3.000000
435 13
Georg Brandl116aa622007-08-15 14:28:22 +0000436 >>>
437
438If you have defined your own classes which you pass to function calls, you have
439to implement a :meth:`from_param` class method for them to be able to use them
440in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
441the Python object passed to the function call, it should do a typecheck or
442whatever is needed to make sure this object is acceptable, and then return the
Thomas Heller2fadaa22008-06-16 19:56:33 +0000443object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
Georg Brandl116aa622007-08-15 14:28:22 +0000444pass as the C function argument in this case. Again, the result should be an
Georg Brandl8d8f1972009-06-08 13:27:23 +0000445integer, string, bytes, a :mod:`ctypes` instance, or an object with an
Georg Brandl116aa622007-08-15 14:28:22 +0000446:attr:`_as_parameter_` attribute.
447
448
449.. _ctypes-return-types:
450
451Return types
452^^^^^^^^^^^^
453
Georg Brandl60203b42010-10-06 10:11:56 +0000454By default functions are assumed to return the C :c:type:`int` type. Other
Georg Brandl1d837bc2009-12-29 11:24:00 +0000455return types can be specified by setting the :attr:`restype` attribute of the
456function object.
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458Here is a more advanced example, it uses the ``strchr`` function, which expects
459a string pointer and a char, and returns a pointer to a string::
460
461 >>> strchr = libc.strchr
Serhiy Storchakadba90392016-05-10 12:01:23 +0300462 >>> strchr(b"abcdef", ord("d")) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000463 8059983
Serhiy Storchakadba90392016-05-10 12:01:23 +0300464 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
Georg Brandl8d8f1972009-06-08 13:27:23 +0000465 >>> strchr(b"abcdef", ord("d"))
466 b'def'
467 >>> print(strchr(b"abcdef", ord("x")))
Georg Brandl116aa622007-08-15 14:28:22 +0000468 None
469 >>>
470
471If you want to avoid the ``ord("x")`` calls above, you can set the
472:attr:`argtypes` attribute, and the second argument will be converted from a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000473single character Python bytes object into a C char::
Georg Brandl116aa622007-08-15 14:28:22 +0000474
475 >>> strchr.restype = c_char_p
476 >>> strchr.argtypes = [c_char_p, c_char]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000477 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000478 'def'
Georg Brandl8d8f1972009-06-08 13:27:23 +0000479 >>> strchr(b"abcdef", b"def")
Georg Brandl116aa622007-08-15 14:28:22 +0000480 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530481 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000482 ArgumentError: argument 2: exceptions.TypeError: one character string expected
Georg Brandl8d8f1972009-06-08 13:27:23 +0000483 >>> print(strchr(b"abcdef", b"x"))
Georg Brandl116aa622007-08-15 14:28:22 +0000484 None
Georg Brandl8d8f1972009-06-08 13:27:23 +0000485 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000486 'def'
487 >>>
488
489You can also use a callable Python object (a function or a class for example) as
490the :attr:`restype` attribute, if the foreign function returns an integer. The
Georg Brandl1d837bc2009-12-29 11:24:00 +0000491callable will be called with the *integer* the C function returns, and the
Georg Brandl116aa622007-08-15 14:28:22 +0000492result of this call will be used as the result of your function call. This is
493useful to check for error return values and automatically raise an exception::
494
Serhiy Storchakadba90392016-05-10 12:01:23 +0300495 >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000496 >>> def ValidHandle(value):
497 ... if value == 0:
498 ... raise WinError()
499 ... return value
500 ...
501 >>>
Serhiy Storchakadba90392016-05-10 12:01:23 +0300502 >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
503 >>> GetModuleHandle(None) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000504 486539264
Serhiy Storchakadba90392016-05-10 12:01:23 +0300505 >>> GetModuleHandle("something silly") # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000506 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530507 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000508 File "<stdin>", line 3, in ValidHandle
Antoine Pitrou442ee032011-10-12 18:53:23 +0200509 OSError: [Errno 126] The specified module could not be found.
Georg Brandl116aa622007-08-15 14:28:22 +0000510 >>>
511
512``WinError`` is a function which will call Windows ``FormatMessage()`` api to
513get the string representation of an error code, and *returns* an exception.
514``WinError`` takes an optional error code parameter, if no one is used, it calls
515:func:`GetLastError` to retrieve it.
516
517Please note that a much more powerful error checking mechanism is available
518through the :attr:`errcheck` attribute; see the reference manual for details.
519
520
521.. _ctypes-passing-pointers:
522
523Passing pointers (or: passing parameters by reference)
524^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
525
526Sometimes a C api function expects a *pointer* to a data type as parameter,
527probably to write into the corresponding location, or if the data is too large
528to be passed by value. This is also known as *passing parameters by reference*.
529
Georg Brandl8d8f1972009-06-08 13:27:23 +0000530:mod:`ctypes` exports the :func:`byref` function which is used to pass parameters
531by reference. The same effect can be achieved with the :func:`pointer` function,
532although :func:`pointer` does a lot more work since it constructs a real pointer
Georg Brandl116aa622007-08-15 14:28:22 +0000533object, so it is faster to use :func:`byref` if you don't need the pointer
534object in Python itself::
535
536 >>> i = c_int()
537 >>> f = c_float()
Georg Brandl8d8f1972009-06-08 13:27:23 +0000538 >>> s = create_string_buffer(b'\000' * 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000539 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000540 0 0.0 b''
541 >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
Georg Brandl116aa622007-08-15 14:28:22 +0000542 ... byref(i), byref(f), s)
543 3
Georg Brandl6911e3c2007-09-04 07:15:32 +0000544 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000545 1 3.1400001049 b'Hello'
Georg Brandl116aa622007-08-15 14:28:22 +0000546 >>>
547
548
549.. _ctypes-structures-unions:
550
551Structures and unions
552^^^^^^^^^^^^^^^^^^^^^
553
554Structures and unions must derive from the :class:`Structure` and :class:`Union`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000555base classes which are defined in the :mod:`ctypes` module. Each subclass must
Georg Brandl116aa622007-08-15 14:28:22 +0000556define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
557*2-tuples*, containing a *field name* and a *field type*.
558
Georg Brandl8d8f1972009-06-08 13:27:23 +0000559The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
560derived :mod:`ctypes` type: structure, union, array, pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562Here is a simple example of a POINT structure, which contains two integers named
Georg Brandl8d8f1972009-06-08 13:27:23 +0000563*x* and *y*, and also shows how to initialize a structure in the constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000564
565 >>> from ctypes import *
566 >>> class POINT(Structure):
567 ... _fields_ = [("x", c_int),
568 ... ("y", c_int)]
569 ...
570 >>> point = POINT(10, 20)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000571 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000572 10 20
573 >>> point = POINT(y=5)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000574 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000575 0 5
576 >>> POINT(1, 2, 3)
577 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530578 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000579 ValueError: too many initializers
580 >>>
581
Eli Benderskyf9164e12013-03-06 06:48:57 -0800582You can, however, build much more complicated structures. A structure can
583itself contain other structures by using a structure as a field type.
Georg Brandl116aa622007-08-15 14:28:22 +0000584
Georg Brandl1d837bc2009-12-29 11:24:00 +0000585Here is a RECT structure which contains two POINTs named *upperleft* and
586*lowerright*::
Georg Brandl116aa622007-08-15 14:28:22 +0000587
588 >>> class RECT(Structure):
589 ... _fields_ = [("upperleft", POINT),
590 ... ("lowerright", POINT)]
591 ...
592 >>> rc = RECT(point)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000593 >>> print(rc.upperleft.x, rc.upperleft.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000594 0 5
Georg Brandl6911e3c2007-09-04 07:15:32 +0000595 >>> print(rc.lowerright.x, rc.lowerright.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000596 0 0
597 >>>
598
599Nested structures can also be initialized in the constructor in several ways::
600
601 >>> r = RECT(POINT(1, 2), POINT(3, 4))
602 >>> r = RECT((1, 2), (3, 4))
603
Georg Brandl9afde1c2007-11-01 20:32:30 +0000604Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
605for debugging because they can provide useful information::
Georg Brandl116aa622007-08-15 14:28:22 +0000606
Georg Brandl6911e3c2007-09-04 07:15:32 +0000607 >>> print(POINT.x)
Georg Brandl116aa622007-08-15 14:28:22 +0000608 <Field type=c_long, ofs=0, size=4>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000609 >>> print(POINT.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000610 <Field type=c_long, ofs=4, size=4>
611 >>>
612
613
614.. _ctypes-structureunion-alignment-byte-order:
615
Eli Bendersky490cf442013-03-09 05:54:00 -0800616.. warning::
617
618 :mod:`ctypes` does not support passing unions or structures with bit-fields
619 to functions by value. While this may work on 32-bit x86, it's not
620 guaranteed by the library to work in the general case. Unions and
621 structures with bit-fields should always be passed to functions by pointer.
622
Georg Brandl116aa622007-08-15 14:28:22 +0000623Structure/union alignment and byte order
624^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
625
626By default, Structure and Union fields are aligned in the same way the C
Thomas Woutersed03b412007-08-28 21:37:11 +0000627compiler does it. It is possible to override this behavior be specifying a
Georg Brandl116aa622007-08-15 14:28:22 +0000628:attr:`_pack_` class attribute in the subclass definition. This must be set to a
629positive integer and specifies the maximum alignment for the fields. This is
630what ``#pragma pack(n)`` also does in MSVC.
631
Georg Brandl8d8f1972009-06-08 13:27:23 +0000632:mod:`ctypes` uses the native byte order for Structures and Unions. To build
Georg Brandl116aa622007-08-15 14:28:22 +0000633structures with non-native byte order, you can use one of the
Georg Brandl1d837bc2009-12-29 11:24:00 +0000634:class:`BigEndianStructure`, :class:`LittleEndianStructure`,
635:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These
636classes cannot contain pointer fields.
Georg Brandl116aa622007-08-15 14:28:22 +0000637
638
639.. _ctypes-bit-fields-in-structures-unions:
640
641Bit fields in structures and unions
642^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
643
644It is possible to create structures and unions containing bit fields. Bit fields
645are only possible for integer fields, the bit width is specified as the third
646item in the :attr:`_fields_` tuples::
647
648 >>> class Int(Structure):
649 ... _fields_ = [("first_16", c_int, 16),
650 ... ("second_16", c_int, 16)]
651 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000652 >>> print(Int.first_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000653 <Field type=c_long, ofs=0:0, bits=16>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000654 >>> print(Int.second_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000655 <Field type=c_long, ofs=0:16, bits=16>
656 >>>
657
658
659.. _ctypes-arrays:
660
661Arrays
662^^^^^^
663
664Arrays are sequences, containing a fixed number of instances of the same type.
665
666The recommended way to create array types is by multiplying a data type with a
667positive integer::
668
669 TenPointsArrayType = POINT * 10
670
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300671Here is an example of a somewhat artificial data type, a structure containing 4
Georg Brandl116aa622007-08-15 14:28:22 +0000672POINTs among other stuff::
673
674 >>> from ctypes import *
675 >>> class POINT(Structure):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300676 ... _fields_ = ("x", c_int), ("y", c_int)
Georg Brandl116aa622007-08-15 14:28:22 +0000677 ...
678 >>> class MyStruct(Structure):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300679 ... _fields_ = [("a", c_int),
680 ... ("b", c_float),
681 ... ("point_array", POINT * 4)]
Georg Brandl116aa622007-08-15 14:28:22 +0000682 >>>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000683 >>> print(len(MyStruct().point_array))
Georg Brandl116aa622007-08-15 14:28:22 +0000684 4
685 >>>
686
687Instances are created in the usual way, by calling the class::
688
689 arr = TenPointsArrayType()
690 for pt in arr:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000691 print(pt.x, pt.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000692
693The above code print a series of ``0 0`` lines, because the array contents is
694initialized to zeros.
695
696Initializers of the correct type can also be specified::
697
698 >>> from ctypes import *
699 >>> TenIntegers = c_int * 10
700 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000701 >>> print(ii)
Georg Brandl116aa622007-08-15 14:28:22 +0000702 <c_long_Array_10 object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000703 >>> for i in ii: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000704 ...
705 1 2 3 4 5 6 7 8 9 10
706 >>>
707
708
709.. _ctypes-pointers:
710
711Pointers
712^^^^^^^^
713
Georg Brandl8d8f1972009-06-08 13:27:23 +0000714Pointer instances are created by calling the :func:`pointer` function on a
715:mod:`ctypes` type::
Georg Brandl116aa622007-08-15 14:28:22 +0000716
717 >>> from ctypes import *
718 >>> i = c_int(42)
719 >>> pi = pointer(i)
720 >>>
721
Martin Panter34360c82016-01-29 10:12:19 +0000722Pointer instances have a :attr:`~_Pointer.contents` attribute which
723returns the object to which the pointer points, the ``i`` object above::
Georg Brandl116aa622007-08-15 14:28:22 +0000724
725 >>> pi.contents
726 c_long(42)
727 >>>
728
Georg Brandl8d8f1972009-06-08 13:27:23 +0000729Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
Georg Brandl116aa622007-08-15 14:28:22 +0000730new, equivalent object each time you retrieve an attribute::
731
732 >>> pi.contents is i
733 False
734 >>> pi.contents is pi.contents
735 False
736 >>>
737
738Assigning another :class:`c_int` instance to the pointer's contents attribute
739would cause the pointer to point to the memory location where this is stored::
740
741 >>> i = c_int(99)
742 >>> pi.contents = i
743 >>> pi.contents
744 c_long(99)
745 >>>
746
Georg Brandl1d837bc2009-12-29 11:24:00 +0000747.. XXX Document dereferencing pointers, and that it is preferred over the
748 .contents attribute.
Thomas Heller2fadaa22008-06-16 19:56:33 +0000749
Georg Brandl116aa622007-08-15 14:28:22 +0000750Pointer instances can also be indexed with integers::
751
752 >>> pi[0]
753 99
754 >>>
755
756Assigning to an integer index changes the pointed to value::
757
Georg Brandl6911e3c2007-09-04 07:15:32 +0000758 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000759 c_long(99)
760 >>> pi[0] = 22
Georg Brandl6911e3c2007-09-04 07:15:32 +0000761 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000762 c_long(22)
763 >>>
764
765It is also possible to use indexes different from 0, but you must know what
766you're doing, just as in C: You can access or change arbitrary memory locations.
767Generally you only use this feature if you receive a pointer from a C function,
768and you *know* that the pointer actually points to an array instead of a single
769item.
770
Georg Brandl8d8f1972009-06-08 13:27:23 +0000771Behind the scenes, the :func:`pointer` function does more than simply create
772pointer instances, it has to create pointer *types* first. This is done with the
773:func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a
774new type::
Georg Brandl116aa622007-08-15 14:28:22 +0000775
776 >>> PI = POINTER(c_int)
777 >>> PI
778 <class 'ctypes.LP_c_long'>
779 >>> PI(42)
780 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530781 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000782 TypeError: expected c_long instead of int
783 >>> PI(c_int(42))
784 <ctypes.LP_c_long object at 0x...>
785 >>>
786
787Calling the pointer type without an argument creates a ``NULL`` pointer.
788``NULL`` pointers have a ``False`` boolean value::
789
790 >>> null_ptr = POINTER(c_int)()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000791 >>> print(bool(null_ptr))
Georg Brandl116aa622007-08-15 14:28:22 +0000792 False
793 >>>
794
Georg Brandl8d8f1972009-06-08 13:27:23 +0000795:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
Thomas Heller2fadaa22008-06-16 19:56:33 +0000796invalid non-\ ``NULL`` pointers would crash Python)::
Georg Brandl116aa622007-08-15 14:28:22 +0000797
798 >>> null_ptr[0]
799 Traceback (most recent call last):
800 ....
801 ValueError: NULL pointer access
802 >>>
803
804 >>> null_ptr[0] = 1234
805 Traceback (most recent call last):
806 ....
807 ValueError: NULL pointer access
808 >>>
809
810
811.. _ctypes-type-conversions:
812
813Type conversions
814^^^^^^^^^^^^^^^^
815
816Usually, ctypes does strict type checking. This means, if you have
817``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
818a member field in a structure definition, only instances of exactly the same
819type are accepted. There are some exceptions to this rule, where ctypes accepts
820other objects. For example, you can pass compatible array instances instead of
821pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
822
823 >>> class Bar(Structure):
824 ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
825 ...
826 >>> bar = Bar()
827 >>> bar.values = (c_int * 3)(1, 2, 3)
828 >>> bar.count = 3
829 >>> for i in range(bar.count):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000830 ... print(bar.values[i])
Georg Brandl116aa622007-08-15 14:28:22 +0000831 ...
832 1
833 2
834 3
835 >>>
836
Eli Benderskyf81de8d2013-03-08 05:31:54 -0800837In addition, if a function argument is explicitly declared to be a pointer type
838(such as ``POINTER(c_int)``) in :attr:`argtypes`, an object of the pointed
839type (``c_int`` in this case) can be passed to the function. ctypes will apply
840the required :func:`byref` conversion in this case automatically.
841
Georg Brandl116aa622007-08-15 14:28:22 +0000842To set a POINTER type field to ``NULL``, you can assign ``None``::
843
844 >>> bar.values = None
845 >>>
846
Thomas Heller2fadaa22008-06-16 19:56:33 +0000847.. XXX list other conversions...
Georg Brandl116aa622007-08-15 14:28:22 +0000848
Georg Brandl8d8f1972009-06-08 13:27:23 +0000849Sometimes you have instances of incompatible types. In C, you can cast one type
850into another type. :mod:`ctypes` provides a :func:`cast` function which can be
Georg Brandl116aa622007-08-15 14:28:22 +0000851used in the same way. The ``Bar`` structure defined above accepts
852``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
853but not instances of other types::
854
855 >>> bar.values = (c_byte * 4)()
856 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530857 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000858 TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
859 >>>
860
Georg Brandl8d8f1972009-06-08 13:27:23 +0000861For these cases, the :func:`cast` function is handy.
Georg Brandl116aa622007-08-15 14:28:22 +0000862
Georg Brandl8d8f1972009-06-08 13:27:23 +0000863The :func:`cast` function can be used to cast a ctypes instance into a pointer
864to a different ctypes data type. :func:`cast` takes two parameters, a ctypes
865object that is or can be converted to a pointer of some kind, and a ctypes
866pointer type. It returns an instance of the second argument, which references
867the same memory block as the first argument::
Georg Brandl116aa622007-08-15 14:28:22 +0000868
869 >>> a = (c_byte * 4)()
870 >>> cast(a, POINTER(c_int))
871 <ctypes.LP_c_long object at ...>
872 >>>
873
Georg Brandl8d8f1972009-06-08 13:27:23 +0000874So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the
Georg Brandl116aa622007-08-15 14:28:22 +0000875structure::
876
877 >>> bar = Bar()
878 >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
Georg Brandl6911e3c2007-09-04 07:15:32 +0000879 >>> print(bar.values[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000880 0
881 >>>
882
883
884.. _ctypes-incomplete-types:
885
886Incomplete Types
887^^^^^^^^^^^^^^^^
888
889*Incomplete Types* are structures, unions or arrays whose members are not yet
890specified. In C, they are specified by forward declarations, which are defined
891later::
892
893 struct cell; /* forward declaration */
894
Sandro Tosi692dba22011-08-02 16:17:14 +0200895 struct cell {
Georg Brandl116aa622007-08-15 14:28:22 +0000896 char *name;
897 struct cell *next;
Sandro Tosi692dba22011-08-02 16:17:14 +0200898 };
Georg Brandl116aa622007-08-15 14:28:22 +0000899
900The straightforward translation into ctypes code would be this, but it does not
901work::
902
903 >>> class cell(Structure):
904 ... _fields_ = [("name", c_char_p),
905 ... ("next", POINTER(cell))]
906 ...
907 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530908 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000909 File "<stdin>", line 2, in cell
910 NameError: name 'cell' is not defined
911 >>>
912
913because the new ``class cell`` is not available in the class statement itself.
Georg Brandl8d8f1972009-06-08 13:27:23 +0000914In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_`
Georg Brandl116aa622007-08-15 14:28:22 +0000915attribute later, after the class statement::
916
917 >>> from ctypes import *
918 >>> class cell(Structure):
919 ... pass
920 ...
921 >>> cell._fields_ = [("name", c_char_p),
922 ... ("next", POINTER(cell))]
923 >>>
924
925Lets try it. We create two instances of ``cell``, and let them point to each
926other, and finally follow the pointer chain a few times::
927
928 >>> c1 = cell()
929 >>> c1.name = "foo"
930 >>> c2 = cell()
931 >>> c2.name = "bar"
932 >>> c1.next = pointer(c2)
933 >>> c2.next = pointer(c1)
934 >>> p = c1
935 >>> for i in range(8):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000936 ... print(p.name, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000937 ... p = p.next[0]
938 ...
939 foo bar foo bar foo bar foo bar
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000940 >>>
Georg Brandl116aa622007-08-15 14:28:22 +0000941
942
943.. _ctypes-callback-functions:
944
945Callback functions
946^^^^^^^^^^^^^^^^^^
947
Martin Panterc04fb562016-02-10 05:44:01 +0000948:mod:`ctypes` allows creating C callable function pointers from Python callables.
Georg Brandl116aa622007-08-15 14:28:22 +0000949These are sometimes called *callback functions*.
950
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200951First, you must create a class for the callback function. The class knows the
Georg Brandl116aa622007-08-15 14:28:22 +0000952calling convention, the return type, and the number and types of arguments this
953function will receive.
954
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200955The :func:`CFUNCTYPE` factory function creates types for callback functions
956using the ``cdecl`` calling convention. On Windows, the :func:`WINFUNCTYPE`
957factory function creates types for callback functions using the ``stdcall``
958calling convention.
Georg Brandl116aa622007-08-15 14:28:22 +0000959
960Both of these factory functions are called with the result type as first
961argument, and the callback functions expected argument types as the remaining
962arguments.
963
Georg Brandl8d8f1972009-06-08 13:27:23 +0000964I will present an example here which uses the standard C library's
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200965:c:func:`qsort` function, that is used to sort items with the help of a callback
Georg Brandl60203b42010-10-06 10:11:56 +0000966function. :c:func:`qsort` will be used to sort an array of integers::
Georg Brandl116aa622007-08-15 14:28:22 +0000967
968 >>> IntArray5 = c_int * 5
969 >>> ia = IntArray5(5, 1, 7, 33, 99)
970 >>> qsort = libc.qsort
971 >>> qsort.restype = None
972 >>>
973
974:func:`qsort` must be called with a pointer to the data to sort, the number of
975items in the data array, the size of one item, and a pointer to the comparison
976function, the callback. The callback will then be called with two pointers to
977items, and it must return a negative integer if the first item is smaller than
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200978the second, a zero if they are equal, and a positive integer otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980So our callback function receives pointers to integers, and must return an
981integer. First we create the ``type`` for the callback function::
982
983 >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
984 >>>
985
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200986To get started, here is a simple callback that shows the values it gets
987passed::
Georg Brandl116aa622007-08-15 14:28:22 +0000988
989 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000990 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000991 ... return 0
992 ...
993 >>> cmp_func = CMPFUNC(py_cmp_func)
994 >>>
995
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200996The result::
Georg Brandl116aa622007-08-15 14:28:22 +0000997
Serhiy Storchakadba90392016-05-10 12:01:23 +0300998 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
Georg Brandl116aa622007-08-15 14:28:22 +0000999 py_cmp_func 5 1
1000 py_cmp_func 33 99
1001 py_cmp_func 7 33
1002 py_cmp_func 5 7
1003 py_cmp_func 1 7
1004 >>>
1005
Eli Bendersky2a1e74a2012-03-16 09:17:43 +02001006Now we can actually compare the two items and return a useful result::
Georg Brandl116aa622007-08-15 14:28:22 +00001007
1008 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001009 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +00001010 ... return a[0] - b[0]
1011 ...
1012 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001013 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1014 py_cmp_func 5 1
1015 py_cmp_func 33 99
1016 py_cmp_func 7 33
1017 py_cmp_func 1 7
1018 py_cmp_func 5 7
1019 >>>
1020
Georg Brandl116aa622007-08-15 14:28:22 +00001021As we can easily check, our array is sorted now::
1022
Georg Brandl6911e3c2007-09-04 07:15:32 +00001023 >>> for i in ia: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +00001024 ...
1025 1 5 7 33 99
1026 >>>
1027
Andrés Delfino379e9d62018-07-13 09:50:20 -03001028The function factories can be used as decorator factories, so we may as well
1029write::
1030
1031 >>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
1032 ... def py_cmp_func(a, b):
1033 ... print("py_cmp_func", a[0], b[0])
1034 ... return a[0] - b[0]
1035 ...
1036 >>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)
1037 py_cmp_func 5 1
1038 py_cmp_func 33 99
1039 py_cmp_func 7 33
1040 py_cmp_func 1 7
1041 py_cmp_func 5 7
1042 >>>
1043
Benjamin Peterson1cfe0092014-01-20 00:10:23 -05001044.. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001045
Benjamin Peterson1cfe0092014-01-20 00:10:23 -05001046 Make sure you keep references to :func:`CFUNCTYPE` objects as long as they
1047 are used from C code. :mod:`ctypes` doesn't, and if you don't, they may be
1048 garbage collected, crashing your program when a callback is made.
Georg Brandl116aa622007-08-15 14:28:22 +00001049
Benjamin Peterson1cfe0092014-01-20 00:10:23 -05001050 Also, note that if the callback function is called in a thread created
1051 outside of Python's control (e.g. by the foreign code that calls the
1052 callback), ctypes creates a new dummy Python thread on every invocation. This
1053 behavior is correct for most purposes, but it means that values stored with
Georg Brandl6b4c8472014-10-30 22:26:26 +01001054 :class:`threading.local` will *not* survive across different callbacks, even when
Benjamin Peterson1cfe0092014-01-20 00:10:23 -05001055 those calls are made from the same C thread.
Georg Brandl116aa622007-08-15 14:28:22 +00001056
1057.. _ctypes-accessing-values-exported-from-dlls:
1058
1059Accessing values exported from dlls
1060^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1061
Thomas Heller2fadaa22008-06-16 19:56:33 +00001062Some shared libraries not only export functions, they also export variables. An
Georg Brandl60203b42010-10-06 10:11:56 +00001063example in the Python library itself is the :c:data:`Py_OptimizeFlag`, an integer
Georg Brandl8d8f1972009-06-08 13:27:23 +00001064set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
Georg Brandl116aa622007-08-15 14:28:22 +00001065startup.
1066
Georg Brandl8d8f1972009-06-08 13:27:23 +00001067:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of
Georg Brandl116aa622007-08-15 14:28:22 +00001068the type. *pythonapi* is a predefined symbol giving access to the Python C
1069api::
1070
1071 >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
Georg Brandl6911e3c2007-09-04 07:15:32 +00001072 >>> print(opt_flag)
Georg Brandl116aa622007-08-15 14:28:22 +00001073 c_long(0)
1074 >>>
1075
1076If the interpreter would have been started with :option:`-O`, the sample would
1077have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1078specified.
1079
1080An extended example which also demonstrates the use of pointers accesses the
Georg Brandl60203b42010-10-06 10:11:56 +00001081:c:data:`PyImport_FrozenModules` pointer exported by Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001082
Georg Brandl8d8f1972009-06-08 13:27:23 +00001083Quoting the docs for that value:
1084
Georg Brandl60203b42010-10-06 10:11:56 +00001085 This pointer is initialized to point to an array of :c:type:`struct _frozen`
Georg Brandl8d8f1972009-06-08 13:27:23 +00001086 records, terminated by one whose members are all *NULL* or zero. When a frozen
1087 module is imported, it is searched in this table. Third-party code could play
1088 tricks with this to provide a dynamically created collection of frozen modules.
Georg Brandl116aa622007-08-15 14:28:22 +00001089
1090So manipulating this pointer could even prove useful. To restrict the example
Georg Brandl8d8f1972009-06-08 13:27:23 +00001091size, we show only how this table can be read with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001092
1093 >>> from ctypes import *
1094 >>>
1095 >>> class struct_frozen(Structure):
1096 ... _fields_ = [("name", c_char_p),
1097 ... ("code", POINTER(c_ubyte)),
1098 ... ("size", c_int)]
1099 ...
1100 >>>
1101
Georg Brandl60203b42010-10-06 10:11:56 +00001102We have defined the :c:type:`struct _frozen` data type, so we can get the pointer
Georg Brandl8d8f1972009-06-08 13:27:23 +00001103to the table::
Georg Brandl116aa622007-08-15 14:28:22 +00001104
1105 >>> FrozenTable = POINTER(struct_frozen)
1106 >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1107 >>>
1108
1109Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1110can iterate over it, but we just have to make sure that our loop terminates,
1111because pointers have no size. Sooner or later it would probably crash with an
1112access violation or whatever, so it's better to break out of the loop when we
1113hit the NULL entry::
1114
1115 >>> for item in table:
Serhiy Storchakadba90392016-05-10 12:01:23 +03001116 ... if item.name is None:
1117 ... break
Martin Panterf47a4002016-05-15 00:13:04 +00001118 ... print(item.name.decode("ascii"), item.size)
Georg Brandl116aa622007-08-15 14:28:22 +00001119 ...
Martin Panterf47a4002016-05-15 00:13:04 +00001120 _frozen_importlib 31764
1121 _frozen_importlib_external 41499
1122 __hello__ 161
1123 __phello__ -161
1124 __phello__.spam 161
Georg Brandl116aa622007-08-15 14:28:22 +00001125 >>>
1126
1127The fact that standard Python has a frozen module and a frozen package
Thomas Woutersed03b412007-08-28 21:37:11 +00001128(indicated by the negative size member) is not well known, it is only used for
Georg Brandl116aa622007-08-15 14:28:22 +00001129testing. Try it out with ``import __hello__`` for example.
1130
1131
1132.. _ctypes-surprises:
1133
1134Surprises
1135^^^^^^^^^
1136
R David Murraya2959ce2012-10-31 10:50:27 -04001137There are some edges in :mod:`ctypes` where you might expect something other
1138than what actually happens.
Georg Brandl116aa622007-08-15 14:28:22 +00001139
1140Consider the following example::
1141
1142 >>> from ctypes import *
1143 >>> class POINT(Structure):
1144 ... _fields_ = ("x", c_int), ("y", c_int)
1145 ...
1146 >>> class RECT(Structure):
1147 ... _fields_ = ("a", POINT), ("b", POINT)
1148 ...
1149 >>> p1 = POINT(1, 2)
1150 >>> p2 = POINT(3, 4)
1151 >>> rc = RECT(p1, p2)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001152 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001153 1 2 3 4
1154 >>> # now swap the two points
1155 >>> rc.a, rc.b = rc.b, rc.a
Georg Brandl6911e3c2007-09-04 07:15:32 +00001156 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001157 3 4 3 4
1158 >>>
1159
1160Hm. We certainly expected the last statement to print ``3 4 1 2``. What
Thomas Woutersed03b412007-08-28 21:37:11 +00001161happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
Georg Brandl116aa622007-08-15 14:28:22 +00001162
1163 >>> temp0, temp1 = rc.b, rc.a
1164 >>> rc.a = temp0
1165 >>> rc.b = temp1
1166 >>>
1167
1168Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1169the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1170contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1171contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1172the expected effect.
1173
Thomas Woutersed03b412007-08-28 21:37:11 +00001174Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1175doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
Georg Brandl116aa622007-08-15 14:28:22 +00001176the root-object's underlying buffer.
1177
1178Another example that may behave different from what one would expect is this::
1179
1180 >>> s = c_char_p()
1181 >>> s.value = "abc def ghi"
1182 >>> s.value
1183 'abc def ghi'
1184 >>> s.value is s.value
1185 False
1186 >>>
1187
1188Why is it printing ``False``? ctypes instances are objects containing a memory
Georg Brandl9afde1c2007-11-01 20:32:30 +00001189block plus some :term:`descriptor`\s accessing the contents of the memory.
1190Storing a Python object in the memory block does not store the object itself,
1191instead the ``contents`` of the object is stored. Accessing the contents again
1192constructs a new Python object each time!
Georg Brandl116aa622007-08-15 14:28:22 +00001193
1194
1195.. _ctypes-variable-sized-data-types:
1196
1197Variable-sized data types
1198^^^^^^^^^^^^^^^^^^^^^^^^^
1199
Georg Brandl8d8f1972009-06-08 13:27:23 +00001200:mod:`ctypes` provides some support for variable-sized arrays and structures.
Georg Brandl116aa622007-08-15 14:28:22 +00001201
Georg Brandl8d8f1972009-06-08 13:27:23 +00001202The :func:`resize` function can be used to resize the memory buffer of an
1203existing ctypes object. The function takes the object as first argument, and
1204the requested size in bytes as the second argument. The memory block cannot be
1205made smaller than the natural memory block specified by the objects type, a
1206:exc:`ValueError` is raised if this is tried::
Georg Brandl116aa622007-08-15 14:28:22 +00001207
1208 >>> short_array = (c_short * 4)()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001209 >>> print(sizeof(short_array))
Georg Brandl116aa622007-08-15 14:28:22 +00001210 8
1211 >>> resize(short_array, 4)
1212 Traceback (most recent call last):
1213 ...
1214 ValueError: minimum size is 8
1215 >>> resize(short_array, 32)
1216 >>> sizeof(short_array)
1217 32
1218 >>> sizeof(type(short_array))
1219 8
1220 >>>
1221
1222This is nice and fine, but how would one access the additional elements
1223contained in this array? Since the type still only knows about 4 elements, we
1224get errors accessing other elements::
1225
1226 >>> short_array[:]
1227 [0, 0, 0, 0]
1228 >>> short_array[7]
1229 Traceback (most recent call last):
1230 ...
1231 IndexError: invalid index
1232 >>>
1233
Georg Brandl8d8f1972009-06-08 13:27:23 +00001234Another way to use variable-sized data types with :mod:`ctypes` is to use the
Georg Brandl116aa622007-08-15 14:28:22 +00001235dynamic nature of Python, and (re-)define the data type after the required size
1236is already known, on a case by case basis.
1237
1238
Georg Brandl116aa622007-08-15 14:28:22 +00001239.. _ctypes-ctypes-reference:
1240
1241ctypes reference
1242----------------
1243
1244
1245.. _ctypes-finding-shared-libraries:
1246
1247Finding shared libraries
1248^^^^^^^^^^^^^^^^^^^^^^^^
1249
1250When programming in a compiled language, shared libraries are accessed when
1251compiling/linking a program, and when the program is run.
1252
Georg Brandl8d8f1972009-06-08 13:27:23 +00001253The purpose of the :func:`find_library` function is to locate a library in a way
Vinay Sajip82df3b32016-08-17 16:20:07 +01001254similar to what the compiler or runtime loader does (on platforms with several
1255versions of a shared library the most recent should be loaded), while the ctypes
1256library loaders act like when a program is run, and call the runtime loader
1257directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001258
Georg Brandl8d8f1972009-06-08 13:27:23 +00001259The :mod:`ctypes.util` module provides a function which can help to determine
1260the library to load.
Georg Brandl116aa622007-08-15 14:28:22 +00001261
1262
1263.. data:: find_library(name)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001264 :module: ctypes.util
Georg Brandl116aa622007-08-15 14:28:22 +00001265 :noindex:
1266
1267 Try to find a library and return a pathname. *name* is the library name without
1268 any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
Martin Panter5c679332016-10-30 04:20:17 +00001269 is the form used for the posix linker option :option:`!-l`). If no library can
Georg Brandl116aa622007-08-15 14:28:22 +00001270 be found, returns ``None``.
1271
Thomas Woutersed03b412007-08-28 21:37:11 +00001272The exact functionality is system dependent.
Georg Brandl116aa622007-08-15 14:28:22 +00001273
Georg Brandl1d837bc2009-12-29 11:24:00 +00001274On Linux, :func:`find_library` tries to run external programs
Vinay Sajip82df3b32016-08-17 16:20:07 +01001275(``/sbin/ldconfig``, ``gcc``, ``objdump`` and ``ld``) to find the library file.
1276It returns the filename of the library file.
1277
1278.. versionchanged:: 3.6
1279 On Linux, the value of the environment variable ``LD_LIBRARY_PATH`` is used
1280 when searching for libraries, if a library cannot be found by any other means.
1281
1282Here are some examples::
Georg Brandl116aa622007-08-15 14:28:22 +00001283
1284 >>> from ctypes.util import find_library
1285 >>> find_library("m")
1286 'libm.so.6'
1287 >>> find_library("c")
1288 'libc.so.6'
1289 >>> find_library("bz2")
1290 'libbz2.so.1.0'
1291 >>>
1292
Georg Brandl8d8f1972009-06-08 13:27:23 +00001293On OS X, :func:`find_library` tries several predefined naming schemes and paths
1294to locate the library, and returns a full pathname if successful::
Georg Brandl116aa622007-08-15 14:28:22 +00001295
1296 >>> from ctypes.util import find_library
1297 >>> find_library("c")
1298 '/usr/lib/libc.dylib'
1299 >>> find_library("m")
1300 '/usr/lib/libm.dylib'
1301 >>> find_library("bz2")
1302 '/usr/lib/libbz2.dylib'
1303 >>> find_library("AGL")
1304 '/System/Library/Frameworks/AGL.framework/AGL'
1305 >>>
1306
Georg Brandl8d8f1972009-06-08 13:27:23 +00001307On Windows, :func:`find_library` searches along the system search path, and
1308returns the full pathname, but since there is no predefined naming scheme a call
1309like ``find_library("c")`` will fail and return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001310
Georg Brandl8d8f1972009-06-08 13:27:23 +00001311If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
Ned Deilyea3cfc52013-05-20 14:29:44 -07001312the shared library name at development time, and hardcode that into the wrapper
Georg Brandl8d8f1972009-06-08 13:27:23 +00001313module instead of using :func:`find_library` to locate the library at runtime.
Georg Brandl116aa622007-08-15 14:28:22 +00001314
1315
1316.. _ctypes-loading-shared-libraries:
1317
1318Loading shared libraries
1319^^^^^^^^^^^^^^^^^^^^^^^^
1320
Zachary Ware46a78bc2016-01-01 12:22:16 -06001321There are several ways to load shared libraries into the Python process. One
Georg Brandl116aa622007-08-15 14:28:22 +00001322way is to instantiate one of the following classes:
1323
1324
Steve Dower2438cdf2019-03-29 16:37:16 -07001325.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001326
1327 Instances of this class represent loaded shared libraries. Functions in these
1328 libraries use the standard C calling convention, and are assumed to return
Georg Brandl60203b42010-10-06 10:11:56 +00001329 :c:type:`int`.
Georg Brandl116aa622007-08-15 14:28:22 +00001330
1331
Steve Dower2438cdf2019-03-29 16:37:16 -07001332.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001333
1334 Windows only: Instances of this class represent loaded shared libraries,
1335 functions in these libraries use the ``stdcall`` calling convention, and are
1336 assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1337 values contain information specifying whether the function call failed or
1338 succeeded, together with additional error code. If the return value signals a
Antoine Pitrou442ee032011-10-12 18:53:23 +02001339 failure, an :class:`OSError` is automatically raised.
1340
1341 .. versionchanged:: 3.3
1342 :exc:`WindowsError` used to be raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001343
1344
Steve Dower2438cdf2019-03-29 16:37:16 -07001345.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001346
1347 Windows only: Instances of this class represent loaded shared libraries,
1348 functions in these libraries use the ``stdcall`` calling convention, and are
Georg Brandl60203b42010-10-06 10:11:56 +00001349 assumed to return :c:type:`int` by default.
Georg Brandl116aa622007-08-15 14:28:22 +00001350
1351 On Windows CE only the standard calling convention is used, for convenience the
1352 :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1353 platform.
1354
Georg Brandl9afde1c2007-11-01 20:32:30 +00001355The Python :term:`global interpreter lock` is released before calling any
1356function exported by these libraries, and reacquired afterwards.
Georg Brandl116aa622007-08-15 14:28:22 +00001357
1358
1359.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1360
1361 Instances of this class behave like :class:`CDLL` instances, except that the
1362 Python GIL is *not* released during the function call, and after the function
1363 execution the Python error flag is checked. If the error flag is set, a Python
1364 exception is raised.
1365
1366 Thus, this is only useful to call Python C api functions directly.
1367
1368All these classes can be instantiated by calling them with at least one
1369argument, the pathname of the shared library. If you have an existing handle to
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001370an already loaded shared library, it can be passed as the ``handle`` named
Georg Brandl1d837bc2009-12-29 11:24:00 +00001371parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary``
Georg Brandl116aa622007-08-15 14:28:22 +00001372function is used to load the library into the process, and to get a handle to
1373it.
1374
1375The *mode* parameter can be used to specify how the library is loaded. For
Martin Panterf18a5da2016-09-27 05:10:40 +00001376details, consult the :manpage:`dlopen(3)` manpage. On Windows, *mode* is
1377ignored. On posix systems, RTLD_NOW is always added, and is not
1378configurable.
Georg Brandl116aa622007-08-15 14:28:22 +00001379
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +03001380The *use_errno* parameter, when set to true, enables a ctypes mechanism that
Martin Panterc04fb562016-02-10 05:44:01 +00001381allows accessing the system :data:`errno` error number in a safe way.
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001382:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1383variable; if you call foreign functions created with ``use_errno=True`` then the
1384:data:`errno` value before the function call is swapped with the ctypes private
1385copy, the same happens immediately after the function call.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001386
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001387The function :func:`ctypes.get_errno` returns the value of the ctypes private
1388copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1389to a new value and returns the former value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001390
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +03001391The *use_last_error* parameter, when set to true, enables the same mechanism for
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001392the Windows error code which is managed by the :func:`GetLastError` and
1393:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1394:func:`ctypes.set_last_error` are used to request and change the ctypes private
1395copy of the windows error code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001396
Steve Dower2438cdf2019-03-29 16:37:16 -07001397The *winmode* parameter is used on Windows to specify how the library is loaded
1398(since *mode* is ignored). It takes any value that is valid for the Win32 API
1399``LoadLibraryEx`` flags parameter. When omitted, the default is to use the flags
1400that result in the most secure DLL load to avoiding issues such as DLL
1401hijacking. Passing the full path to the DLL is the safest way to ensure the
1402correct library and dependencies are loaded.
1403
1404.. versionchanged:: 3.8
1405 Added *winmode* parameter.
1406
1407
Georg Brandl116aa622007-08-15 14:28:22 +00001408.. data:: RTLD_GLOBAL
1409 :noindex:
1410
1411 Flag to use as *mode* parameter. On platforms where this flag is not available,
1412 it is defined as the integer zero.
1413
1414
1415.. data:: RTLD_LOCAL
1416 :noindex:
1417
1418 Flag to use as *mode* parameter. On platforms where this is not available, it
1419 is the same as *RTLD_GLOBAL*.
1420
1421
1422.. data:: DEFAULT_MODE
1423 :noindex:
1424
1425 The default mode which is used to load shared libraries. On OSX 10.3, this is
1426 *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1427
R David Murray9db487b2014-10-04 18:25:07 -04001428Instances of these classes have no public methods. Functions exported by the
1429shared library can be accessed as attributes or by index. Please note that
1430accessing the function through an attribute caches the result and therefore
1431accessing it repeatedly returns the same object each time. On the other hand,
Marco Buttub2a7c2f2017-03-02 12:02:43 +01001432accessing it through an index returns a new object each time::
R David Murray9db487b2014-10-04 18:25:07 -04001433
Marco Buttub2a7c2f2017-03-02 12:02:43 +01001434 >>> from ctypes import CDLL
1435 >>> libc = CDLL("libc.so.6") # On Linux
R David Murray9db487b2014-10-04 18:25:07 -04001436 >>> libc.time == libc.time
1437 True
1438 >>> libc['time'] == libc['time']
1439 False
Georg Brandl116aa622007-08-15 14:28:22 +00001440
1441The following public attributes are available, their name starts with an
1442underscore to not clash with exported function names:
1443
1444
1445.. attribute:: PyDLL._handle
1446
1447 The system handle used to access the library.
1448
1449
1450.. attribute:: PyDLL._name
1451
Thomas Woutersed03b412007-08-28 21:37:11 +00001452 The name of the library passed in the constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001453
1454Shared libraries can also be loaded by using one of the prefabricated objects,
1455which are instances of the :class:`LibraryLoader` class, either by calling the
1456:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1457loader instance.
1458
1459
1460.. class:: LibraryLoader(dlltype)
1461
Georg Brandl1d837bc2009-12-29 11:24:00 +00001462 Class which loads shared libraries. *dlltype* should be one of the
Georg Brandl116aa622007-08-15 14:28:22 +00001463 :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1464
Martin Panterc04fb562016-02-10 05:44:01 +00001465 :meth:`__getattr__` has special behavior: It allows loading a shared library by
Georg Brandl116aa622007-08-15 14:28:22 +00001466 accessing it as attribute of a library loader instance. The result is cached,
1467 so repeated attribute accesses return the same library each time.
1468
Benjamin Petersone41251e2008-04-25 01:59:09 +00001469 .. method:: LoadLibrary(name)
Georg Brandl116aa622007-08-15 14:28:22 +00001470
Benjamin Petersone41251e2008-04-25 01:59:09 +00001471 Load a shared library into the process and return it. This method always
1472 returns a new instance of the library.
Georg Brandl116aa622007-08-15 14:28:22 +00001473
Georg Brandl116aa622007-08-15 14:28:22 +00001474
Georg Brandl8d8f1972009-06-08 13:27:23 +00001475These prefabricated library loaders are available:
Georg Brandl116aa622007-08-15 14:28:22 +00001476
1477.. data:: cdll
1478 :noindex:
1479
1480 Creates :class:`CDLL` instances.
1481
1482
1483.. data:: windll
1484 :noindex:
1485
1486 Windows only: Creates :class:`WinDLL` instances.
1487
1488
1489.. data:: oledll
1490 :noindex:
1491
1492 Windows only: Creates :class:`OleDLL` instances.
1493
1494
1495.. data:: pydll
1496 :noindex:
1497
1498 Creates :class:`PyDLL` instances.
1499
Georg Brandl8d8f1972009-06-08 13:27:23 +00001500
Georg Brandl116aa622007-08-15 14:28:22 +00001501For accessing the C Python api directly, a ready-to-use Python shared library
1502object is available:
1503
Georg Brandl116aa622007-08-15 14:28:22 +00001504.. data:: pythonapi
1505 :noindex:
1506
Georg Brandl1d837bc2009-12-29 11:24:00 +00001507 An instance of :class:`PyDLL` that exposes Python C API functions as
1508 attributes. Note that all these functions are assumed to return C
Georg Brandl60203b42010-10-06 10:11:56 +00001509 :c:type:`int`, which is of course not always the truth, so you have to assign
Georg Brandl1d837bc2009-12-29 11:24:00 +00001510 the correct :attr:`restype` attribute to use these functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001511
Steve Dowerb82e17e2019-05-23 08:45:22 -07001512.. audit-event:: ctypes.dlopen name
1513
1514 Loading a library through any of these objects raises an
1515 :ref:`auditing event <auditing>` ``ctypes.dlopen`` with string argument
1516 ``name``, the name used to load the library.
1517
1518.. audit-event:: ctypes.dlsym "library name"
1519
1520 Accessing a function on a loaded library raises an auditing event
1521 ``ctypes.dlsym`` with arguments ``library`` (the library object) and ``name``
1522 (the symbol's name as a string or integer).
Georg Brandl116aa622007-08-15 14:28:22 +00001523
1524.. _ctypes-foreign-functions:
1525
1526Foreign functions
1527^^^^^^^^^^^^^^^^^
1528
1529As explained in the previous section, foreign functions can be accessed as
1530attributes of loaded shared libraries. The function objects created in this way
1531by default accept any number of arguments, accept any ctypes data instances as
1532arguments, and return the default result type specified by the library loader.
1533They are instances of a private class:
1534
1535
1536.. class:: _FuncPtr
1537
1538 Base class for C callable foreign functions.
1539
Benjamin Petersone41251e2008-04-25 01:59:09 +00001540 Instances of foreign functions are also C compatible data types; they
1541 represent C function pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001542
Benjamin Petersone41251e2008-04-25 01:59:09 +00001543 This behavior can be customized by assigning to special attributes of the
1544 foreign function object.
Georg Brandl116aa622007-08-15 14:28:22 +00001545
Benjamin Petersone41251e2008-04-25 01:59:09 +00001546 .. attribute:: restype
Georg Brandl116aa622007-08-15 14:28:22 +00001547
Benjamin Petersone41251e2008-04-25 01:59:09 +00001548 Assign a ctypes type to specify the result type of the foreign function.
Georg Brandl60203b42010-10-06 10:11:56 +00001549 Use ``None`` for :c:type:`void`, a function not returning anything.
Georg Brandl116aa622007-08-15 14:28:22 +00001550
Benjamin Petersone41251e2008-04-25 01:59:09 +00001551 It is possible to assign a callable Python object that is not a ctypes
Georg Brandl60203b42010-10-06 10:11:56 +00001552 type, in this case the function is assumed to return a C :c:type:`int`, and
Martin Panterc04fb562016-02-10 05:44:01 +00001553 the callable will be called with this integer, allowing further
Benjamin Petersone41251e2008-04-25 01:59:09 +00001554 processing or error checking. Using this is deprecated, for more flexible
1555 post processing or error checking use a ctypes data type as
1556 :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001557
Benjamin Petersone41251e2008-04-25 01:59:09 +00001558 .. attribute:: argtypes
Georg Brandl116aa622007-08-15 14:28:22 +00001559
Benjamin Petersone41251e2008-04-25 01:59:09 +00001560 Assign a tuple of ctypes types to specify the argument types that the
1561 function accepts. Functions using the ``stdcall`` calling convention can
1562 only be called with the same number of arguments as the length of this
1563 tuple; functions using the C calling convention accept additional,
1564 unspecified arguments as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001565
Benjamin Petersone41251e2008-04-25 01:59:09 +00001566 When a foreign function is called, each actual argument is passed to the
1567 :meth:`from_param` class method of the items in the :attr:`argtypes`
Martin Panterc04fb562016-02-10 05:44:01 +00001568 tuple, this method allows adapting the actual argument to an object that
Benjamin Petersone41251e2008-04-25 01:59:09 +00001569 the foreign function accepts. For example, a :class:`c_char_p` item in
Georg Brandl8d8f1972009-06-08 13:27:23 +00001570 the :attr:`argtypes` tuple will convert a string passed as argument into
1571 a bytes object using ctypes conversion rules.
Georg Brandl116aa622007-08-15 14:28:22 +00001572
Benjamin Petersone41251e2008-04-25 01:59:09 +00001573 New: It is now possible to put items in argtypes which are not ctypes
1574 types, but each item must have a :meth:`from_param` method which returns a
1575 value usable as argument (integer, string, ctypes instance). This allows
Martin Panterc04fb562016-02-10 05:44:01 +00001576 defining adapters that can adapt custom objects as function parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001577
Benjamin Petersone41251e2008-04-25 01:59:09 +00001578 .. attribute:: errcheck
Georg Brandl116aa622007-08-15 14:28:22 +00001579
Benjamin Petersone41251e2008-04-25 01:59:09 +00001580 Assign a Python function or another callable to this attribute. The
1581 callable will be called with three or more arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001582
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001583 .. function:: callable(result, func, arguments)
1584 :noindex:
Georg Brandl8d8f1972009-06-08 13:27:23 +00001585 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001586
Georg Brandl1d837bc2009-12-29 11:24:00 +00001587 *result* is what the foreign function returns, as specified by the
1588 :attr:`restype` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001589
Martin Panterc04fb562016-02-10 05:44:01 +00001590 *func* is the foreign function object itself, this allows reusing the
Georg Brandl1d837bc2009-12-29 11:24:00 +00001591 same callable object to check or post process the results of several
1592 functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001593
Georg Brandl1d837bc2009-12-29 11:24:00 +00001594 *arguments* is a tuple containing the parameters originally passed to
Martin Panterc04fb562016-02-10 05:44:01 +00001595 the function call, this allows specializing the behavior on the
Georg Brandl1d837bc2009-12-29 11:24:00 +00001596 arguments used.
Georg Brandl116aa622007-08-15 14:28:22 +00001597
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001598 The object that this function returns will be returned from the
1599 foreign function call, but it can also check the result value
1600 and raise an exception if the foreign function call failed.
Georg Brandl116aa622007-08-15 14:28:22 +00001601
1602
Georg Brandl8d8f1972009-06-08 13:27:23 +00001603.. exception:: ArgumentError
Georg Brandl116aa622007-08-15 14:28:22 +00001604
1605 This exception is raised when a foreign function call cannot convert one of the
1606 passed arguments.
1607
1608
1609.. _ctypes-function-prototypes:
1610
1611Function prototypes
1612^^^^^^^^^^^^^^^^^^^
1613
1614Foreign functions can also be created by instantiating function prototypes.
1615Function prototypes are similar to function prototypes in C; they describe a
1616function (return type, argument types, calling convention) without defining an
1617implementation. The factory functions must be called with the desired result
Andrés Delfino379e9d62018-07-13 09:50:20 -03001618type and the argument types of the function, and can be used as decorator
1619factories, and as such, be applied to functions through the ``@wrapper`` syntax.
1620See :ref:`ctypes-callback-functions` for examples.
Georg Brandl116aa622007-08-15 14:28:22 +00001621
1622
Thomas Hellerb795f5282008-06-10 15:26:58 +00001623.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001624
1625 The returned function prototype creates functions that use the standard C
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001626 calling convention. The function will release the GIL during the call. If
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +03001627 *use_errno* is set to true, the ctypes private copy of the system
Georg Brandla6053b42009-09-01 08:11:14 +00001628 :data:`errno` variable is exchanged with the real :data:`errno` value before
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001629 and after the call; *use_last_error* does the same for the Windows error
1630 code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001631
Georg Brandl116aa622007-08-15 14:28:22 +00001632
Thomas Hellerb795f5282008-06-10 15:26:58 +00001633.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001634
1635 Windows only: The returned function prototype creates functions that use the
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001636 ``stdcall`` calling convention, except on Windows CE where
1637 :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
1638 release the GIL during the call. *use_errno* and *use_last_error* have the
1639 same meaning as above.
Georg Brandl116aa622007-08-15 14:28:22 +00001640
1641
1642.. function:: PYFUNCTYPE(restype, *argtypes)
1643
1644 The returned function prototype creates functions that use the Python calling
1645 convention. The function will *not* release the GIL during the call.
1646
Thomas Heller2fadaa22008-06-16 19:56:33 +00001647Function prototypes created by these factory functions can be instantiated in
1648different ways, depending on the type and number of the parameters in the call:
Georg Brandl116aa622007-08-15 14:28:22 +00001649
1650
Thomas Heller2fadaa22008-06-16 19:56:33 +00001651 .. function:: prototype(address)
1652 :noindex:
1653 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001654
Thomas Heller2fadaa22008-06-16 19:56:33 +00001655 Returns a foreign function at the specified address which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00001656
1657
Thomas Heller2fadaa22008-06-16 19:56:33 +00001658 .. function:: prototype(callable)
1659 :noindex:
1660 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001661
Georg Brandl8d8f1972009-06-08 13:27:23 +00001662 Create a C callable function (a callback function) from a Python *callable*.
Georg Brandl116aa622007-08-15 14:28:22 +00001663
1664
Thomas Heller2fadaa22008-06-16 19:56:33 +00001665 .. function:: prototype(func_spec[, paramflags])
1666 :noindex:
1667 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001668
Georg Brandl1d837bc2009-12-29 11:24:00 +00001669 Returns a foreign function exported by a shared library. *func_spec* must
1670 be a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of
1671 the exported function as string, or the ordinal of the exported function
1672 as small integer. The second item is the shared library instance.
Georg Brandl116aa622007-08-15 14:28:22 +00001673
1674
Thomas Heller2fadaa22008-06-16 19:56:33 +00001675 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1676 :noindex:
1677 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001678
Georg Brandl8d8f1972009-06-08 13:27:23 +00001679 Returns a foreign function that will call a COM method. *vtbl_index* is
1680 the index into the virtual function table, a small non-negative
1681 integer. *name* is name of the COM method. *iid* is an optional pointer to
1682 the interface identifier which is used in extended error reporting.
Georg Brandl116aa622007-08-15 14:28:22 +00001683
Georg Brandl8d8f1972009-06-08 13:27:23 +00001684 COM methods use a special calling convention: They require a pointer to
1685 the COM interface as first argument, in addition to those parameters that
1686 are specified in the :attr:`argtypes` tuple.
Georg Brandl116aa622007-08-15 14:28:22 +00001687
Thomas Heller2fadaa22008-06-16 19:56:33 +00001688 The optional *paramflags* parameter creates foreign function wrappers with much
1689 more functionality than the features described above.
Georg Brandl116aa622007-08-15 14:28:22 +00001690
Thomas Heller2fadaa22008-06-16 19:56:33 +00001691 *paramflags* must be a tuple of the same length as :attr:`argtypes`.
Georg Brandl116aa622007-08-15 14:28:22 +00001692
Thomas Heller2fadaa22008-06-16 19:56:33 +00001693 Each item in this tuple contains further information about a parameter, it must
1694 be a tuple containing one, two, or three items.
Georg Brandl116aa622007-08-15 14:28:22 +00001695
Thomas Heller2fadaa22008-06-16 19:56:33 +00001696 The first item is an integer containing a combination of direction
1697 flags for the parameter:
Georg Brandl116aa622007-08-15 14:28:22 +00001698
Thomas Heller2fadaa22008-06-16 19:56:33 +00001699 1
1700 Specifies an input parameter to the function.
Georg Brandl116aa622007-08-15 14:28:22 +00001701
Thomas Heller2fadaa22008-06-16 19:56:33 +00001702 2
1703 Output parameter. The foreign function fills in a value.
Georg Brandl116aa622007-08-15 14:28:22 +00001704
Thomas Heller2fadaa22008-06-16 19:56:33 +00001705 4
1706 Input parameter which defaults to the integer zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001707
Thomas Heller2fadaa22008-06-16 19:56:33 +00001708 The optional second item is the parameter name as string. If this is specified,
1709 the foreign function can be called with named parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001710
Thomas Heller2fadaa22008-06-16 19:56:33 +00001711 The optional third item is the default value for this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001712
Berker Peksagde55c612016-09-28 17:07:01 +03001713This example demonstrates how to wrap the Windows ``MessageBoxW`` function so
Georg Brandl116aa622007-08-15 14:28:22 +00001714that it supports default parameters and named arguments. The C declaration from
1715the windows header file is this::
1716
1717 WINUSERAPI int WINAPI
Berker Peksagde55c612016-09-28 17:07:01 +03001718 MessageBoxW(
Serhiy Storchakaa4d170d2013-12-23 18:20:51 +02001719 HWND hWnd,
Berker Peksagde55c612016-09-28 17:07:01 +03001720 LPCWSTR lpText,
1721 LPCWSTR lpCaption,
Georg Brandl116aa622007-08-15 14:28:22 +00001722 UINT uType);
1723
Georg Brandl8d8f1972009-06-08 13:27:23 +00001724Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001725
Thomas Heller2fadaa22008-06-16 19:56:33 +00001726 >>> from ctypes import c_int, WINFUNCTYPE, windll
Berker Peksagde55c612016-09-28 17:07:01 +03001727 >>> from ctypes.wintypes import HWND, LPCWSTR, UINT
1728 >>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)
1729 >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0)
1730 >>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags)
Georg Brandl116aa622007-08-15 14:28:22 +00001731
Berker Peksagde55c612016-09-28 17:07:01 +03001732The ``MessageBox`` foreign function can now be called in these ways::
Georg Brandl116aa622007-08-15 14:28:22 +00001733
1734 >>> MessageBox()
1735 >>> MessageBox(text="Spam, spam, spam")
1736 >>> MessageBox(flags=2, text="foo bar")
Georg Brandl116aa622007-08-15 14:28:22 +00001737
1738A second example demonstrates output parameters. The win32 ``GetWindowRect``
1739function retrieves the dimensions of a specified window by copying them into
1740``RECT`` structure that the caller has to supply. Here is the C declaration::
1741
1742 WINUSERAPI BOOL WINAPI
1743 GetWindowRect(
1744 HWND hWnd,
1745 LPRECT lpRect);
1746
Georg Brandl8d8f1972009-06-08 13:27:23 +00001747Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001748
Thomas Heller2fadaa22008-06-16 19:56:33 +00001749 >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1750 >>> from ctypes.wintypes import BOOL, HWND, RECT
1751 >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1752 >>> paramflags = (1, "hwnd"), (2, "lprect")
1753 >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1754 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001755
1756Functions with output parameters will automatically return the output parameter
1757value if there is a single one, or a tuple containing the output parameter
1758values when there are more than one, so the GetWindowRect function now returns a
1759RECT instance, when called.
1760
1761Output parameters can be combined with the :attr:`errcheck` protocol to do
1762further output processing and error checking. The win32 ``GetWindowRect`` api
1763function returns a ``BOOL`` to signal success or failure, so this function could
1764do the error checking, and raises an exception when the api call failed::
1765
1766 >>> def errcheck(result, func, args):
1767 ... if not result:
1768 ... raise WinError()
1769 ... return args
Thomas Heller2fadaa22008-06-16 19:56:33 +00001770 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001771 >>> GetWindowRect.errcheck = errcheck
1772 >>>
1773
1774If the :attr:`errcheck` function returns the argument tuple it receives
Georg Brandl8d8f1972009-06-08 13:27:23 +00001775unchanged, :mod:`ctypes` continues the normal processing it does on the output
Georg Brandl116aa622007-08-15 14:28:22 +00001776parameters. If you want to return a tuple of window coordinates instead of a
1777``RECT`` instance, you can retrieve the fields in the function and return them
1778instead, the normal processing will no longer take place::
1779
1780 >>> def errcheck(result, func, args):
1781 ... if not result:
1782 ... raise WinError()
1783 ... rc = args[1]
1784 ... return rc.left, rc.top, rc.bottom, rc.right
Thomas Heller2fadaa22008-06-16 19:56:33 +00001785 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001786 >>> GetWindowRect.errcheck = errcheck
1787 >>>
1788
1789
1790.. _ctypes-utility-functions:
1791
1792Utility functions
1793^^^^^^^^^^^^^^^^^
1794
Georg Brandl116aa622007-08-15 14:28:22 +00001795.. function:: addressof(obj)
1796
Georg Brandl8d8f1972009-06-08 13:27:23 +00001797 Returns the address of the memory buffer as integer. *obj* must be an
Georg Brandl116aa622007-08-15 14:28:22 +00001798 instance of a ctypes type.
1799
1800
1801.. function:: alignment(obj_or_type)
1802
Georg Brandl8d8f1972009-06-08 13:27:23 +00001803 Returns the alignment requirements of a ctypes type. *obj_or_type* must be a
Georg Brandl116aa622007-08-15 14:28:22 +00001804 ctypes type or instance.
1805
1806
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001807.. function:: byref(obj[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +00001808
Georg Brandl1d837bc2009-12-29 11:24:00 +00001809 Returns a light-weight pointer to *obj*, which must be an instance of a
1810 ctypes type. *offset* defaults to zero, and must be an integer that will be
1811 added to the internal pointer value.
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001812
1813 ``byref(obj, offset)`` corresponds to this C code::
1814
1815 (((char *)&obj) + offset)
1816
Georg Brandl1d837bc2009-12-29 11:24:00 +00001817 The returned object can only be used as a foreign function call parameter.
1818 It behaves similar to ``pointer(obj)``, but the construction is a lot faster.
Georg Brandl116aa622007-08-15 14:28:22 +00001819
1820
1821.. function:: cast(obj, type)
1822
Georg Brandl8d8f1972009-06-08 13:27:23 +00001823 This function is similar to the cast operator in C. It returns a new instance
Georg Brandl1d837bc2009-12-29 11:24:00 +00001824 of *type* which points to the same memory block as *obj*. *type* must be a
Georg Brandl8d8f1972009-06-08 13:27:23 +00001825 pointer type, and *obj* must be an object that can be interpreted as a
Georg Brandl116aa622007-08-15 14:28:22 +00001826 pointer.
1827
1828
Georg Brandl8d8f1972009-06-08 13:27:23 +00001829.. function:: create_string_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001830
1831 This function creates a mutable character buffer. The returned object is a
1832 ctypes array of :class:`c_char`.
1833
Georg Brandl8d8f1972009-06-08 13:27:23 +00001834 *init_or_size* must be an integer which specifies the size of the array, or a
1835 bytes object which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001836
Georg Brandl8d8f1972009-06-08 13:27:23 +00001837 If a bytes object is specified as first argument, the buffer is made one item
1838 larger than its length so that the last element in the array is a NUL
Georg Brandl116aa622007-08-15 14:28:22 +00001839 termination character. An integer can be passed as second argument which allows
Martin Panterc04fb562016-02-10 05:44:01 +00001840 specifying the size of the array if the length of the bytes should not be used.
Georg Brandl116aa622007-08-15 14:28:22 +00001841
Georg Brandl116aa622007-08-15 14:28:22 +00001842
1843
Georg Brandl8d8f1972009-06-08 13:27:23 +00001844.. function:: create_unicode_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001845
1846 This function creates a mutable unicode character buffer. The returned object is
1847 a ctypes array of :class:`c_wchar`.
1848
Georg Brandl8d8f1972009-06-08 13:27:23 +00001849 *init_or_size* must be an integer which specifies the size of the array, or a
1850 string which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001851
Georg Brandl8d8f1972009-06-08 13:27:23 +00001852 If a string is specified as first argument, the buffer is made one item
Georg Brandl116aa622007-08-15 14:28:22 +00001853 larger than the length of the string so that the last element in the array is a
1854 NUL termination character. An integer can be passed as second argument which
Martin Panterc04fb562016-02-10 05:44:01 +00001855 allows specifying the size of the array if the length of the string should not
Georg Brandl116aa622007-08-15 14:28:22 +00001856 be used.
1857
Georg Brandl116aa622007-08-15 14:28:22 +00001858
1859
1860.. function:: DllCanUnloadNow()
1861
Martin Panterc04fb562016-02-10 05:44:01 +00001862 Windows only: This function is a hook which allows implementing in-process
Georg Brandl1d837bc2009-12-29 11:24:00 +00001863 COM servers with ctypes. It is called from the DllCanUnloadNow function that
1864 the _ctypes extension dll exports.
Georg Brandl116aa622007-08-15 14:28:22 +00001865
1866
1867.. function:: DllGetClassObject()
1868
Martin Panterc04fb562016-02-10 05:44:01 +00001869 Windows only: This function is a hook which allows implementing in-process
Georg Brandl1d837bc2009-12-29 11:24:00 +00001870 COM servers with ctypes. It is called from the DllGetClassObject function
1871 that the ``_ctypes`` extension dll exports.
1872
Georg Brandl116aa622007-08-15 14:28:22 +00001873
Thomas Heller2fadaa22008-06-16 19:56:33 +00001874.. function:: find_library(name)
1875 :module: ctypes.util
1876
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001877 Try to find a library and return a pathname. *name* is the library name
Benjamin Peterson28d88b42009-01-09 03:03:23 +00001878 without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
Martin Panter5c679332016-10-30 04:20:17 +00001879 number (this is the form used for the posix linker option :option:`!-l`). If
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001880 no library can be found, returns ``None``.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001881
1882 The exact functionality is system dependent.
1883
Thomas Heller2fadaa22008-06-16 19:56:33 +00001884
1885.. function:: find_msvcrt()
1886 :module: ctypes.util
1887
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001888 Windows only: return the filename of the VC runtime library used by Python,
Georg Brandl1d837bc2009-12-29 11:24:00 +00001889 and by the extension modules. If the name of the library cannot be
1890 determined, ``None`` is returned.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001891
Georg Brandl1d837bc2009-12-29 11:24:00 +00001892 If you need to free memory, for example, allocated by an extension module
1893 with a call to the ``free(void *)``, it is important that you use the
1894 function in the same library that allocated the memory.
1895
Thomas Heller2fadaa22008-06-16 19:56:33 +00001896
Georg Brandl116aa622007-08-15 14:28:22 +00001897.. function:: FormatError([code])
1898
Georg Brandl1d837bc2009-12-29 11:24:00 +00001899 Windows only: Returns a textual description of the error code *code*. If no
1900 error code is specified, the last error code is used by calling the Windows
1901 api function GetLastError.
Georg Brandl116aa622007-08-15 14:28:22 +00001902
1903
1904.. function:: GetLastError()
1905
1906 Windows only: Returns the last error code set by Windows in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001907 This function calls the Windows `GetLastError()` function directly,
1908 it does not return the ctypes-private copy of the error code.
Georg Brandl116aa622007-08-15 14:28:22 +00001909
Thomas Hellerb795f5282008-06-10 15:26:58 +00001910.. function:: get_errno()
1911
1912 Returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001913 :data:`errno` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001914
Thomas Hellerb795f5282008-06-10 15:26:58 +00001915.. function:: get_last_error()
1916
1917 Windows only: returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001918 :data:`LastError` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001919
Georg Brandl116aa622007-08-15 14:28:22 +00001920.. function:: memmove(dst, src, count)
1921
1922 Same as the standard C memmove library function: copies *count* bytes from
Georg Brandl1d837bc2009-12-29 11:24:00 +00001923 *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can
1924 be converted to pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001925
1926
1927.. function:: memset(dst, c, count)
1928
1929 Same as the standard C memset library function: fills the memory block at
1930 address *dst* with *count* bytes of value *c*. *dst* must be an integer
1931 specifying an address, or a ctypes instance.
1932
1933
1934.. function:: POINTER(type)
1935
1936 This factory function creates and returns a new ctypes pointer type. Pointer
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001937 types are cached and reused internally, so calling this function repeatedly is
Georg Brandl1d837bc2009-12-29 11:24:00 +00001938 cheap. *type* must be a ctypes type.
Georg Brandl116aa622007-08-15 14:28:22 +00001939
1940
1941.. function:: pointer(obj)
1942
Georg Brandl8d8f1972009-06-08 13:27:23 +00001943 This function creates a new pointer instance, pointing to *obj*. The returned
Georg Brandl1d837bc2009-12-29 11:24:00 +00001944 object is of the type ``POINTER(type(obj))``.
Georg Brandl116aa622007-08-15 14:28:22 +00001945
1946 Note: If you just want to pass a pointer to an object to a foreign function
1947 call, you should use ``byref(obj)`` which is much faster.
1948
1949
1950.. function:: resize(obj, size)
1951
Georg Brandl1d837bc2009-12-29 11:24:00 +00001952 This function resizes the internal memory buffer of *obj*, which must be an
1953 instance of a ctypes type. It is not possible to make the buffer smaller
1954 than the native size of the objects type, as given by ``sizeof(type(obj))``,
1955 but it is possible to enlarge the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00001956
1957
Thomas Hellerb795f5282008-06-10 15:26:58 +00001958.. function:: set_errno(value)
1959
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001960 Set the current value of the ctypes-private copy of the system :data:`errno`
1961 variable in the calling thread to *value* and return the previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001962
Georg Brandl8d8f1972009-06-08 13:27:23 +00001963
Georg Brandl1d837bc2009-12-29 11:24:00 +00001964
Thomas Hellerb795f5282008-06-10 15:26:58 +00001965.. function:: set_last_error(value)
1966
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001967 Windows only: set the current value of the ctypes-private copy of the system
1968 :data:`LastError` variable in the calling thread to *value* and return the
1969 previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001970
Georg Brandl8d8f1972009-06-08 13:27:23 +00001971
Georg Brandl1d837bc2009-12-29 11:24:00 +00001972
Georg Brandl116aa622007-08-15 14:28:22 +00001973.. function:: sizeof(obj_or_type)
1974
Ezio Melottie4597502013-10-21 04:41:40 +03001975 Returns the size in bytes of a ctypes type or instance memory buffer.
1976 Does the same as the C ``sizeof`` operator.
Georg Brandl116aa622007-08-15 14:28:22 +00001977
1978
Georg Brandl8d8f1972009-06-08 13:27:23 +00001979.. function:: string_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001980
Ezio Melottie130a522011-10-19 10:58:56 +03001981 This function returns the C string starting at memory address *address* as a bytes
Georg Brandl8d8f1972009-06-08 13:27:23 +00001982 object. If size is specified, it is used as size, otherwise the string is assumed
1983 to be zero-terminated.
Georg Brandl116aa622007-08-15 14:28:22 +00001984
1985
1986.. function:: WinError(code=None, descr=None)
1987
1988 Windows only: this function is probably the worst-named thing in ctypes. It
Antoine Pitrou442ee032011-10-12 18:53:23 +02001989 creates an instance of OSError. If *code* is not specified,
Georg Brandl1d837bc2009-12-29 11:24:00 +00001990 ``GetLastError`` is called to determine the error code. If *descr* is not
Thomas Woutersed03b412007-08-28 21:37:11 +00001991 specified, :func:`FormatError` is called to get a textual description of the
Georg Brandl116aa622007-08-15 14:28:22 +00001992 error.
1993
Antoine Pitrou442ee032011-10-12 18:53:23 +02001994 .. versionchanged:: 3.3
1995 An instance of :exc:`WindowsError` used to be created.
1996
Georg Brandl116aa622007-08-15 14:28:22 +00001997
Georg Brandl8d8f1972009-06-08 13:27:23 +00001998.. function:: wstring_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001999
2000 This function returns the wide character string starting at memory address
Georg Brandl1d837bc2009-12-29 11:24:00 +00002001 *address* as a string. If *size* is specified, it is used as the number of
2002 characters of the string, otherwise the string is assumed to be
Georg Brandl116aa622007-08-15 14:28:22 +00002003 zero-terminated.
2004
2005
2006.. _ctypes-data-types:
2007
2008Data types
2009^^^^^^^^^^
2010
2011
2012.. class:: _CData
2013
Georg Brandl1d837bc2009-12-29 11:24:00 +00002014 This non-public class is the common base class of all ctypes data types.
2015 Among other things, all ctypes type instances contain a memory block that
2016 hold C compatible data; the address of the memory block is returned by the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002017 :func:`addressof` helper function. Another instance variable is exposed as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002018 :attr:`_objects`; this contains other Python objects that need to be kept
2019 alive in case the memory block contains pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00002020
Benjamin Petersone41251e2008-04-25 01:59:09 +00002021 Common methods of ctypes data types, these are all class methods (to be
2022 exact, they are methods of the :term:`metaclass`):
Georg Brandl116aa622007-08-15 14:28:22 +00002023
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002024 .. method:: _CData.from_buffer(source[, offset])
2025
Georg Brandl1d837bc2009-12-29 11:24:00 +00002026 This method returns a ctypes instance that shares the buffer of the
2027 *source* object. The *source* object must support the writeable buffer
2028 interface. The optional *offset* parameter specifies an offset into the
2029 source buffer in bytes; the default is zero. If the source buffer is not
2030 large enough a :exc:`ValueError` is raised.
2031
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002032
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002033 .. method:: _CData.from_buffer_copy(source[, offset])
2034
Georg Brandl1d837bc2009-12-29 11:24:00 +00002035 This method creates a ctypes instance, copying the buffer from the
2036 *source* object buffer which must be readable. The optional *offset*
2037 parameter specifies an offset into the source buffer in bytes; the default
2038 is zero. If the source buffer is not large enough a :exc:`ValueError` is
2039 raised.
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002040
Benjamin Petersone41251e2008-04-25 01:59:09 +00002041 .. method:: from_address(address)
Georg Brandl116aa622007-08-15 14:28:22 +00002042
Benjamin Petersone41251e2008-04-25 01:59:09 +00002043 This method returns a ctypes type instance using the memory specified by
Georg Brandl1d837bc2009-12-29 11:24:00 +00002044 *address* which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00002045
Steve Dowerb82e17e2019-05-23 08:45:22 -07002046 .. audit-event:: ctypes.cdata address
2047
2048 This method, and others that indirectly call this method, raises an
Steve Dower60419a72019-06-24 08:42:54 -07002049 :ref:`auditing event <auditing>` ``ctypes.cdata`` with argument
Steve Dowerb82e17e2019-05-23 08:45:22 -07002050 ``address``.
2051
Benjamin Petersone41251e2008-04-25 01:59:09 +00002052 .. method:: from_param(obj)
Georg Brandl116aa622007-08-15 14:28:22 +00002053
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002054 This method adapts *obj* to a ctypes type. It is called with the actual
2055 object used in a foreign function call when the type is present in the
2056 foreign function's :attr:`argtypes` tuple; it must return an object that
2057 can be used as a function call parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00002058
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002059 All ctypes data types have a default implementation of this classmethod
Georg Brandl8d8f1972009-06-08 13:27:23 +00002060 that normally returns *obj* if that is an instance of the type. Some
Benjamin Petersone41251e2008-04-25 01:59:09 +00002061 types accept other objects as well.
Georg Brandl116aa622007-08-15 14:28:22 +00002062
Benjamin Petersone41251e2008-04-25 01:59:09 +00002063 .. method:: in_dll(library, name)
Georg Brandl116aa622007-08-15 14:28:22 +00002064
Benjamin Petersone41251e2008-04-25 01:59:09 +00002065 This method returns a ctypes type instance exported by a shared
2066 library. *name* is the name of the symbol that exports the data, *library*
2067 is the loaded shared library.
Georg Brandl116aa622007-08-15 14:28:22 +00002068
Benjamin Petersone41251e2008-04-25 01:59:09 +00002069 Common instance variables of ctypes data types:
Georg Brandl116aa622007-08-15 14:28:22 +00002070
Benjamin Petersone41251e2008-04-25 01:59:09 +00002071 .. attribute:: _b_base_
Georg Brandl116aa622007-08-15 14:28:22 +00002072
Benjamin Petersone41251e2008-04-25 01:59:09 +00002073 Sometimes ctypes data instances do not own the memory block they contain,
2074 instead they share part of the memory block of a base object. The
2075 :attr:`_b_base_` read-only member is the root ctypes object that owns the
2076 memory block.
Georg Brandl116aa622007-08-15 14:28:22 +00002077
Benjamin Petersone41251e2008-04-25 01:59:09 +00002078 .. attribute:: _b_needsfree_
Georg Brandl116aa622007-08-15 14:28:22 +00002079
Benjamin Petersone41251e2008-04-25 01:59:09 +00002080 This read-only variable is true when the ctypes data instance has
2081 allocated the memory block itself, false otherwise.
2082
Benjamin Petersone41251e2008-04-25 01:59:09 +00002083 .. attribute:: _objects
2084
2085 This member is either ``None`` or a dictionary containing Python objects
2086 that need to be kept alive so that the memory block contents is kept
2087 valid. This object is only exposed for debugging; never modify the
2088 contents of this dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002089
2090
2091.. _ctypes-fundamental-data-types-2:
2092
2093Fundamental data types
2094^^^^^^^^^^^^^^^^^^^^^^
2095
Georg Brandl116aa622007-08-15 14:28:22 +00002096.. class:: _SimpleCData
2097
Benjamin Peterson35e8c462008-04-24 02:34:53 +00002098 This non-public class is the base class of all fundamental ctypes data
2099 types. It is mentioned here because it contains the common attributes of the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002100 fundamental ctypes data types. :class:`_SimpleCData` is a subclass of
2101 :class:`_CData`, so it inherits their methods and attributes. ctypes data
2102 types that are not and do not contain pointers can now be pickled.
Thomas Heller13394e92008-02-13 20:40:44 +00002103
Benjamin Petersone41251e2008-04-25 01:59:09 +00002104 Instances have a single attribute:
Georg Brandl116aa622007-08-15 14:28:22 +00002105
Benjamin Petersone41251e2008-04-25 01:59:09 +00002106 .. attribute:: value
Georg Brandl116aa622007-08-15 14:28:22 +00002107
Benjamin Petersone41251e2008-04-25 01:59:09 +00002108 This attribute contains the actual value of the instance. For integer and
2109 pointer types, it is an integer, for character types, it is a single
Georg Brandl8d8f1972009-06-08 13:27:23 +00002110 character bytes object or string, for character pointer types it is a
2111 Python bytes object or string.
Georg Brandl116aa622007-08-15 14:28:22 +00002112
Benjamin Petersone41251e2008-04-25 01:59:09 +00002113 When the ``value`` attribute is retrieved from a ctypes instance, usually
Georg Brandl8d8f1972009-06-08 13:27:23 +00002114 a new object is returned each time. :mod:`ctypes` does *not* implement
Benjamin Petersone41251e2008-04-25 01:59:09 +00002115 original object return, always a new object is constructed. The same is
2116 true for all other ctypes object instances.
Georg Brandl116aa622007-08-15 14:28:22 +00002117
Georg Brandl8d8f1972009-06-08 13:27:23 +00002118
Georg Brandl116aa622007-08-15 14:28:22 +00002119Fundamental data types, when returned as foreign function call results, or, for
2120example, by retrieving structure field members or array items, are transparently
2121converted to native Python types. In other words, if a foreign function has a
Georg Brandl8d8f1972009-06-08 13:27:23 +00002122:attr:`restype` of :class:`c_char_p`, you will always receive a Python bytes
2123object, *not* a :class:`c_char_p` instance.
2124
2125.. XXX above is false, it actually returns a Unicode string
Georg Brandl116aa622007-08-15 14:28:22 +00002126
Thomas Woutersed03b412007-08-28 21:37:11 +00002127Subclasses of fundamental data types do *not* inherit this behavior. So, if a
Georg Brandl116aa622007-08-15 14:28:22 +00002128foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2129receive an instance of this subclass from the function call. Of course, you can
2130get the value of the pointer by accessing the ``value`` attribute.
2131
2132These are the fundamental ctypes data types:
2133
Georg Brandl116aa622007-08-15 14:28:22 +00002134.. class:: c_byte
2135
Georg Brandl60203b42010-10-06 10:11:56 +00002136 Represents the C :c:type:`signed char` datatype, and interprets the value as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002137 small integer. The constructor accepts an optional integer initializer; no
2138 overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002139
2140
2141.. class:: c_char
2142
Georg Brandl60203b42010-10-06 10:11:56 +00002143 Represents the C :c:type:`char` datatype, and interprets the value as a single
Georg Brandl1d837bc2009-12-29 11:24:00 +00002144 character. The constructor accepts an optional string initializer, the
2145 length of the string must be exactly one character.
Georg Brandl116aa622007-08-15 14:28:22 +00002146
2147
2148.. class:: c_char_p
2149
Georg Brandl60203b42010-10-06 10:11:56 +00002150 Represents the C :c:type:`char *` datatype when it points to a zero-terminated
Georg Brandl1d837bc2009-12-29 11:24:00 +00002151 string. For a general character pointer that may also point to binary data,
2152 ``POINTER(c_char)`` must be used. The constructor accepts an integer
2153 address, or a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +00002154
2155
2156.. class:: c_double
2157
Georg Brandl60203b42010-10-06 10:11:56 +00002158 Represents the C :c:type:`double` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002159 optional float initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002160
2161
Thomas Wouters89d996e2007-09-08 17:39:28 +00002162.. class:: c_longdouble
2163
Georg Brandl60203b42010-10-06 10:11:56 +00002164 Represents the C :c:type:`long double` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002165 optional float initializer. On platforms where ``sizeof(long double) ==
2166 sizeof(double)`` it is an alias to :class:`c_double`.
Thomas Wouters89d996e2007-09-08 17:39:28 +00002167
Georg Brandl116aa622007-08-15 14:28:22 +00002168.. class:: c_float
2169
Georg Brandl60203b42010-10-06 10:11:56 +00002170 Represents the C :c:type:`float` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002171 optional float initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002172
2173
2174.. class:: c_int
2175
Georg Brandl60203b42010-10-06 10:11:56 +00002176 Represents the C :c:type:`signed int` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002177 optional integer initializer; no overflow checking is done. On platforms
2178 where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
Georg Brandl116aa622007-08-15 14:28:22 +00002179
2180
2181.. class:: c_int8
2182
Georg Brandl60203b42010-10-06 10:11:56 +00002183 Represents the C 8-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002184 :class:`c_byte`.
2185
2186
2187.. class:: c_int16
2188
Georg Brandl60203b42010-10-06 10:11:56 +00002189 Represents the C 16-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002190 :class:`c_short`.
2191
2192
2193.. class:: c_int32
2194
Georg Brandl60203b42010-10-06 10:11:56 +00002195 Represents the C 32-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002196 :class:`c_int`.
2197
2198
2199.. class:: c_int64
2200
Georg Brandl60203b42010-10-06 10:11:56 +00002201 Represents the C 64-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002202 :class:`c_longlong`.
2203
2204
2205.. class:: c_long
2206
Georg Brandl60203b42010-10-06 10:11:56 +00002207 Represents the C :c:type:`signed long` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002208 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002209
2210
2211.. class:: c_longlong
2212
Georg Brandl60203b42010-10-06 10:11:56 +00002213 Represents the C :c:type:`signed long long` datatype. The constructor accepts
Georg Brandl1d837bc2009-12-29 11:24:00 +00002214 an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002215
2216
2217.. class:: c_short
2218
Georg Brandl60203b42010-10-06 10:11:56 +00002219 Represents the C :c:type:`signed short` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002220 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002221
2222
2223.. class:: c_size_t
2224
Georg Brandl60203b42010-10-06 10:11:56 +00002225 Represents the C :c:type:`size_t` datatype.
Georg Brandl116aa622007-08-15 14:28:22 +00002226
2227
Gregory P. Smith1a530912010-03-01 04:59:27 +00002228.. class:: c_ssize_t
2229
Georg Brandl60203b42010-10-06 10:11:56 +00002230 Represents the C :c:type:`ssize_t` datatype.
Gregory P. Smith1a530912010-03-01 04:59:27 +00002231
2232 .. versionadded:: 3.2
2233
2234
Georg Brandl116aa622007-08-15 14:28:22 +00002235.. class:: c_ubyte
2236
Georg Brandl60203b42010-10-06 10:11:56 +00002237 Represents the C :c:type:`unsigned char` datatype, it interprets the value as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002238 small integer. The constructor accepts an optional integer initializer; no
2239 overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002240
2241
2242.. class:: c_uint
2243
Georg Brandl60203b42010-10-06 10:11:56 +00002244 Represents the C :c:type:`unsigned int` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002245 optional integer initializer; no overflow checking is done. On platforms
2246 where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
Georg Brandl116aa622007-08-15 14:28:22 +00002247
2248
2249.. class:: c_uint8
2250
Georg Brandl60203b42010-10-06 10:11:56 +00002251 Represents the C 8-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002252 :class:`c_ubyte`.
2253
2254
2255.. class:: c_uint16
2256
Georg Brandl60203b42010-10-06 10:11:56 +00002257 Represents the C 16-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002258 :class:`c_ushort`.
2259
2260
2261.. class:: c_uint32
2262
Georg Brandl60203b42010-10-06 10:11:56 +00002263 Represents the C 32-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002264 :class:`c_uint`.
2265
2266
2267.. class:: c_uint64
2268
Georg Brandl60203b42010-10-06 10:11:56 +00002269 Represents the C 64-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002270 :class:`c_ulonglong`.
2271
2272
2273.. class:: c_ulong
2274
Georg Brandl60203b42010-10-06 10:11:56 +00002275 Represents the C :c:type:`unsigned long` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002276 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002277
2278
2279.. class:: c_ulonglong
2280
Georg Brandl60203b42010-10-06 10:11:56 +00002281 Represents the C :c:type:`unsigned long long` datatype. The constructor
Georg Brandl1d837bc2009-12-29 11:24:00 +00002282 accepts an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002283
2284
2285.. class:: c_ushort
2286
Georg Brandl60203b42010-10-06 10:11:56 +00002287 Represents the C :c:type:`unsigned short` datatype. The constructor accepts
Georg Brandl1d837bc2009-12-29 11:24:00 +00002288 an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002289
2290
2291.. class:: c_void_p
2292
Georg Brandl60203b42010-10-06 10:11:56 +00002293 Represents the C :c:type:`void *` type. The value is represented as integer.
Georg Brandl1d837bc2009-12-29 11:24:00 +00002294 The constructor accepts an optional integer initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002295
2296
2297.. class:: c_wchar
2298
Georg Brandl60203b42010-10-06 10:11:56 +00002299 Represents the C :c:type:`wchar_t` datatype, and interprets the value as a
Georg Brandl1d837bc2009-12-29 11:24:00 +00002300 single character unicode string. The constructor accepts an optional string
Georg Brandl116aa622007-08-15 14:28:22 +00002301 initializer, the length of the string must be exactly one character.
2302
2303
2304.. class:: c_wchar_p
2305
Georg Brandl60203b42010-10-06 10:11:56 +00002306 Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a
Georg Brandl1d837bc2009-12-29 11:24:00 +00002307 zero-terminated wide character string. The constructor accepts an integer
Georg Brandl116aa622007-08-15 14:28:22 +00002308 address, or a string.
2309
2310
2311.. class:: c_bool
2312
Georg Brandl60203b42010-10-06 10:11:56 +00002313 Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from
Serhiy Storchakafbc1c262013-11-29 12:17:13 +02002314 C99). Its value can be ``True`` or ``False``, and the constructor accepts any object
Georg Brandl1d837bc2009-12-29 11:24:00 +00002315 that has a truth value.
Georg Brandl116aa622007-08-15 14:28:22 +00002316
Georg Brandl116aa622007-08-15 14:28:22 +00002317
2318.. class:: HRESULT
2319
Georg Brandl60203b42010-10-06 10:11:56 +00002320 Windows only: Represents a :c:type:`HRESULT` value, which contains success or
Georg Brandl116aa622007-08-15 14:28:22 +00002321 error information for a function or method call.
2322
2323
2324.. class:: py_object
2325
Georg Brandl60203b42010-10-06 10:11:56 +00002326 Represents the C :c:type:`PyObject *` datatype. Calling this without an
2327 argument creates a ``NULL`` :c:type:`PyObject *` pointer.
Georg Brandl116aa622007-08-15 14:28:22 +00002328
Georg Brandl1d837bc2009-12-29 11:24:00 +00002329The :mod:`ctypes.wintypes` module provides quite some other Windows specific
Georg Brandl60203b42010-10-06 10:11:56 +00002330data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`. Some
2331useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined.
Georg Brandl116aa622007-08-15 14:28:22 +00002332
2333
2334.. _ctypes-structured-data-types:
2335
2336Structured data types
2337^^^^^^^^^^^^^^^^^^^^^
2338
2339
2340.. class:: Union(*args, **kw)
2341
2342 Abstract base class for unions in native byte order.
2343
2344
2345.. class:: BigEndianStructure(*args, **kw)
2346
2347 Abstract base class for structures in *big endian* byte order.
2348
2349
2350.. class:: LittleEndianStructure(*args, **kw)
2351
2352 Abstract base class for structures in *little endian* byte order.
2353
2354Structures with non-native byte order cannot contain pointer type fields, or any
2355other data types containing pointer type fields.
2356
2357
2358.. class:: Structure(*args, **kw)
2359
2360 Abstract base class for structures in *native* byte order.
2361
Benjamin Petersone41251e2008-04-25 01:59:09 +00002362 Concrete structure and union types must be created by subclassing one of these
Georg Brandl8d8f1972009-06-08 13:27:23 +00002363 types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
Benjamin Petersone41251e2008-04-25 01:59:09 +00002364 create :term:`descriptor`\s which allow reading and writing the fields by direct
2365 attribute accesses. These are the
Georg Brandl116aa622007-08-15 14:28:22 +00002366
2367
Benjamin Petersone41251e2008-04-25 01:59:09 +00002368 .. attribute:: _fields_
Georg Brandl116aa622007-08-15 14:28:22 +00002369
Benjamin Petersone41251e2008-04-25 01:59:09 +00002370 A sequence defining the structure fields. The items must be 2-tuples or
2371 3-tuples. The first item is the name of the field, the second item
2372 specifies the type of the field; it can be any ctypes data type.
Georg Brandl116aa622007-08-15 14:28:22 +00002373
Benjamin Petersone41251e2008-04-25 01:59:09 +00002374 For integer type fields like :class:`c_int`, a third optional item can be
2375 given. It must be a small positive integer defining the bit width of the
2376 field.
Georg Brandl116aa622007-08-15 14:28:22 +00002377
Benjamin Petersone41251e2008-04-25 01:59:09 +00002378 Field names must be unique within one structure or union. This is not
2379 checked, only one field can be accessed when names are repeated.
Georg Brandl116aa622007-08-15 14:28:22 +00002380
Benjamin Petersone41251e2008-04-25 01:59:09 +00002381 It is possible to define the :attr:`_fields_` class variable *after* the
Martin Panterc04fb562016-02-10 05:44:01 +00002382 class statement that defines the Structure subclass, this allows creating
Benjamin Petersone41251e2008-04-25 01:59:09 +00002383 data types that directly or indirectly reference themselves::
Georg Brandl116aa622007-08-15 14:28:22 +00002384
Benjamin Petersone41251e2008-04-25 01:59:09 +00002385 class List(Structure):
2386 pass
2387 List._fields_ = [("pnext", POINTER(List)),
2388 ...
2389 ]
Georg Brandl116aa622007-08-15 14:28:22 +00002390
Benjamin Petersone41251e2008-04-25 01:59:09 +00002391 The :attr:`_fields_` class variable must, however, be defined before the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002392 type is first used (an instance is created, :func:`sizeof` is called on it,
Benjamin Petersone41251e2008-04-25 01:59:09 +00002393 and so on). Later assignments to the :attr:`_fields_` class variable will
2394 raise an AttributeError.
Georg Brandl116aa622007-08-15 14:28:22 +00002395
Yavor Konstantinov133fc892019-05-15 08:02:13 -07002396 It is possible to define sub-subclasses of structure types, they inherit
Benjamin Petersone41251e2008-04-25 01:59:09 +00002397 the fields of the base class plus the :attr:`_fields_` defined in the
2398 sub-subclass, if any.
Georg Brandl116aa622007-08-15 14:28:22 +00002399
2400
Benjamin Petersone41251e2008-04-25 01:59:09 +00002401 .. attribute:: _pack_
Georg Brandl116aa622007-08-15 14:28:22 +00002402
Martin Panterc04fb562016-02-10 05:44:01 +00002403 An optional small integer that allows overriding the alignment of
Benjamin Petersone41251e2008-04-25 01:59:09 +00002404 structure fields in the instance. :attr:`_pack_` must already be defined
2405 when :attr:`_fields_` is assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002406
2407
Benjamin Petersone41251e2008-04-25 01:59:09 +00002408 .. attribute:: _anonymous_
Georg Brandl116aa622007-08-15 14:28:22 +00002409
Benjamin Petersone41251e2008-04-25 01:59:09 +00002410 An optional sequence that lists the names of unnamed (anonymous) fields.
Georg Brandl1d837bc2009-12-29 11:24:00 +00002411 :attr:`_anonymous_` must be already defined when :attr:`_fields_` is
2412 assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002413
Benjamin Petersone41251e2008-04-25 01:59:09 +00002414 The fields listed in this variable must be structure or union type fields.
Martin Panterc04fb562016-02-10 05:44:01 +00002415 :mod:`ctypes` will create descriptors in the structure type that allows
2416 accessing the nested fields directly, without the need to create the
Benjamin Petersone41251e2008-04-25 01:59:09 +00002417 structure or union field.
Georg Brandl116aa622007-08-15 14:28:22 +00002418
Benjamin Petersone41251e2008-04-25 01:59:09 +00002419 Here is an example type (Windows)::
Georg Brandl116aa622007-08-15 14:28:22 +00002420
Benjamin Petersone41251e2008-04-25 01:59:09 +00002421 class _U(Union):
2422 _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2423 ("lpadesc", POINTER(ARRAYDESC)),
2424 ("hreftype", HREFTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002425
Benjamin Petersone41251e2008-04-25 01:59:09 +00002426 class TYPEDESC(Structure):
Benjamin Petersonb58dda72009-01-18 22:27:04 +00002427 _anonymous_ = ("u",)
Benjamin Petersone41251e2008-04-25 01:59:09 +00002428 _fields_ = [("u", _U),
2429 ("vt", VARTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002430
Georg Brandl116aa622007-08-15 14:28:22 +00002431
Benjamin Petersone41251e2008-04-25 01:59:09 +00002432 The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2433 specifies which one of the union fields is valid. Since the ``u`` field
2434 is defined as anonymous field, it is now possible to access the members
2435 directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2436 are equivalent, but the former is faster since it does not need to create
2437 a temporary union instance::
Georg Brandl116aa622007-08-15 14:28:22 +00002438
Benjamin Petersone41251e2008-04-25 01:59:09 +00002439 td = TYPEDESC()
2440 td.vt = VT_PTR
2441 td.lptdesc = POINTER(some_type)
2442 td.u.lptdesc = POINTER(some_type)
Georg Brandl116aa622007-08-15 14:28:22 +00002443
Yavor Konstantinov133fc892019-05-15 08:02:13 -07002444 It is possible to define sub-subclasses of structures, they inherit the
Georg Brandl1d837bc2009-12-29 11:24:00 +00002445 fields of the base class. If the subclass definition has a separate
2446 :attr:`_fields_` variable, the fields specified in this are appended to the
2447 fields of the base class.
Georg Brandl116aa622007-08-15 14:28:22 +00002448
Georg Brandl1d837bc2009-12-29 11:24:00 +00002449 Structure and union constructors accept both positional and keyword
2450 arguments. Positional arguments are used to initialize member fields in the
2451 same order as they are appear in :attr:`_fields_`. Keyword arguments in the
2452 constructor are interpreted as attribute assignments, so they will initialize
2453 :attr:`_fields_` with the same name, or create new attributes for names not
2454 present in :attr:`_fields_`.
Georg Brandl116aa622007-08-15 14:28:22 +00002455
2456
2457.. _ctypes-arrays-pointers:
2458
2459Arrays and pointers
2460^^^^^^^^^^^^^^^^^^^
2461
Martin Panter34360c82016-01-29 10:12:19 +00002462.. class:: Array(\*args)
2463
2464 Abstract base class for arrays.
2465
2466 The recommended way to create concrete array types is by multiplying any
2467 :mod:`ctypes` data type with a positive integer. Alternatively, you can subclass
2468 this type and define :attr:`_length_` and :attr:`_type_` class variables.
2469 Array elements can be read and written using standard
2470 subscript and slice accesses; for slice reads, the resulting object is
2471 *not* itself an :class:`Array`.
2472
2473
2474 .. attribute:: _length_
2475
2476 A positive integer specifying the number of elements in the array.
2477 Out-of-range subscripts result in an :exc:`IndexError`. Will be
2478 returned by :func:`len`.
2479
2480
2481 .. attribute:: _type_
2482
2483 Specifies the type of each element in the array.
2484
2485
2486 Array subclass constructors accept positional arguments, used to
2487 initialize the elements in order.
2488
2489
2490.. class:: _Pointer
2491
2492 Private, abstract base class for pointers.
2493
2494 Concrete pointer types are created by calling :func:`POINTER` with the
2495 type that will be pointed to; this is done automatically by
2496 :func:`pointer`.
2497
2498 If a pointer points to an array, its elements can be read and
2499 written using standard subscript and slice accesses. Pointer objects
2500 have no size, so :func:`len` will raise :exc:`TypeError`. Negative
2501 subscripts will read from the memory *before* the pointer (as in C), and
2502 out-of-range subscripts will probably crash with an access violation (if
2503 you're lucky).
2504
2505
2506 .. attribute:: _type_
2507
2508 Specifies the type pointed to.
2509
2510 .. attribute:: contents
2511
2512 Returns the object to which to pointer points. Assigning to this
2513 attribute changes the pointer to point to the assigned object.
Georg Brandl116aa622007-08-15 14:28:22 +00002514