blob: ccbb8ec563e5bf37217410f4f52393e0d3140e92 [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.
6.. moduleauthor:: Thomas Heller <theller@python.net>
7
8
Georg Brandl1d837bc2009-12-29 11:24:00 +00009:mod:`ctypes` is a foreign function library for Python. It provides C compatible
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000010data types, and allows calling functions in DLLs or shared libraries. It can be
Georg Brandl116aa622007-08-15 14:28:22 +000011used to wrap these libraries in pure Python.
12
13
14.. _ctypes-ctypes-tutorial:
15
16ctypes tutorial
17---------------
18
Georg Brandl1d837bc2009-12-29 11:24:00 +000019Note: The code samples in this tutorial use :mod:`doctest` to make sure that
20they actually work. Since some code samples behave differently under Linux,
21Windows, or Mac OS X, they contain doctest directives in comments.
Georg Brandl116aa622007-08-15 14:28:22 +000022
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000023Note: Some code samples reference the ctypes :class:`c_int` type. This type is
24an alias for the :class:`c_long` type on 32-bit systems. So, you should not be
Georg Brandl116aa622007-08-15 14:28:22 +000025confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
26they are actually the same type.
27
28
29.. _ctypes-loading-dynamic-link-libraries:
30
31Loading dynamic link libraries
32^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
33
Georg Brandl8d8f1972009-06-08 13:27:23 +000034:mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll*
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000035objects, for loading dynamic link libraries.
Georg Brandl116aa622007-08-15 14:28:22 +000036
37You load libraries by accessing them as attributes of these objects. *cdll*
38loads libraries which export functions using the standard ``cdecl`` calling
39convention, while *windll* libraries call functions using the ``stdcall``
40calling convention. *oledll* also uses the ``stdcall`` calling convention, and
Georg Brandl60203b42010-10-06 10:11:56 +000041assumes the functions return a Windows :c:type:`HRESULT` error code. The error
Antoine Pitrou442ee032011-10-12 18:53:23 +020042code is used to automatically raise a :class:`OSError` exception when the
Georg Brandl1d837bc2009-12-29 11:24:00 +000043function call fails.
Georg Brandl116aa622007-08-15 14:28:22 +000044
Antoine Pitrou442ee032011-10-12 18:53:23 +020045.. versionchanged:: 3.3
46 Windows errors used to raise :exc:`WindowsError`, which is now an alias
47 of :exc:`OSError`.
48
49
Georg Brandl116aa622007-08-15 14:28:22 +000050Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
51library containing most standard C functions, and uses the cdecl calling
52convention::
53
54 >>> from ctypes import *
Georg Brandl6911e3c2007-09-04 07:15:32 +000055 >>> print(windll.kernel32) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000056 <WinDLL 'kernel32', handle ... at ...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000057 >>> print(cdll.msvcrt) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000058 <CDLL 'msvcrt', handle ... at ...>
59 >>> libc = cdll.msvcrt # doctest: +WINDOWS
60 >>>
61
Thomas Heller2fadaa22008-06-16 19:56:33 +000062Windows appends the usual ``.dll`` file suffix automatically.
Georg Brandl116aa622007-08-15 14:28:22 +000063
64On Linux, it is required to specify the filename *including* the extension to
Thomas Heller2fadaa22008-06-16 19:56:33 +000065load a library, so attribute access can not be used to load libraries. Either the
Georg Brandl116aa622007-08-15 14:28:22 +000066:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
67the library by creating an instance of CDLL by calling the constructor::
68
69 >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
70 <CDLL 'libc.so.6', handle ... at ...>
71 >>> libc = CDLL("libc.so.6") # doctest: +LINUX
72 >>> libc # doctest: +LINUX
73 <CDLL 'libc.so.6', handle ... at ...>
74 >>>
75
Christian Heimes5b5e81c2007-12-31 16:14:33 +000076.. XXX Add section for Mac OS X.
Georg Brandl116aa622007-08-15 14:28:22 +000077
78
79.. _ctypes-accessing-functions-from-loaded-dlls:
80
81Accessing functions from loaded dlls
82^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
83
84Functions are accessed as attributes of dll objects::
85
86 >>> from ctypes import *
87 >>> libc.printf
88 <_FuncPtr object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000089 >>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000090 <_FuncPtr object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000091 >>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000092 Traceback (most recent call last):
93 File "<stdin>", line 1, in ?
94 File "ctypes.py", line 239, in __getattr__
95 func = _StdcallFuncPtr(name, self)
96 AttributeError: function 'MyOwnFunction' not found
97 >>>
98
99Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
100as well as UNICODE versions of a function. The UNICODE version is exported with
101an ``W`` appended to the name, while the ANSI version is exported with an ``A``
102appended to the name. The win32 ``GetModuleHandle`` function, which returns a
103*module handle* for a given module name, has the following C prototype, and a
104macro is used to expose one of them as ``GetModuleHandle`` depending on whether
105UNICODE is defined or not::
106
107 /* ANSI version */
108 HMODULE GetModuleHandleA(LPCSTR lpModuleName);
109 /* UNICODE version */
110 HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
111
112*windll* does not try to select one of them by magic, you must access the
113version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
Georg Brandl8d8f1972009-06-08 13:27:23 +0000114explicitly, and then call it with bytes or string objects respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116Sometimes, dlls export functions with names which aren't valid Python
Georg Brandl1d837bc2009-12-29 11:24:00 +0000117identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
118:func:`getattr` to retrieve the function::
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120 >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
121 <_FuncPtr object at 0x...>
122 >>>
123
124On Windows, some dlls export functions not by name but by ordinal. These
125functions can be accessed by indexing the dll object with the ordinal number::
126
127 >>> cdll.kernel32[1] # doctest: +WINDOWS
128 <_FuncPtr object at 0x...>
129 >>> cdll.kernel32[0] # doctest: +WINDOWS
130 Traceback (most recent call last):
131 File "<stdin>", line 1, in ?
132 File "ctypes.py", line 310, in __getitem__
133 func = _StdcallFuncPtr(name, self)
134 AttributeError: function ordinal 0 not found
135 >>>
136
137
138.. _ctypes-calling-functions:
139
140Calling functions
141^^^^^^^^^^^^^^^^^
142
143You can call these functions like any other Python callable. This example uses
144the ``time()`` function, which returns system time in seconds since the Unix
145epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
146handle.
147
148This example calls both functions with a NULL pointer (``None`` should be used
149as the NULL pointer)::
150
Georg Brandl6911e3c2007-09-04 07:15:32 +0000151 >>> print(libc.time(None)) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000152 1150640792
Georg Brandl6911e3c2007-09-04 07:15:32 +0000153 >>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000154 0x1d000000
155 >>>
156
Georg Brandl1d837bc2009-12-29 11:24:00 +0000157:mod:`ctypes` tries to protect you from calling functions with the wrong number
158of arguments or the wrong calling convention. Unfortunately this only works on
Georg Brandl116aa622007-08-15 14:28:22 +0000159Windows. It does this by examining the stack after the function returns, so
160although an error is raised the function *has* been called::
161
162 >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
163 Traceback (most recent call last):
164 File "<stdin>", line 1, in ?
165 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
166 >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
167 Traceback (most recent call last):
168 File "<stdin>", line 1, in ?
169 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
170 >>>
171
172The same exception is raised when you call an ``stdcall`` function with the
173``cdecl`` calling convention, or vice versa::
174
175 >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
176 Traceback (most recent call last):
177 File "<stdin>", line 1, in ?
178 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
179 >>>
180
Georg Brandl8d8f1972009-06-08 13:27:23 +0000181 >>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000182 Traceback (most recent call last):
183 File "<stdin>", line 1, in ?
184 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
185 >>>
186
187To find out the correct calling convention you have to look into the C header
188file or the documentation for the function you want to call.
189
Georg Brandl8d8f1972009-06-08 13:27:23 +0000190On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
Georg Brandl116aa622007-08-15 14:28:22 +0000191crashes from general protection faults when functions are called with invalid
192argument values::
193
194 >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
195 Traceback (most recent call last):
196 File "<stdin>", line 1, in ?
Antoine Pitrou442ee032011-10-12 18:53:23 +0200197 OSError: exception: access violation reading 0x00000020
Georg Brandl116aa622007-08-15 14:28:22 +0000198 >>>
199
Georg Brandl1d837bc2009-12-29 11:24:00 +0000200There are, however, enough ways to crash Python with :mod:`ctypes`, so you
Georg Brandlb33c6eb2013-10-06 10:51:01 +0200201should be careful anyway. The :mod:`faulthandler` module can be helpful in
202debugging crashes (e.g. from segmentation faults produced by erroneous C library
203calls).
Georg Brandl116aa622007-08-15 14:28:22 +0000204
Georg Brandl8d8f1972009-06-08 13:27:23 +0000205``None``, integers, bytes objects and (unicode) strings are the only native
Georg Brandl116aa622007-08-15 14:28:22 +0000206Python objects that can directly be used as parameters in these function calls.
Georg Brandl1d837bc2009-12-29 11:24:00 +0000207``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are passed
Georg Brandl60203b42010-10-06 10:11:56 +0000208as pointer to the memory block that contains their data (:c:type:`char *` or
209:c:type:`wchar_t *`). Python integers are passed as the platforms default C
210:c:type:`int` type, their value is masked to fit into the C type.
Georg Brandl116aa622007-08-15 14:28:22 +0000211
212Before we move on calling functions with other parameter types, we have to learn
Georg Brandl8d8f1972009-06-08 13:27:23 +0000213more about :mod:`ctypes` data types.
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215
216.. _ctypes-fundamental-data-types:
217
218Fundamental data types
219^^^^^^^^^^^^^^^^^^^^^^
220
Georg Brandl8d8f1972009-06-08 13:27:23 +0000221:mod:`ctypes` defines a number of primitive C compatible data types :
Georg Brandl116aa622007-08-15 14:28:22 +0000222
Georg Brandl60203b42010-10-06 10:11:56 +0000223+----------------------+------------------------------------------+----------------------------+
224| ctypes type | C type | Python type |
225+======================+==========================================+============================+
Georg Brandlecdd63f2011-01-19 20:05:49 +0000226| :class:`c_bool` | :c:type:`_Bool` | bool (1) |
227+----------------------+------------------------------------------+----------------------------+
Georg Brandl60203b42010-10-06 10:11:56 +0000228| :class:`c_char` | :c:type:`char` | 1-character bytes object |
229+----------------------+------------------------------------------+----------------------------+
230| :class:`c_wchar` | :c:type:`wchar_t` | 1-character string |
231+----------------------+------------------------------------------+----------------------------+
232| :class:`c_byte` | :c:type:`char` | int |
233+----------------------+------------------------------------------+----------------------------+
234| :class:`c_ubyte` | :c:type:`unsigned char` | int |
235+----------------------+------------------------------------------+----------------------------+
236| :class:`c_short` | :c:type:`short` | int |
237+----------------------+------------------------------------------+----------------------------+
238| :class:`c_ushort` | :c:type:`unsigned short` | int |
239+----------------------+------------------------------------------+----------------------------+
240| :class:`c_int` | :c:type:`int` | int |
241+----------------------+------------------------------------------+----------------------------+
242| :class:`c_uint` | :c:type:`unsigned int` | int |
243+----------------------+------------------------------------------+----------------------------+
244| :class:`c_long` | :c:type:`long` | int |
245+----------------------+------------------------------------------+----------------------------+
246| :class:`c_ulong` | :c:type:`unsigned long` | int |
247+----------------------+------------------------------------------+----------------------------+
248| :class:`c_longlong` | :c:type:`__int64` or :c:type:`long long` | int |
249+----------------------+------------------------------------------+----------------------------+
250| :class:`c_ulonglong` | :c:type:`unsigned __int64` or | int |
251| | :c:type:`unsigned long long` | |
252+----------------------+------------------------------------------+----------------------------+
Antoine Pitrou52cc7222012-07-12 20:31:50 +0200253| :class:`c_size_t` | :c:type:`size_t` | int |
254+----------------------+------------------------------------------+----------------------------+
255| :class:`c_ssize_t` | :c:type:`ssize_t` or | int |
256| | :c:type:`Py_ssize_t` | |
257+----------------------+------------------------------------------+----------------------------+
Georg Brandl60203b42010-10-06 10:11:56 +0000258| :class:`c_float` | :c:type:`float` | float |
259+----------------------+------------------------------------------+----------------------------+
260| :class:`c_double` | :c:type:`double` | float |
261+----------------------+------------------------------------------+----------------------------+
262| :class:`c_longdouble`| :c:type:`long double` | float |
263+----------------------+------------------------------------------+----------------------------+
264| :class:`c_char_p` | :c:type:`char *` (NUL terminated) | bytes object or ``None`` |
265+----------------------+------------------------------------------+----------------------------+
266| :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | string or ``None`` |
267+----------------------+------------------------------------------+----------------------------+
268| :class:`c_void_p` | :c:type:`void *` | int or ``None`` |
269+----------------------+------------------------------------------+----------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Georg Brandlecdd63f2011-01-19 20:05:49 +0000271(1)
272 The constructor accepts any object with a truth value.
273
Georg Brandl116aa622007-08-15 14:28:22 +0000274All these types can be created by calling them with an optional initializer of
275the correct type and value::
276
277 >>> c_int()
278 c_long(0)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000279 >>> c_wchar_p("Hello, World")
280 c_wchar_p('Hello, World')
Georg Brandl116aa622007-08-15 14:28:22 +0000281 >>> c_ushort(-3)
282 c_ushort(65533)
283 >>>
284
285Since these types are mutable, their value can also be changed afterwards::
286
287 >>> i = c_int(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000288 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000289 c_long(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000290 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000291 42
292 >>> i.value = -99
Georg Brandl6911e3c2007-09-04 07:15:32 +0000293 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000294 -99
295 >>>
296
297Assigning a new value to instances of the pointer types :class:`c_char_p`,
298:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
299point to, *not the contents* of the memory block (of course not, because Python
Georg Brandl8d8f1972009-06-08 13:27:23 +0000300bytes objects are immutable)::
Georg Brandl116aa622007-08-15 14:28:22 +0000301
302 >>> s = "Hello, World"
Georg Brandl8d8f1972009-06-08 13:27:23 +0000303 >>> c_s = c_wchar_p(s)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000304 >>> print(c_s)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000305 c_wchar_p('Hello, World')
Georg Brandl116aa622007-08-15 14:28:22 +0000306 >>> c_s.value = "Hi, there"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000307 >>> print(c_s)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000308 c_wchar_p('Hi, there')
309 >>> print(s) # first object is unchanged
Georg Brandl116aa622007-08-15 14:28:22 +0000310 Hello, World
311 >>>
312
313You should be careful, however, not to pass them to functions expecting pointers
314to mutable memory. If you need mutable memory blocks, ctypes has a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000315:func:`create_string_buffer` function which creates these in various ways. The
Georg Brandl116aa622007-08-15 14:28:22 +0000316current memory block contents can be accessed (or changed) with the ``raw``
317property; if you want to access it as NUL terminated string, use the ``value``
318property::
319
320 >>> from ctypes import *
Georg Brandl8d8f1972009-06-08 13:27:23 +0000321 >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
Georg Brandl6911e3c2007-09-04 07:15:32 +0000322 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000323 3 b'\x00\x00\x00'
324 >>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string
Georg Brandl6911e3c2007-09-04 07:15:32 +0000325 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000326 6 b'Hello\x00'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000327 >>> print(repr(p.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000328 b'Hello'
329 >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000330 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000331 10 b'Hello\x00\x00\x00\x00\x00'
332 >>> p.value = b"Hi"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000333 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000334 10 b'Hi\x00lo\x00\x00\x00\x00\x00'
Georg Brandl116aa622007-08-15 14:28:22 +0000335 >>>
336
Georg Brandl1d837bc2009-12-29 11:24:00 +0000337The :func:`create_string_buffer` function replaces the :func:`c_buffer` function
338(which is still available as an alias), as well as the :func:`c_string` function
Georg Brandl8d8f1972009-06-08 13:27:23 +0000339from earlier ctypes releases. To create a mutable memory block containing
Georg Brandl60203b42010-10-06 10:11:56 +0000340unicode characters of the C type :c:type:`wchar_t` use the
Georg Brandl8d8f1972009-06-08 13:27:23 +0000341:func:`create_unicode_buffer` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343
344.. _ctypes-calling-functions-continued:
345
346Calling functions, continued
347^^^^^^^^^^^^^^^^^^^^^^^^^^^^
348
349Note that printf prints to the real standard output channel, *not* to
Georg Brandl8d8f1972009-06-08 13:27:23 +0000350:data:`sys.stdout`, so these examples will only work at the console prompt, not
351from within *IDLE* or *PythonWin*::
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353 >>> printf = libc.printf
Georg Brandl8d8f1972009-06-08 13:27:23 +0000354 >>> printf(b"Hello, %s\n", b"World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000355 Hello, World!
356 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000357 >>> printf(b"Hello, %S\n", "World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000358 Hello, World!
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000359 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000360 >>> printf(b"%d bottles of beer\n", 42)
Georg Brandl116aa622007-08-15 14:28:22 +0000361 42 bottles of beer
362 19
Georg Brandl8d8f1972009-06-08 13:27:23 +0000363 >>> printf(b"%f bottles of beer\n", 42.5)
Georg Brandl116aa622007-08-15 14:28:22 +0000364 Traceback (most recent call last):
365 File "<stdin>", line 1, in ?
366 ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
367 >>>
368
369As has been mentioned before, all Python types except integers, strings, and
Georg Brandl8d8f1972009-06-08 13:27:23 +0000370bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so
Georg Brandl116aa622007-08-15 14:28:22 +0000371that they can be converted to the required C data type::
372
Georg Brandl8d8f1972009-06-08 13:27:23 +0000373 >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000374 An int 1234, a double 3.140000
Georg Brandl116aa622007-08-15 14:28:22 +0000375 31
376 >>>
377
378
379.. _ctypes-calling-functions-with-own-custom-data-types:
380
381Calling functions with your own custom data types
382^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
383
Georg Brandl1d837bc2009-12-29 11:24:00 +0000384You can also customize :mod:`ctypes` argument conversion to allow instances of
385your own classes be used as function arguments. :mod:`ctypes` looks for an
386:attr:`_as_parameter_` attribute and uses this as the function argument. Of
Georg Brandl8d8f1972009-06-08 13:27:23 +0000387course, it must be one of integer, string, or bytes::
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Éric Araujo28053fb2010-11-22 03:09:19 +0000389 >>> class Bottles:
Georg Brandl116aa622007-08-15 14:28:22 +0000390 ... def __init__(self, number):
391 ... self._as_parameter_ = number
392 ...
393 >>> bottles = Bottles(42)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000394 >>> printf(b"%d bottles of beer\n", bottles)
Georg Brandl116aa622007-08-15 14:28:22 +0000395 42 bottles of beer
396 19
397 >>>
398
399If you don't want to store the instance's data in the :attr:`_as_parameter_`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000400instance variable, you could define a :class:`property` which makes the
401attribute available on request.
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403
404.. _ctypes-specifying-required-argument-types:
405
406Specifying the required argument types (function prototypes)
407^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
408
409It is possible to specify the required argument types of functions exported from
410DLLs by setting the :attr:`argtypes` attribute.
411
412:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
413probably not a good example here, because it takes a variable number and
414different types of parameters depending on the format string, on the other hand
415this is quite handy to experiment with this feature)::
416
417 >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000418 >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
Georg Brandl116aa622007-08-15 14:28:22 +0000419 String 'Hi', Int 10, Double 2.200000
420 37
421 >>>
422
423Specifying a format protects against incompatible argument types (just as a
424prototype for a C function), and tries to convert the arguments to valid types::
425
Georg Brandl8d8f1972009-06-08 13:27:23 +0000426 >>> printf(b"%d %d %d", 1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000427 Traceback (most recent call last):
428 File "<stdin>", line 1, in ?
429 ArgumentError: argument 2: exceptions.TypeError: wrong type
Georg Brandl8d8f1972009-06-08 13:27:23 +0000430 >>> printf(b"%s %d %f\n", b"X", 2, 3)
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000431 X 2 3.000000
432 13
Georg Brandl116aa622007-08-15 14:28:22 +0000433 >>>
434
435If you have defined your own classes which you pass to function calls, you have
436to implement a :meth:`from_param` class method for them to be able to use them
437in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
438the Python object passed to the function call, it should do a typecheck or
439whatever is needed to make sure this object is acceptable, and then return the
Thomas Heller2fadaa22008-06-16 19:56:33 +0000440object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
Georg Brandl116aa622007-08-15 14:28:22 +0000441pass as the C function argument in this case. Again, the result should be an
Georg Brandl8d8f1972009-06-08 13:27:23 +0000442integer, string, bytes, a :mod:`ctypes` instance, or an object with an
Georg Brandl116aa622007-08-15 14:28:22 +0000443:attr:`_as_parameter_` attribute.
444
445
446.. _ctypes-return-types:
447
448Return types
449^^^^^^^^^^^^
450
Georg Brandl60203b42010-10-06 10:11:56 +0000451By default functions are assumed to return the C :c:type:`int` type. Other
Georg Brandl1d837bc2009-12-29 11:24:00 +0000452return types can be specified by setting the :attr:`restype` attribute of the
453function object.
Georg Brandl116aa622007-08-15 14:28:22 +0000454
455Here is a more advanced example, it uses the ``strchr`` function, which expects
456a string pointer and a char, and returns a pointer to a string::
457
458 >>> strchr = libc.strchr
Georg Brandl8d8f1972009-06-08 13:27:23 +0000459 >>> strchr(b"abcdef", ord("d")) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000460 8059983
Georg Brandl8d8f1972009-06-08 13:27:23 +0000461 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
462 >>> strchr(b"abcdef", ord("d"))
463 b'def'
464 >>> print(strchr(b"abcdef", ord("x")))
Georg Brandl116aa622007-08-15 14:28:22 +0000465 None
466 >>>
467
468If you want to avoid the ``ord("x")`` calls above, you can set the
469:attr:`argtypes` attribute, and the second argument will be converted from a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000470single character Python bytes object into a C char::
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472 >>> strchr.restype = c_char_p
473 >>> strchr.argtypes = [c_char_p, c_char]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000474 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000475 'def'
Georg Brandl8d8f1972009-06-08 13:27:23 +0000476 >>> strchr(b"abcdef", b"def")
Georg Brandl116aa622007-08-15 14:28:22 +0000477 Traceback (most recent call last):
478 File "<stdin>", line 1, in ?
479 ArgumentError: argument 2: exceptions.TypeError: one character string expected
Georg Brandl8d8f1972009-06-08 13:27:23 +0000480 >>> print(strchr(b"abcdef", b"x"))
Georg Brandl116aa622007-08-15 14:28:22 +0000481 None
Georg Brandl8d8f1972009-06-08 13:27:23 +0000482 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000483 'def'
484 >>>
485
486You can also use a callable Python object (a function or a class for example) as
487the :attr:`restype` attribute, if the foreign function returns an integer. The
Georg Brandl1d837bc2009-12-29 11:24:00 +0000488callable will be called with the *integer* the C function returns, and the
Georg Brandl116aa622007-08-15 14:28:22 +0000489result of this call will be used as the result of your function call. This is
490useful to check for error return values and automatically raise an exception::
491
492 >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
493 >>> def ValidHandle(value):
494 ... if value == 0:
495 ... raise WinError()
496 ... return value
497 ...
498 >>>
499 >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
500 >>> GetModuleHandle(None) # doctest: +WINDOWS
501 486539264
502 >>> GetModuleHandle("something silly") # doctest: +WINDOWS
503 Traceback (most recent call last):
504 File "<stdin>", line 1, in ?
505 File "<stdin>", line 3, in ValidHandle
Antoine Pitrou442ee032011-10-12 18:53:23 +0200506 OSError: [Errno 126] The specified module could not be found.
Georg Brandl116aa622007-08-15 14:28:22 +0000507 >>>
508
509``WinError`` is a function which will call Windows ``FormatMessage()`` api to
510get the string representation of an error code, and *returns* an exception.
511``WinError`` takes an optional error code parameter, if no one is used, it calls
512:func:`GetLastError` to retrieve it.
513
514Please note that a much more powerful error checking mechanism is available
515through the :attr:`errcheck` attribute; see the reference manual for details.
516
517
518.. _ctypes-passing-pointers:
519
520Passing pointers (or: passing parameters by reference)
521^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
522
523Sometimes a C api function expects a *pointer* to a data type as parameter,
524probably to write into the corresponding location, or if the data is too large
525to be passed by value. This is also known as *passing parameters by reference*.
526
Georg Brandl8d8f1972009-06-08 13:27:23 +0000527:mod:`ctypes` exports the :func:`byref` function which is used to pass parameters
528by reference. The same effect can be achieved with the :func:`pointer` function,
529although :func:`pointer` does a lot more work since it constructs a real pointer
Georg Brandl116aa622007-08-15 14:28:22 +0000530object, so it is faster to use :func:`byref` if you don't need the pointer
531object in Python itself::
532
533 >>> i = c_int()
534 >>> f = c_float()
Georg Brandl8d8f1972009-06-08 13:27:23 +0000535 >>> s = create_string_buffer(b'\000' * 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000536 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000537 0 0.0 b''
538 >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
Georg Brandl116aa622007-08-15 14:28:22 +0000539 ... byref(i), byref(f), s)
540 3
Georg Brandl6911e3c2007-09-04 07:15:32 +0000541 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000542 1 3.1400001049 b'Hello'
Georg Brandl116aa622007-08-15 14:28:22 +0000543 >>>
544
545
546.. _ctypes-structures-unions:
547
548Structures and unions
549^^^^^^^^^^^^^^^^^^^^^
550
551Structures and unions must derive from the :class:`Structure` and :class:`Union`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000552base classes which are defined in the :mod:`ctypes` module. Each subclass must
Georg Brandl116aa622007-08-15 14:28:22 +0000553define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
554*2-tuples*, containing a *field name* and a *field type*.
555
Georg Brandl8d8f1972009-06-08 13:27:23 +0000556The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
557derived :mod:`ctypes` type: structure, union, array, pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000558
559Here is a simple example of a POINT structure, which contains two integers named
Georg Brandl8d8f1972009-06-08 13:27:23 +0000560*x* and *y*, and also shows how to initialize a structure in the constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562 >>> from ctypes import *
563 >>> class POINT(Structure):
564 ... _fields_ = [("x", c_int),
565 ... ("y", c_int)]
566 ...
567 >>> point = POINT(10, 20)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000568 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000569 10 20
570 >>> point = POINT(y=5)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000571 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000572 0 5
573 >>> POINT(1, 2, 3)
574 Traceback (most recent call last):
575 File "<stdin>", line 1, in ?
576 ValueError: too many initializers
577 >>>
578
Eli Benderskyf9164e12013-03-06 06:48:57 -0800579You can, however, build much more complicated structures. A structure can
580itself contain other structures by using a structure as a field type.
Georg Brandl116aa622007-08-15 14:28:22 +0000581
Georg Brandl1d837bc2009-12-29 11:24:00 +0000582Here is a RECT structure which contains two POINTs named *upperleft* and
583*lowerright*::
Georg Brandl116aa622007-08-15 14:28:22 +0000584
585 >>> class RECT(Structure):
586 ... _fields_ = [("upperleft", POINT),
587 ... ("lowerright", POINT)]
588 ...
589 >>> rc = RECT(point)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000590 >>> print(rc.upperleft.x, rc.upperleft.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000591 0 5
Georg Brandl6911e3c2007-09-04 07:15:32 +0000592 >>> print(rc.lowerright.x, rc.lowerright.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000593 0 0
594 >>>
595
596Nested structures can also be initialized in the constructor in several ways::
597
598 >>> r = RECT(POINT(1, 2), POINT(3, 4))
599 >>> r = RECT((1, 2), (3, 4))
600
Georg Brandl9afde1c2007-11-01 20:32:30 +0000601Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
602for debugging because they can provide useful information::
Georg Brandl116aa622007-08-15 14:28:22 +0000603
Georg Brandl6911e3c2007-09-04 07:15:32 +0000604 >>> print(POINT.x)
Georg Brandl116aa622007-08-15 14:28:22 +0000605 <Field type=c_long, ofs=0, size=4>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000606 >>> print(POINT.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000607 <Field type=c_long, ofs=4, size=4>
608 >>>
609
610
611.. _ctypes-structureunion-alignment-byte-order:
612
Eli Bendersky490cf442013-03-09 05:54:00 -0800613.. warning::
614
615 :mod:`ctypes` does not support passing unions or structures with bit-fields
616 to functions by value. While this may work on 32-bit x86, it's not
617 guaranteed by the library to work in the general case. Unions and
618 structures with bit-fields should always be passed to functions by pointer.
619
Georg Brandl116aa622007-08-15 14:28:22 +0000620Structure/union alignment and byte order
621^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
622
623By default, Structure and Union fields are aligned in the same way the C
Thomas Woutersed03b412007-08-28 21:37:11 +0000624compiler does it. It is possible to override this behavior be specifying a
Georg Brandl116aa622007-08-15 14:28:22 +0000625:attr:`_pack_` class attribute in the subclass definition. This must be set to a
626positive integer and specifies the maximum alignment for the fields. This is
627what ``#pragma pack(n)`` also does in MSVC.
628
Georg Brandl8d8f1972009-06-08 13:27:23 +0000629:mod:`ctypes` uses the native byte order for Structures and Unions. To build
Georg Brandl116aa622007-08-15 14:28:22 +0000630structures with non-native byte order, you can use one of the
Georg Brandl1d837bc2009-12-29 11:24:00 +0000631:class:`BigEndianStructure`, :class:`LittleEndianStructure`,
632:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These
633classes cannot contain pointer fields.
Georg Brandl116aa622007-08-15 14:28:22 +0000634
635
636.. _ctypes-bit-fields-in-structures-unions:
637
638Bit fields in structures and unions
639^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
640
641It is possible to create structures and unions containing bit fields. Bit fields
642are only possible for integer fields, the bit width is specified as the third
643item in the :attr:`_fields_` tuples::
644
645 >>> class Int(Structure):
646 ... _fields_ = [("first_16", c_int, 16),
647 ... ("second_16", c_int, 16)]
648 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000649 >>> print(Int.first_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000650 <Field type=c_long, ofs=0:0, bits=16>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000651 >>> print(Int.second_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000652 <Field type=c_long, ofs=0:16, bits=16>
653 >>>
654
655
656.. _ctypes-arrays:
657
658Arrays
659^^^^^^
660
661Arrays are sequences, containing a fixed number of instances of the same type.
662
663The recommended way to create array types is by multiplying a data type with a
664positive integer::
665
666 TenPointsArrayType = POINT * 10
667
Thomas Woutersed03b412007-08-28 21:37:11 +0000668Here is an example of an somewhat artificial data type, a structure containing 4
Georg Brandl116aa622007-08-15 14:28:22 +0000669POINTs among other stuff::
670
671 >>> from ctypes import *
672 >>> class POINT(Structure):
673 ... _fields_ = ("x", c_int), ("y", c_int)
674 ...
675 >>> class MyStruct(Structure):
676 ... _fields_ = [("a", c_int),
677 ... ("b", c_float),
678 ... ("point_array", POINT * 4)]
679 >>>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000680 >>> print(len(MyStruct().point_array))
Georg Brandl116aa622007-08-15 14:28:22 +0000681 4
682 >>>
683
684Instances are created in the usual way, by calling the class::
685
686 arr = TenPointsArrayType()
687 for pt in arr:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000688 print(pt.x, pt.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690The above code print a series of ``0 0`` lines, because the array contents is
691initialized to zeros.
692
693Initializers of the correct type can also be specified::
694
695 >>> from ctypes import *
696 >>> TenIntegers = c_int * 10
697 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000698 >>> print(ii)
Georg Brandl116aa622007-08-15 14:28:22 +0000699 <c_long_Array_10 object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000700 >>> for i in ii: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000701 ...
702 1 2 3 4 5 6 7 8 9 10
703 >>>
704
705
706.. _ctypes-pointers:
707
708Pointers
709^^^^^^^^
710
Georg Brandl8d8f1972009-06-08 13:27:23 +0000711Pointer instances are created by calling the :func:`pointer` function on a
712:mod:`ctypes` type::
Georg Brandl116aa622007-08-15 14:28:22 +0000713
714 >>> from ctypes import *
715 >>> i = c_int(42)
716 >>> pi = pointer(i)
717 >>>
718
Georg Brandl1d837bc2009-12-29 11:24:00 +0000719Pointer instances have a :attr:`contents` attribute which returns the object to
Georg Brandl116aa622007-08-15 14:28:22 +0000720which the pointer points, the ``i`` object above::
721
722 >>> pi.contents
723 c_long(42)
724 >>>
725
Georg Brandl8d8f1972009-06-08 13:27:23 +0000726Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
Georg Brandl116aa622007-08-15 14:28:22 +0000727new, equivalent object each time you retrieve an attribute::
728
729 >>> pi.contents is i
730 False
731 >>> pi.contents is pi.contents
732 False
733 >>>
734
735Assigning another :class:`c_int` instance to the pointer's contents attribute
736would cause the pointer to point to the memory location where this is stored::
737
738 >>> i = c_int(99)
739 >>> pi.contents = i
740 >>> pi.contents
741 c_long(99)
742 >>>
743
Georg Brandl1d837bc2009-12-29 11:24:00 +0000744.. XXX Document dereferencing pointers, and that it is preferred over the
745 .contents attribute.
Thomas Heller2fadaa22008-06-16 19:56:33 +0000746
Georg Brandl116aa622007-08-15 14:28:22 +0000747Pointer instances can also be indexed with integers::
748
749 >>> pi[0]
750 99
751 >>>
752
753Assigning to an integer index changes the pointed to value::
754
Georg Brandl6911e3c2007-09-04 07:15:32 +0000755 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000756 c_long(99)
757 >>> pi[0] = 22
Georg Brandl6911e3c2007-09-04 07:15:32 +0000758 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000759 c_long(22)
760 >>>
761
762It is also possible to use indexes different from 0, but you must know what
763you're doing, just as in C: You can access or change arbitrary memory locations.
764Generally you only use this feature if you receive a pointer from a C function,
765and you *know* that the pointer actually points to an array instead of a single
766item.
767
Georg Brandl8d8f1972009-06-08 13:27:23 +0000768Behind the scenes, the :func:`pointer` function does more than simply create
769pointer instances, it has to create pointer *types* first. This is done with the
770:func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a
771new type::
Georg Brandl116aa622007-08-15 14:28:22 +0000772
773 >>> PI = POINTER(c_int)
774 >>> PI
775 <class 'ctypes.LP_c_long'>
776 >>> PI(42)
777 Traceback (most recent call last):
778 File "<stdin>", line 1, in ?
779 TypeError: expected c_long instead of int
780 >>> PI(c_int(42))
781 <ctypes.LP_c_long object at 0x...>
782 >>>
783
784Calling the pointer type without an argument creates a ``NULL`` pointer.
785``NULL`` pointers have a ``False`` boolean value::
786
787 >>> null_ptr = POINTER(c_int)()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000788 >>> print(bool(null_ptr))
Georg Brandl116aa622007-08-15 14:28:22 +0000789 False
790 >>>
791
Georg Brandl8d8f1972009-06-08 13:27:23 +0000792:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
Thomas Heller2fadaa22008-06-16 19:56:33 +0000793invalid non-\ ``NULL`` pointers would crash Python)::
Georg Brandl116aa622007-08-15 14:28:22 +0000794
795 >>> null_ptr[0]
796 Traceback (most recent call last):
797 ....
798 ValueError: NULL pointer access
799 >>>
800
801 >>> null_ptr[0] = 1234
802 Traceback (most recent call last):
803 ....
804 ValueError: NULL pointer access
805 >>>
806
807
808.. _ctypes-type-conversions:
809
810Type conversions
811^^^^^^^^^^^^^^^^
812
813Usually, ctypes does strict type checking. This means, if you have
814``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
815a member field in a structure definition, only instances of exactly the same
816type are accepted. There are some exceptions to this rule, where ctypes accepts
817other objects. For example, you can pass compatible array instances instead of
818pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
819
820 >>> class Bar(Structure):
821 ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
822 ...
823 >>> bar = Bar()
824 >>> bar.values = (c_int * 3)(1, 2, 3)
825 >>> bar.count = 3
826 >>> for i in range(bar.count):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000827 ... print(bar.values[i])
Georg Brandl116aa622007-08-15 14:28:22 +0000828 ...
829 1
830 2
831 3
832 >>>
833
Eli Benderskyf81de8d2013-03-08 05:31:54 -0800834In addition, if a function argument is explicitly declared to be a pointer type
835(such as ``POINTER(c_int)``) in :attr:`argtypes`, an object of the pointed
836type (``c_int`` in this case) can be passed to the function. ctypes will apply
837the required :func:`byref` conversion in this case automatically.
838
Georg Brandl116aa622007-08-15 14:28:22 +0000839To set a POINTER type field to ``NULL``, you can assign ``None``::
840
841 >>> bar.values = None
842 >>>
843
Thomas Heller2fadaa22008-06-16 19:56:33 +0000844.. XXX list other conversions...
Georg Brandl116aa622007-08-15 14:28:22 +0000845
Georg Brandl8d8f1972009-06-08 13:27:23 +0000846Sometimes you have instances of incompatible types. In C, you can cast one type
847into another type. :mod:`ctypes` provides a :func:`cast` function which can be
Georg Brandl116aa622007-08-15 14:28:22 +0000848used in the same way. The ``Bar`` structure defined above accepts
849``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
850but not instances of other types::
851
852 >>> bar.values = (c_byte * 4)()
853 Traceback (most recent call last):
854 File "<stdin>", line 1, in ?
855 TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
856 >>>
857
Georg Brandl8d8f1972009-06-08 13:27:23 +0000858For these cases, the :func:`cast` function is handy.
Georg Brandl116aa622007-08-15 14:28:22 +0000859
Georg Brandl8d8f1972009-06-08 13:27:23 +0000860The :func:`cast` function can be used to cast a ctypes instance into a pointer
861to a different ctypes data type. :func:`cast` takes two parameters, a ctypes
862object that is or can be converted to a pointer of some kind, and a ctypes
863pointer type. It returns an instance of the second argument, which references
864the same memory block as the first argument::
Georg Brandl116aa622007-08-15 14:28:22 +0000865
866 >>> a = (c_byte * 4)()
867 >>> cast(a, POINTER(c_int))
868 <ctypes.LP_c_long object at ...>
869 >>>
870
Georg Brandl8d8f1972009-06-08 13:27:23 +0000871So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the
Georg Brandl116aa622007-08-15 14:28:22 +0000872structure::
873
874 >>> bar = Bar()
875 >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
Georg Brandl6911e3c2007-09-04 07:15:32 +0000876 >>> print(bar.values[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000877 0
878 >>>
879
880
881.. _ctypes-incomplete-types:
882
883Incomplete Types
884^^^^^^^^^^^^^^^^
885
886*Incomplete Types* are structures, unions or arrays whose members are not yet
887specified. In C, they are specified by forward declarations, which are defined
888later::
889
890 struct cell; /* forward declaration */
891
Sandro Tosi692dba22011-08-02 16:17:14 +0200892 struct cell {
Georg Brandl116aa622007-08-15 14:28:22 +0000893 char *name;
894 struct cell *next;
Sandro Tosi692dba22011-08-02 16:17:14 +0200895 };
Georg Brandl116aa622007-08-15 14:28:22 +0000896
897The straightforward translation into ctypes code would be this, but it does not
898work::
899
900 >>> class cell(Structure):
901 ... _fields_ = [("name", c_char_p),
902 ... ("next", POINTER(cell))]
903 ...
904 Traceback (most recent call last):
905 File "<stdin>", line 1, in ?
906 File "<stdin>", line 2, in cell
907 NameError: name 'cell' is not defined
908 >>>
909
910because the new ``class cell`` is not available in the class statement itself.
Georg Brandl8d8f1972009-06-08 13:27:23 +0000911In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_`
Georg Brandl116aa622007-08-15 14:28:22 +0000912attribute later, after the class statement::
913
914 >>> from ctypes import *
915 >>> class cell(Structure):
916 ... pass
917 ...
918 >>> cell._fields_ = [("name", c_char_p),
919 ... ("next", POINTER(cell))]
920 >>>
921
922Lets try it. We create two instances of ``cell``, and let them point to each
923other, and finally follow the pointer chain a few times::
924
925 >>> c1 = cell()
926 >>> c1.name = "foo"
927 >>> c2 = cell()
928 >>> c2.name = "bar"
929 >>> c1.next = pointer(c2)
930 >>> c2.next = pointer(c1)
931 >>> p = c1
932 >>> for i in range(8):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000933 ... print(p.name, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000934 ... p = p.next[0]
935 ...
936 foo bar foo bar foo bar foo bar
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000937 >>>
Georg Brandl116aa622007-08-15 14:28:22 +0000938
939
940.. _ctypes-callback-functions:
941
942Callback functions
943^^^^^^^^^^^^^^^^^^
944
Georg Brandl8d8f1972009-06-08 13:27:23 +0000945:mod:`ctypes` allows to create C callable function pointers from Python callables.
Georg Brandl116aa622007-08-15 14:28:22 +0000946These are sometimes called *callback functions*.
947
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200948First, you must create a class for the callback function. The class knows the
Georg Brandl116aa622007-08-15 14:28:22 +0000949calling convention, the return type, and the number and types of arguments this
950function will receive.
951
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200952The :func:`CFUNCTYPE` factory function creates types for callback functions
953using the ``cdecl`` calling convention. On Windows, the :func:`WINFUNCTYPE`
954factory function creates types for callback functions using the ``stdcall``
955calling convention.
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957Both of these factory functions are called with the result type as first
958argument, and the callback functions expected argument types as the remaining
959arguments.
960
Georg Brandl8d8f1972009-06-08 13:27:23 +0000961I will present an example here which uses the standard C library's
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200962:c:func:`qsort` function, that is used to sort items with the help of a callback
Georg Brandl60203b42010-10-06 10:11:56 +0000963function. :c:func:`qsort` will be used to sort an array of integers::
Georg Brandl116aa622007-08-15 14:28:22 +0000964
965 >>> IntArray5 = c_int * 5
966 >>> ia = IntArray5(5, 1, 7, 33, 99)
967 >>> qsort = libc.qsort
968 >>> qsort.restype = None
969 >>>
970
971:func:`qsort` must be called with a pointer to the data to sort, the number of
972items in the data array, the size of one item, and a pointer to the comparison
973function, the callback. The callback will then be called with two pointers to
974items, and it must return a negative integer if the first item is smaller than
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200975the second, a zero if they are equal, and a positive integer otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +0000976
977So our callback function receives pointers to integers, and must return an
978integer. First we create the ``type`` for the callback function::
979
980 >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
981 >>>
982
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200983To get started, here is a simple callback that shows the values it gets
984passed::
Georg Brandl116aa622007-08-15 14:28:22 +0000985
986 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000987 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000988 ... return 0
989 ...
990 >>> cmp_func = CMPFUNC(py_cmp_func)
991 >>>
992
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200993The result::
Georg Brandl116aa622007-08-15 14:28:22 +0000994
995 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
996 py_cmp_func 5 1
997 py_cmp_func 33 99
998 py_cmp_func 7 33
999 py_cmp_func 5 7
1000 py_cmp_func 1 7
1001 >>>
1002
Eli Bendersky2a1e74a2012-03-16 09:17:43 +02001003Now we can actually compare the two items and return a useful result::
Georg Brandl116aa622007-08-15 14:28:22 +00001004
1005 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001006 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +00001007 ... return a[0] - b[0]
1008 ...
1009 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001010 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1011 py_cmp_func 5 1
1012 py_cmp_func 33 99
1013 py_cmp_func 7 33
1014 py_cmp_func 1 7
1015 py_cmp_func 5 7
1016 >>>
1017
Georg Brandl116aa622007-08-15 14:28:22 +00001018As we can easily check, our array is sorted now::
1019
Georg Brandl6911e3c2007-09-04 07:15:32 +00001020 >>> for i in ia: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +00001021 ...
1022 1 5 7 33 99
1023 >>>
1024
1025**Important note for callback functions:**
1026
Eli Bendersky2a1e74a2012-03-16 09:17:43 +02001027Make sure you keep references to :func:`CFUNCTYPE` objects as long as they are
1028used from C code. :mod:`ctypes` doesn't, and if you don't, they may be garbage
1029collected, crashing your program when a callback is made.
Georg Brandl116aa622007-08-15 14:28:22 +00001030
1031
1032.. _ctypes-accessing-values-exported-from-dlls:
1033
1034Accessing values exported from dlls
1035^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1036
Thomas Heller2fadaa22008-06-16 19:56:33 +00001037Some shared libraries not only export functions, they also export variables. An
Georg Brandl60203b42010-10-06 10:11:56 +00001038example in the Python library itself is the :c:data:`Py_OptimizeFlag`, an integer
Georg Brandl8d8f1972009-06-08 13:27:23 +00001039set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
Georg Brandl116aa622007-08-15 14:28:22 +00001040startup.
1041
Georg Brandl8d8f1972009-06-08 13:27:23 +00001042:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of
Georg Brandl116aa622007-08-15 14:28:22 +00001043the type. *pythonapi* is a predefined symbol giving access to the Python C
1044api::
1045
1046 >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
Georg Brandl6911e3c2007-09-04 07:15:32 +00001047 >>> print(opt_flag)
Georg Brandl116aa622007-08-15 14:28:22 +00001048 c_long(0)
1049 >>>
1050
1051If the interpreter would have been started with :option:`-O`, the sample would
1052have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1053specified.
1054
1055An extended example which also demonstrates the use of pointers accesses the
Georg Brandl60203b42010-10-06 10:11:56 +00001056:c:data:`PyImport_FrozenModules` pointer exported by Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001057
Georg Brandl8d8f1972009-06-08 13:27:23 +00001058Quoting the docs for that value:
1059
Georg Brandl60203b42010-10-06 10:11:56 +00001060 This pointer is initialized to point to an array of :c:type:`struct _frozen`
Georg Brandl8d8f1972009-06-08 13:27:23 +00001061 records, terminated by one whose members are all *NULL* or zero. When a frozen
1062 module is imported, it is searched in this table. Third-party code could play
1063 tricks with this to provide a dynamically created collection of frozen modules.
Georg Brandl116aa622007-08-15 14:28:22 +00001064
1065So manipulating this pointer could even prove useful. To restrict the example
Georg Brandl8d8f1972009-06-08 13:27:23 +00001066size, we show only how this table can be read with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001067
1068 >>> from ctypes import *
1069 >>>
1070 >>> class struct_frozen(Structure):
1071 ... _fields_ = [("name", c_char_p),
1072 ... ("code", POINTER(c_ubyte)),
1073 ... ("size", c_int)]
1074 ...
1075 >>>
1076
Georg Brandl60203b42010-10-06 10:11:56 +00001077We have defined the :c:type:`struct _frozen` data type, so we can get the pointer
Georg Brandl8d8f1972009-06-08 13:27:23 +00001078to the table::
Georg Brandl116aa622007-08-15 14:28:22 +00001079
1080 >>> FrozenTable = POINTER(struct_frozen)
1081 >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1082 >>>
1083
1084Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1085can iterate over it, but we just have to make sure that our loop terminates,
1086because pointers have no size. Sooner or later it would probably crash with an
1087access violation or whatever, so it's better to break out of the loop when we
1088hit the NULL entry::
1089
1090 >>> for item in table:
Georg Brandl6911e3c2007-09-04 07:15:32 +00001091 ... print(item.name, item.size)
Georg Brandl116aa622007-08-15 14:28:22 +00001092 ... if item.name is None:
1093 ... break
1094 ...
1095 __hello__ 104
1096 __phello__ -104
1097 __phello__.spam 104
1098 None 0
1099 >>>
1100
1101The fact that standard Python has a frozen module and a frozen package
Thomas Woutersed03b412007-08-28 21:37:11 +00001102(indicated by the negative size member) is not well known, it is only used for
Georg Brandl116aa622007-08-15 14:28:22 +00001103testing. Try it out with ``import __hello__`` for example.
1104
1105
1106.. _ctypes-surprises:
1107
1108Surprises
1109^^^^^^^^^
1110
R David Murraya2959ce2012-10-31 10:50:27 -04001111There are some edges in :mod:`ctypes` where you might expect something other
1112than what actually happens.
Georg Brandl116aa622007-08-15 14:28:22 +00001113
1114Consider the following example::
1115
1116 >>> from ctypes import *
1117 >>> class POINT(Structure):
1118 ... _fields_ = ("x", c_int), ("y", c_int)
1119 ...
1120 >>> class RECT(Structure):
1121 ... _fields_ = ("a", POINT), ("b", POINT)
1122 ...
1123 >>> p1 = POINT(1, 2)
1124 >>> p2 = POINT(3, 4)
1125 >>> rc = RECT(p1, p2)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001126 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001127 1 2 3 4
1128 >>> # now swap the two points
1129 >>> rc.a, rc.b = rc.b, rc.a
Georg Brandl6911e3c2007-09-04 07:15:32 +00001130 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001131 3 4 3 4
1132 >>>
1133
1134Hm. We certainly expected the last statement to print ``3 4 1 2``. What
Thomas Woutersed03b412007-08-28 21:37:11 +00001135happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137 >>> temp0, temp1 = rc.b, rc.a
1138 >>> rc.a = temp0
1139 >>> rc.b = temp1
1140 >>>
1141
1142Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1143the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1144contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1145contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1146the expected effect.
1147
Thomas Woutersed03b412007-08-28 21:37:11 +00001148Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1149doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
Georg Brandl116aa622007-08-15 14:28:22 +00001150the root-object's underlying buffer.
1151
1152Another example that may behave different from what one would expect is this::
1153
1154 >>> s = c_char_p()
1155 >>> s.value = "abc def ghi"
1156 >>> s.value
1157 'abc def ghi'
1158 >>> s.value is s.value
1159 False
1160 >>>
1161
1162Why is it printing ``False``? ctypes instances are objects containing a memory
Georg Brandl9afde1c2007-11-01 20:32:30 +00001163block plus some :term:`descriptor`\s accessing the contents of the memory.
1164Storing a Python object in the memory block does not store the object itself,
1165instead the ``contents`` of the object is stored. Accessing the contents again
1166constructs a new Python object each time!
Georg Brandl116aa622007-08-15 14:28:22 +00001167
1168
1169.. _ctypes-variable-sized-data-types:
1170
1171Variable-sized data types
1172^^^^^^^^^^^^^^^^^^^^^^^^^
1173
Georg Brandl8d8f1972009-06-08 13:27:23 +00001174:mod:`ctypes` provides some support for variable-sized arrays and structures.
Georg Brandl116aa622007-08-15 14:28:22 +00001175
Georg Brandl8d8f1972009-06-08 13:27:23 +00001176The :func:`resize` function can be used to resize the memory buffer of an
1177existing ctypes object. The function takes the object as first argument, and
1178the requested size in bytes as the second argument. The memory block cannot be
1179made smaller than the natural memory block specified by the objects type, a
1180:exc:`ValueError` is raised if this is tried::
Georg Brandl116aa622007-08-15 14:28:22 +00001181
1182 >>> short_array = (c_short * 4)()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001183 >>> print(sizeof(short_array))
Georg Brandl116aa622007-08-15 14:28:22 +00001184 8
1185 >>> resize(short_array, 4)
1186 Traceback (most recent call last):
1187 ...
1188 ValueError: minimum size is 8
1189 >>> resize(short_array, 32)
1190 >>> sizeof(short_array)
1191 32
1192 >>> sizeof(type(short_array))
1193 8
1194 >>>
1195
1196This is nice and fine, but how would one access the additional elements
1197contained in this array? Since the type still only knows about 4 elements, we
1198get errors accessing other elements::
1199
1200 >>> short_array[:]
1201 [0, 0, 0, 0]
1202 >>> short_array[7]
1203 Traceback (most recent call last):
1204 ...
1205 IndexError: invalid index
1206 >>>
1207
Georg Brandl8d8f1972009-06-08 13:27:23 +00001208Another way to use variable-sized data types with :mod:`ctypes` is to use the
Georg Brandl116aa622007-08-15 14:28:22 +00001209dynamic nature of Python, and (re-)define the data type after the required size
1210is already known, on a case by case basis.
1211
1212
Georg Brandl116aa622007-08-15 14:28:22 +00001213.. _ctypes-ctypes-reference:
1214
1215ctypes reference
1216----------------
1217
1218
1219.. _ctypes-finding-shared-libraries:
1220
1221Finding shared libraries
1222^^^^^^^^^^^^^^^^^^^^^^^^
1223
1224When programming in a compiled language, shared libraries are accessed when
1225compiling/linking a program, and when the program is run.
1226
Georg Brandl8d8f1972009-06-08 13:27:23 +00001227The purpose of the :func:`find_library` function is to locate a library in a way
Georg Brandl116aa622007-08-15 14:28:22 +00001228similar to what the compiler does (on platforms with several versions of a
1229shared library the most recent should be loaded), while the ctypes library
1230loaders act like when a program is run, and call the runtime loader directly.
1231
Georg Brandl8d8f1972009-06-08 13:27:23 +00001232The :mod:`ctypes.util` module provides a function which can help to determine
1233the library to load.
Georg Brandl116aa622007-08-15 14:28:22 +00001234
1235
1236.. data:: find_library(name)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001237 :module: ctypes.util
Georg Brandl116aa622007-08-15 14:28:22 +00001238 :noindex:
1239
1240 Try to find a library and return a pathname. *name* is the library name without
1241 any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1242 is the form used for the posix linker option :option:`-l`). If no library can
1243 be found, returns ``None``.
1244
Thomas Woutersed03b412007-08-28 21:37:11 +00001245The exact functionality is system dependent.
Georg Brandl116aa622007-08-15 14:28:22 +00001246
Georg Brandl1d837bc2009-12-29 11:24:00 +00001247On Linux, :func:`find_library` tries to run external programs
1248(``/sbin/ldconfig``, ``gcc``, and ``objdump``) to find the library file. It
1249returns the filename of the library file. Here are some examples::
Georg Brandl116aa622007-08-15 14:28:22 +00001250
1251 >>> from ctypes.util import find_library
1252 >>> find_library("m")
1253 'libm.so.6'
1254 >>> find_library("c")
1255 'libc.so.6'
1256 >>> find_library("bz2")
1257 'libbz2.so.1.0'
1258 >>>
1259
Georg Brandl8d8f1972009-06-08 13:27:23 +00001260On OS X, :func:`find_library` tries several predefined naming schemes and paths
1261to locate the library, and returns a full pathname if successful::
Georg Brandl116aa622007-08-15 14:28:22 +00001262
1263 >>> from ctypes.util import find_library
1264 >>> find_library("c")
1265 '/usr/lib/libc.dylib'
1266 >>> find_library("m")
1267 '/usr/lib/libm.dylib'
1268 >>> find_library("bz2")
1269 '/usr/lib/libbz2.dylib'
1270 >>> find_library("AGL")
1271 '/System/Library/Frameworks/AGL.framework/AGL'
1272 >>>
1273
Georg Brandl8d8f1972009-06-08 13:27:23 +00001274On Windows, :func:`find_library` searches along the system search path, and
1275returns the full pathname, but since there is no predefined naming scheme a call
1276like ``find_library("c")`` will fail and return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001277
Georg Brandl8d8f1972009-06-08 13:27:23 +00001278If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
Ned Deilyea3cfc52013-05-20 14:29:44 -07001279the shared library name at development time, and hardcode that into the wrapper
Georg Brandl8d8f1972009-06-08 13:27:23 +00001280module instead of using :func:`find_library` to locate the library at runtime.
Georg Brandl116aa622007-08-15 14:28:22 +00001281
1282
1283.. _ctypes-loading-shared-libraries:
1284
1285Loading shared libraries
1286^^^^^^^^^^^^^^^^^^^^^^^^
1287
1288There are several ways to loaded shared libraries into the Python process. One
1289way is to instantiate one of the following classes:
1290
1291
Thomas Hellerb795f5282008-06-10 15:26:58 +00001292.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001293
1294 Instances of this class represent loaded shared libraries. Functions in these
1295 libraries use the standard C calling convention, and are assumed to return
Georg Brandl60203b42010-10-06 10:11:56 +00001296 :c:type:`int`.
Georg Brandl116aa622007-08-15 14:28:22 +00001297
1298
Thomas Hellerb795f5282008-06-10 15:26:58 +00001299.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001300
1301 Windows only: Instances of this class represent loaded shared libraries,
1302 functions in these libraries use the ``stdcall`` calling convention, and are
1303 assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1304 values contain information specifying whether the function call failed or
1305 succeeded, together with additional error code. If the return value signals a
Antoine Pitrou442ee032011-10-12 18:53:23 +02001306 failure, an :class:`OSError` is automatically raised.
1307
1308 .. versionchanged:: 3.3
1309 :exc:`WindowsError` used to be raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001310
1311
Thomas Hellerb795f5282008-06-10 15:26:58 +00001312.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001313
1314 Windows only: Instances of this class represent loaded shared libraries,
1315 functions in these libraries use the ``stdcall`` calling convention, and are
Georg Brandl60203b42010-10-06 10:11:56 +00001316 assumed to return :c:type:`int` by default.
Georg Brandl116aa622007-08-15 14:28:22 +00001317
1318 On Windows CE only the standard calling convention is used, for convenience the
1319 :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1320 platform.
1321
Georg Brandl9afde1c2007-11-01 20:32:30 +00001322The Python :term:`global interpreter lock` is released before calling any
1323function exported by these libraries, and reacquired afterwards.
Georg Brandl116aa622007-08-15 14:28:22 +00001324
1325
1326.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1327
1328 Instances of this class behave like :class:`CDLL` instances, except that the
1329 Python GIL is *not* released during the function call, and after the function
1330 execution the Python error flag is checked. If the error flag is set, a Python
1331 exception is raised.
1332
1333 Thus, this is only useful to call Python C api functions directly.
1334
1335All these classes can be instantiated by calling them with at least one
1336argument, the pathname of the shared library. If you have an existing handle to
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001337an already loaded shared library, it can be passed as the ``handle`` named
Georg Brandl1d837bc2009-12-29 11:24:00 +00001338parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary``
Georg Brandl116aa622007-08-15 14:28:22 +00001339function is used to load the library into the process, and to get a handle to
1340it.
1341
1342The *mode* parameter can be used to specify how the library is loaded. For
Georg Brandl1d837bc2009-12-29 11:24:00 +00001343details, consult the :manpage:`dlopen(3)` manpage, on Windows, *mode* is
1344ignored.
Georg Brandl116aa622007-08-15 14:28:22 +00001345
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001346The *use_errno* parameter, when set to True, enables a ctypes mechanism that
1347allows to access the system :data:`errno` error number in a safe way.
1348:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1349variable; if you call foreign functions created with ``use_errno=True`` then the
1350:data:`errno` value before the function call is swapped with the ctypes private
1351copy, the same happens immediately after the function call.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001352
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001353The function :func:`ctypes.get_errno` returns the value of the ctypes private
1354copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1355to a new value and returns the former value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001356
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001357The *use_last_error* parameter, when set to True, enables the same mechanism for
1358the Windows error code which is managed by the :func:`GetLastError` and
1359:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1360:func:`ctypes.set_last_error` are used to request and change the ctypes private
1361copy of the windows error code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001362
Georg Brandl116aa622007-08-15 14:28:22 +00001363.. data:: RTLD_GLOBAL
1364 :noindex:
1365
1366 Flag to use as *mode* parameter. On platforms where this flag is not available,
1367 it is defined as the integer zero.
1368
1369
1370.. data:: RTLD_LOCAL
1371 :noindex:
1372
1373 Flag to use as *mode* parameter. On platforms where this is not available, it
1374 is the same as *RTLD_GLOBAL*.
1375
1376
1377.. data:: DEFAULT_MODE
1378 :noindex:
1379
1380 The default mode which is used to load shared libraries. On OSX 10.3, this is
1381 *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1382
1383Instances of these classes have no public methods, however :meth:`__getattr__`
Thomas Woutersed03b412007-08-28 21:37:11 +00001384and :meth:`__getitem__` have special behavior: functions exported by the shared
Georg Brandl116aa622007-08-15 14:28:22 +00001385library can be accessed as attributes of by index. Please note that both
1386:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1387repeatedly returns the same object each time.
1388
1389The following public attributes are available, their name starts with an
1390underscore to not clash with exported function names:
1391
1392
1393.. attribute:: PyDLL._handle
1394
1395 The system handle used to access the library.
1396
1397
1398.. attribute:: PyDLL._name
1399
Thomas Woutersed03b412007-08-28 21:37:11 +00001400 The name of the library passed in the constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001401
1402Shared libraries can also be loaded by using one of the prefabricated objects,
1403which are instances of the :class:`LibraryLoader` class, either by calling the
1404:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1405loader instance.
1406
1407
1408.. class:: LibraryLoader(dlltype)
1409
Georg Brandl1d837bc2009-12-29 11:24:00 +00001410 Class which loads shared libraries. *dlltype* should be one of the
Georg Brandl116aa622007-08-15 14:28:22 +00001411 :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1412
Thomas Woutersed03b412007-08-28 21:37:11 +00001413 :meth:`__getattr__` has special behavior: It allows to load a shared library by
Georg Brandl116aa622007-08-15 14:28:22 +00001414 accessing it as attribute of a library loader instance. The result is cached,
1415 so repeated attribute accesses return the same library each time.
1416
Benjamin Petersone41251e2008-04-25 01:59:09 +00001417 .. method:: LoadLibrary(name)
Georg Brandl116aa622007-08-15 14:28:22 +00001418
Benjamin Petersone41251e2008-04-25 01:59:09 +00001419 Load a shared library into the process and return it. This method always
1420 returns a new instance of the library.
Georg Brandl116aa622007-08-15 14:28:22 +00001421
Georg Brandl116aa622007-08-15 14:28:22 +00001422
Georg Brandl8d8f1972009-06-08 13:27:23 +00001423These prefabricated library loaders are available:
Georg Brandl116aa622007-08-15 14:28:22 +00001424
1425.. data:: cdll
1426 :noindex:
1427
1428 Creates :class:`CDLL` instances.
1429
1430
1431.. data:: windll
1432 :noindex:
1433
1434 Windows only: Creates :class:`WinDLL` instances.
1435
1436
1437.. data:: oledll
1438 :noindex:
1439
1440 Windows only: Creates :class:`OleDLL` instances.
1441
1442
1443.. data:: pydll
1444 :noindex:
1445
1446 Creates :class:`PyDLL` instances.
1447
Georg Brandl8d8f1972009-06-08 13:27:23 +00001448
Georg Brandl116aa622007-08-15 14:28:22 +00001449For accessing the C Python api directly, a ready-to-use Python shared library
1450object is available:
1451
Georg Brandl116aa622007-08-15 14:28:22 +00001452.. data:: pythonapi
1453 :noindex:
1454
Georg Brandl1d837bc2009-12-29 11:24:00 +00001455 An instance of :class:`PyDLL` that exposes Python C API functions as
1456 attributes. Note that all these functions are assumed to return C
Georg Brandl60203b42010-10-06 10:11:56 +00001457 :c:type:`int`, which is of course not always the truth, so you have to assign
Georg Brandl1d837bc2009-12-29 11:24:00 +00001458 the correct :attr:`restype` attribute to use these functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001459
1460
1461.. _ctypes-foreign-functions:
1462
1463Foreign functions
1464^^^^^^^^^^^^^^^^^
1465
1466As explained in the previous section, foreign functions can be accessed as
1467attributes of loaded shared libraries. The function objects created in this way
1468by default accept any number of arguments, accept any ctypes data instances as
1469arguments, and return the default result type specified by the library loader.
1470They are instances of a private class:
1471
1472
1473.. class:: _FuncPtr
1474
1475 Base class for C callable foreign functions.
1476
Benjamin Petersone41251e2008-04-25 01:59:09 +00001477 Instances of foreign functions are also C compatible data types; they
1478 represent C function pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001479
Benjamin Petersone41251e2008-04-25 01:59:09 +00001480 This behavior can be customized by assigning to special attributes of the
1481 foreign function object.
Georg Brandl116aa622007-08-15 14:28:22 +00001482
Benjamin Petersone41251e2008-04-25 01:59:09 +00001483 .. attribute:: restype
Georg Brandl116aa622007-08-15 14:28:22 +00001484
Benjamin Petersone41251e2008-04-25 01:59:09 +00001485 Assign a ctypes type to specify the result type of the foreign function.
Georg Brandl60203b42010-10-06 10:11:56 +00001486 Use ``None`` for :c:type:`void`, a function not returning anything.
Georg Brandl116aa622007-08-15 14:28:22 +00001487
Benjamin Petersone41251e2008-04-25 01:59:09 +00001488 It is possible to assign a callable Python object that is not a ctypes
Georg Brandl60203b42010-10-06 10:11:56 +00001489 type, in this case the function is assumed to return a C :c:type:`int`, and
Georg Brandl1d837bc2009-12-29 11:24:00 +00001490 the callable will be called with this integer, allowing to do further
Benjamin Petersone41251e2008-04-25 01:59:09 +00001491 processing or error checking. Using this is deprecated, for more flexible
1492 post processing or error checking use a ctypes data type as
1493 :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001494
Benjamin Petersone41251e2008-04-25 01:59:09 +00001495 .. attribute:: argtypes
Georg Brandl116aa622007-08-15 14:28:22 +00001496
Benjamin Petersone41251e2008-04-25 01:59:09 +00001497 Assign a tuple of ctypes types to specify the argument types that the
1498 function accepts. Functions using the ``stdcall`` calling convention can
1499 only be called with the same number of arguments as the length of this
1500 tuple; functions using the C calling convention accept additional,
1501 unspecified arguments as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001502
Benjamin Petersone41251e2008-04-25 01:59:09 +00001503 When a foreign function is called, each actual argument is passed to the
1504 :meth:`from_param` class method of the items in the :attr:`argtypes`
1505 tuple, this method allows to adapt the actual argument to an object that
1506 the foreign function accepts. For example, a :class:`c_char_p` item in
Georg Brandl8d8f1972009-06-08 13:27:23 +00001507 the :attr:`argtypes` tuple will convert a string passed as argument into
1508 a bytes object using ctypes conversion rules.
Georg Brandl116aa622007-08-15 14:28:22 +00001509
Benjamin Petersone41251e2008-04-25 01:59:09 +00001510 New: It is now possible to put items in argtypes which are not ctypes
1511 types, but each item must have a :meth:`from_param` method which returns a
1512 value usable as argument (integer, string, ctypes instance). This allows
1513 to define adapters that can adapt custom objects as function parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001514
Benjamin Petersone41251e2008-04-25 01:59:09 +00001515 .. attribute:: errcheck
Georg Brandl116aa622007-08-15 14:28:22 +00001516
Benjamin Petersone41251e2008-04-25 01:59:09 +00001517 Assign a Python function or another callable to this attribute. The
1518 callable will be called with three or more arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001519
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001520 .. function:: callable(result, func, arguments)
1521 :noindex:
Georg Brandl8d8f1972009-06-08 13:27:23 +00001522 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001523
Georg Brandl1d837bc2009-12-29 11:24:00 +00001524 *result* is what the foreign function returns, as specified by the
1525 :attr:`restype` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001526
Georg Brandl1d837bc2009-12-29 11:24:00 +00001527 *func* is the foreign function object itself, this allows to reuse the
1528 same callable object to check or post process the results of several
1529 functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001530
Georg Brandl1d837bc2009-12-29 11:24:00 +00001531 *arguments* is a tuple containing the parameters originally passed to
1532 the function call, this allows to specialize the behavior on the
1533 arguments used.
Georg Brandl116aa622007-08-15 14:28:22 +00001534
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001535 The object that this function returns will be returned from the
1536 foreign function call, but it can also check the result value
1537 and raise an exception if the foreign function call failed.
Georg Brandl116aa622007-08-15 14:28:22 +00001538
1539
Georg Brandl8d8f1972009-06-08 13:27:23 +00001540.. exception:: ArgumentError
Georg Brandl116aa622007-08-15 14:28:22 +00001541
1542 This exception is raised when a foreign function call cannot convert one of the
1543 passed arguments.
1544
1545
1546.. _ctypes-function-prototypes:
1547
1548Function prototypes
1549^^^^^^^^^^^^^^^^^^^
1550
1551Foreign functions can also be created by instantiating function prototypes.
1552Function prototypes are similar to function prototypes in C; they describe a
1553function (return type, argument types, calling convention) without defining an
1554implementation. The factory functions must be called with the desired result
1555type and the argument types of the function.
1556
1557
Thomas Hellerb795f5282008-06-10 15:26:58 +00001558.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001559
1560 The returned function prototype creates functions that use the standard C
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001561 calling convention. The function will release the GIL during the call. If
1562 *use_errno* is set to True, the ctypes private copy of the system
Georg Brandla6053b42009-09-01 08:11:14 +00001563 :data:`errno` variable is exchanged with the real :data:`errno` value before
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001564 and after the call; *use_last_error* does the same for the Windows error
1565 code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001566
Georg Brandl116aa622007-08-15 14:28:22 +00001567
Thomas Hellerb795f5282008-06-10 15:26:58 +00001568.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001569
1570 Windows only: The returned function prototype creates functions that use the
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001571 ``stdcall`` calling convention, except on Windows CE where
1572 :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
1573 release the GIL during the call. *use_errno* and *use_last_error* have the
1574 same meaning as above.
Georg Brandl116aa622007-08-15 14:28:22 +00001575
1576
1577.. function:: PYFUNCTYPE(restype, *argtypes)
1578
1579 The returned function prototype creates functions that use the Python calling
1580 convention. The function will *not* release the GIL during the call.
1581
Thomas Heller2fadaa22008-06-16 19:56:33 +00001582Function prototypes created by these factory functions can be instantiated in
1583different ways, depending on the type and number of the parameters in the call:
Georg Brandl116aa622007-08-15 14:28:22 +00001584
1585
Thomas Heller2fadaa22008-06-16 19:56:33 +00001586 .. function:: prototype(address)
1587 :noindex:
1588 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001589
Thomas Heller2fadaa22008-06-16 19:56:33 +00001590 Returns a foreign function at the specified address which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00001591
1592
Thomas Heller2fadaa22008-06-16 19:56:33 +00001593 .. function:: prototype(callable)
1594 :noindex:
1595 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001596
Georg Brandl8d8f1972009-06-08 13:27:23 +00001597 Create a C callable function (a callback function) from a Python *callable*.
Georg Brandl116aa622007-08-15 14:28:22 +00001598
1599
Thomas Heller2fadaa22008-06-16 19:56:33 +00001600 .. function:: prototype(func_spec[, paramflags])
1601 :noindex:
1602 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001603
Georg Brandl1d837bc2009-12-29 11:24:00 +00001604 Returns a foreign function exported by a shared library. *func_spec* must
1605 be a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of
1606 the exported function as string, or the ordinal of the exported function
1607 as small integer. The second item is the shared library instance.
Georg Brandl116aa622007-08-15 14:28:22 +00001608
1609
Thomas Heller2fadaa22008-06-16 19:56:33 +00001610 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1611 :noindex:
1612 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001613
Georg Brandl8d8f1972009-06-08 13:27:23 +00001614 Returns a foreign function that will call a COM method. *vtbl_index* is
1615 the index into the virtual function table, a small non-negative
1616 integer. *name* is name of the COM method. *iid* is an optional pointer to
1617 the interface identifier which is used in extended error reporting.
Georg Brandl116aa622007-08-15 14:28:22 +00001618
Georg Brandl8d8f1972009-06-08 13:27:23 +00001619 COM methods use a special calling convention: They require a pointer to
1620 the COM interface as first argument, in addition to those parameters that
1621 are specified in the :attr:`argtypes` tuple.
Georg Brandl116aa622007-08-15 14:28:22 +00001622
Thomas Heller2fadaa22008-06-16 19:56:33 +00001623 The optional *paramflags* parameter creates foreign function wrappers with much
1624 more functionality than the features described above.
Georg Brandl116aa622007-08-15 14:28:22 +00001625
Thomas Heller2fadaa22008-06-16 19:56:33 +00001626 *paramflags* must be a tuple of the same length as :attr:`argtypes`.
Georg Brandl116aa622007-08-15 14:28:22 +00001627
Thomas Heller2fadaa22008-06-16 19:56:33 +00001628 Each item in this tuple contains further information about a parameter, it must
1629 be a tuple containing one, two, or three items.
Georg Brandl116aa622007-08-15 14:28:22 +00001630
Thomas Heller2fadaa22008-06-16 19:56:33 +00001631 The first item is an integer containing a combination of direction
1632 flags for the parameter:
Georg Brandl116aa622007-08-15 14:28:22 +00001633
Thomas Heller2fadaa22008-06-16 19:56:33 +00001634 1
1635 Specifies an input parameter to the function.
Georg Brandl116aa622007-08-15 14:28:22 +00001636
Thomas Heller2fadaa22008-06-16 19:56:33 +00001637 2
1638 Output parameter. The foreign function fills in a value.
Georg Brandl116aa622007-08-15 14:28:22 +00001639
Thomas Heller2fadaa22008-06-16 19:56:33 +00001640 4
1641 Input parameter which defaults to the integer zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001642
Thomas Heller2fadaa22008-06-16 19:56:33 +00001643 The optional second item is the parameter name as string. If this is specified,
1644 the foreign function can be called with named parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001645
Thomas Heller2fadaa22008-06-16 19:56:33 +00001646 The optional third item is the default value for this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001647
1648This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
1649that it supports default parameters and named arguments. The C declaration from
1650the windows header file is this::
1651
1652 WINUSERAPI int WINAPI
1653 MessageBoxA(
1654 HWND hWnd ,
1655 LPCSTR lpText,
1656 LPCSTR lpCaption,
1657 UINT uType);
1658
Georg Brandl8d8f1972009-06-08 13:27:23 +00001659Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001660
Thomas Heller2fadaa22008-06-16 19:56:33 +00001661 >>> from ctypes import c_int, WINFUNCTYPE, windll
1662 >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1663 >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
1664 >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1665 >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1666 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001667
1668The MessageBox foreign function can now be called in these ways::
1669
1670 >>> MessageBox()
1671 >>> MessageBox(text="Spam, spam, spam")
1672 >>> MessageBox(flags=2, text="foo bar")
1673 >>>
1674
1675A second example demonstrates output parameters. The win32 ``GetWindowRect``
1676function retrieves the dimensions of a specified window by copying them into
1677``RECT`` structure that the caller has to supply. Here is the C declaration::
1678
1679 WINUSERAPI BOOL WINAPI
1680 GetWindowRect(
1681 HWND hWnd,
1682 LPRECT lpRect);
1683
Georg Brandl8d8f1972009-06-08 13:27:23 +00001684Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001685
Thomas Heller2fadaa22008-06-16 19:56:33 +00001686 >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1687 >>> from ctypes.wintypes import BOOL, HWND, RECT
1688 >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1689 >>> paramflags = (1, "hwnd"), (2, "lprect")
1690 >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1691 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001692
1693Functions with output parameters will automatically return the output parameter
1694value if there is a single one, or a tuple containing the output parameter
1695values when there are more than one, so the GetWindowRect function now returns a
1696RECT instance, when called.
1697
1698Output parameters can be combined with the :attr:`errcheck` protocol to do
1699further output processing and error checking. The win32 ``GetWindowRect`` api
1700function returns a ``BOOL`` to signal success or failure, so this function could
1701do the error checking, and raises an exception when the api call failed::
1702
1703 >>> def errcheck(result, func, args):
1704 ... if not result:
1705 ... raise WinError()
1706 ... return args
Thomas Heller2fadaa22008-06-16 19:56:33 +00001707 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001708 >>> GetWindowRect.errcheck = errcheck
1709 >>>
1710
1711If the :attr:`errcheck` function returns the argument tuple it receives
Georg Brandl8d8f1972009-06-08 13:27:23 +00001712unchanged, :mod:`ctypes` continues the normal processing it does on the output
Georg Brandl116aa622007-08-15 14:28:22 +00001713parameters. If you want to return a tuple of window coordinates instead of a
1714``RECT`` instance, you can retrieve the fields in the function and return them
1715instead, the normal processing will no longer take place::
1716
1717 >>> def errcheck(result, func, args):
1718 ... if not result:
1719 ... raise WinError()
1720 ... rc = args[1]
1721 ... return rc.left, rc.top, rc.bottom, rc.right
Thomas Heller2fadaa22008-06-16 19:56:33 +00001722 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001723 >>> GetWindowRect.errcheck = errcheck
1724 >>>
1725
1726
1727.. _ctypes-utility-functions:
1728
1729Utility functions
1730^^^^^^^^^^^^^^^^^
1731
Georg Brandl116aa622007-08-15 14:28:22 +00001732.. function:: addressof(obj)
1733
Georg Brandl8d8f1972009-06-08 13:27:23 +00001734 Returns the address of the memory buffer as integer. *obj* must be an
Georg Brandl116aa622007-08-15 14:28:22 +00001735 instance of a ctypes type.
1736
1737
1738.. function:: alignment(obj_or_type)
1739
Georg Brandl8d8f1972009-06-08 13:27:23 +00001740 Returns the alignment requirements of a ctypes type. *obj_or_type* must be a
Georg Brandl116aa622007-08-15 14:28:22 +00001741 ctypes type or instance.
1742
1743
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001744.. function:: byref(obj[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +00001745
Georg Brandl1d837bc2009-12-29 11:24:00 +00001746 Returns a light-weight pointer to *obj*, which must be an instance of a
1747 ctypes type. *offset* defaults to zero, and must be an integer that will be
1748 added to the internal pointer value.
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001749
1750 ``byref(obj, offset)`` corresponds to this C code::
1751
1752 (((char *)&obj) + offset)
1753
Georg Brandl1d837bc2009-12-29 11:24:00 +00001754 The returned object can only be used as a foreign function call parameter.
1755 It behaves similar to ``pointer(obj)``, but the construction is a lot faster.
Georg Brandl116aa622007-08-15 14:28:22 +00001756
1757
1758.. function:: cast(obj, type)
1759
Georg Brandl8d8f1972009-06-08 13:27:23 +00001760 This function is similar to the cast operator in C. It returns a new instance
Georg Brandl1d837bc2009-12-29 11:24:00 +00001761 of *type* which points to the same memory block as *obj*. *type* must be a
Georg Brandl8d8f1972009-06-08 13:27:23 +00001762 pointer type, and *obj* must be an object that can be interpreted as a
Georg Brandl116aa622007-08-15 14:28:22 +00001763 pointer.
1764
1765
Georg Brandl8d8f1972009-06-08 13:27:23 +00001766.. function:: create_string_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001767
1768 This function creates a mutable character buffer. The returned object is a
1769 ctypes array of :class:`c_char`.
1770
Georg Brandl8d8f1972009-06-08 13:27:23 +00001771 *init_or_size* must be an integer which specifies the size of the array, or a
1772 bytes object which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001773
Georg Brandl8d8f1972009-06-08 13:27:23 +00001774 If a bytes object is specified as first argument, the buffer is made one item
1775 larger than its length so that the last element in the array is a NUL
Georg Brandl116aa622007-08-15 14:28:22 +00001776 termination character. An integer can be passed as second argument which allows
Georg Brandl8d8f1972009-06-08 13:27:23 +00001777 to specify the size of the array if the length of the bytes should not be used.
Georg Brandl116aa622007-08-15 14:28:22 +00001778
Georg Brandl116aa622007-08-15 14:28:22 +00001779
1780
Georg Brandl8d8f1972009-06-08 13:27:23 +00001781.. function:: create_unicode_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001782
1783 This function creates a mutable unicode character buffer. The returned object is
1784 a ctypes array of :class:`c_wchar`.
1785
Georg Brandl8d8f1972009-06-08 13:27:23 +00001786 *init_or_size* must be an integer which specifies the size of the array, or a
1787 string which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001788
Georg Brandl8d8f1972009-06-08 13:27:23 +00001789 If a string is specified as first argument, the buffer is made one item
Georg Brandl116aa622007-08-15 14:28:22 +00001790 larger than the length of the string so that the last element in the array is a
1791 NUL termination character. An integer can be passed as second argument which
1792 allows to specify the size of the array if the length of the string should not
1793 be used.
1794
Georg Brandl116aa622007-08-15 14:28:22 +00001795
1796
1797.. function:: DllCanUnloadNow()
1798
Georg Brandl1d837bc2009-12-29 11:24:00 +00001799 Windows only: This function is a hook which allows to implement in-process
1800 COM servers with ctypes. It is called from the DllCanUnloadNow function that
1801 the _ctypes extension dll exports.
Georg Brandl116aa622007-08-15 14:28:22 +00001802
1803
1804.. function:: DllGetClassObject()
1805
Georg Brandl1d837bc2009-12-29 11:24:00 +00001806 Windows only: This function is a hook which allows to implement in-process
1807 COM servers with ctypes. It is called from the DllGetClassObject function
1808 that the ``_ctypes`` extension dll exports.
1809
Georg Brandl116aa622007-08-15 14:28:22 +00001810
Thomas Heller2fadaa22008-06-16 19:56:33 +00001811.. function:: find_library(name)
1812 :module: ctypes.util
1813
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001814 Try to find a library and return a pathname. *name* is the library name
Benjamin Peterson28d88b42009-01-09 03:03:23 +00001815 without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001816 number (this is the form used for the posix linker option :option:`-l`). If
1817 no library can be found, returns ``None``.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001818
1819 The exact functionality is system dependent.
1820
Thomas Heller2fadaa22008-06-16 19:56:33 +00001821
1822.. function:: find_msvcrt()
1823 :module: ctypes.util
1824
Georg Brandl1d837bc2009-12-29 11:24:00 +00001825 Windows only: return the filename of the VC runtype library used by Python,
1826 and by the extension modules. If the name of the library cannot be
1827 determined, ``None`` is returned.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001828
Georg Brandl1d837bc2009-12-29 11:24:00 +00001829 If you need to free memory, for example, allocated by an extension module
1830 with a call to the ``free(void *)``, it is important that you use the
1831 function in the same library that allocated the memory.
1832
Thomas Heller2fadaa22008-06-16 19:56:33 +00001833
Georg Brandl116aa622007-08-15 14:28:22 +00001834.. function:: FormatError([code])
1835
Georg Brandl1d837bc2009-12-29 11:24:00 +00001836 Windows only: Returns a textual description of the error code *code*. If no
1837 error code is specified, the last error code is used by calling the Windows
1838 api function GetLastError.
Georg Brandl116aa622007-08-15 14:28:22 +00001839
1840
1841.. function:: GetLastError()
1842
1843 Windows only: Returns the last error code set by Windows in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001844 This function calls the Windows `GetLastError()` function directly,
1845 it does not return the ctypes-private copy of the error code.
Georg Brandl116aa622007-08-15 14:28:22 +00001846
Thomas Hellerb795f5282008-06-10 15:26:58 +00001847.. function:: get_errno()
1848
1849 Returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001850 :data:`errno` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001851
Thomas Hellerb795f5282008-06-10 15:26:58 +00001852.. function:: get_last_error()
1853
1854 Windows only: returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001855 :data:`LastError` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001856
Georg Brandl116aa622007-08-15 14:28:22 +00001857.. function:: memmove(dst, src, count)
1858
1859 Same as the standard C memmove library function: copies *count* bytes from
Georg Brandl1d837bc2009-12-29 11:24:00 +00001860 *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can
1861 be converted to pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001862
1863
1864.. function:: memset(dst, c, count)
1865
1866 Same as the standard C memset library function: fills the memory block at
1867 address *dst* with *count* bytes of value *c*. *dst* must be an integer
1868 specifying an address, or a ctypes instance.
1869
1870
1871.. function:: POINTER(type)
1872
1873 This factory function creates and returns a new ctypes pointer type. Pointer
1874 types are cached an reused internally, so calling this function repeatedly is
Georg Brandl1d837bc2009-12-29 11:24:00 +00001875 cheap. *type* must be a ctypes type.
Georg Brandl116aa622007-08-15 14:28:22 +00001876
1877
1878.. function:: pointer(obj)
1879
Georg Brandl8d8f1972009-06-08 13:27:23 +00001880 This function creates a new pointer instance, pointing to *obj*. The returned
Georg Brandl1d837bc2009-12-29 11:24:00 +00001881 object is of the type ``POINTER(type(obj))``.
Georg Brandl116aa622007-08-15 14:28:22 +00001882
1883 Note: If you just want to pass a pointer to an object to a foreign function
1884 call, you should use ``byref(obj)`` which is much faster.
1885
1886
1887.. function:: resize(obj, size)
1888
Georg Brandl1d837bc2009-12-29 11:24:00 +00001889 This function resizes the internal memory buffer of *obj*, which must be an
1890 instance of a ctypes type. It is not possible to make the buffer smaller
1891 than the native size of the objects type, as given by ``sizeof(type(obj))``,
1892 but it is possible to enlarge the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00001893
1894
Thomas Hellerb795f5282008-06-10 15:26:58 +00001895.. function:: set_errno(value)
1896
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001897 Set the current value of the ctypes-private copy of the system :data:`errno`
1898 variable in the calling thread to *value* and return the previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001899
Georg Brandl8d8f1972009-06-08 13:27:23 +00001900
Georg Brandl1d837bc2009-12-29 11:24:00 +00001901
Thomas Hellerb795f5282008-06-10 15:26:58 +00001902.. function:: set_last_error(value)
1903
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001904 Windows only: set the current value of the ctypes-private copy of the system
1905 :data:`LastError` variable in the calling thread to *value* and return the
1906 previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001907
Georg Brandl8d8f1972009-06-08 13:27:23 +00001908
Georg Brandl1d837bc2009-12-29 11:24:00 +00001909
Georg Brandl116aa622007-08-15 14:28:22 +00001910.. function:: sizeof(obj_or_type)
1911
Ezio Melottie4597502013-10-21 04:41:40 +03001912 Returns the size in bytes of a ctypes type or instance memory buffer.
1913 Does the same as the C ``sizeof`` operator.
Georg Brandl116aa622007-08-15 14:28:22 +00001914
1915
Georg Brandl8d8f1972009-06-08 13:27:23 +00001916.. function:: string_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001917
Ezio Melottie130a522011-10-19 10:58:56 +03001918 This function returns the C string starting at memory address *address* as a bytes
Georg Brandl8d8f1972009-06-08 13:27:23 +00001919 object. If size is specified, it is used as size, otherwise the string is assumed
1920 to be zero-terminated.
Georg Brandl116aa622007-08-15 14:28:22 +00001921
1922
1923.. function:: WinError(code=None, descr=None)
1924
1925 Windows only: this function is probably the worst-named thing in ctypes. It
Antoine Pitrou442ee032011-10-12 18:53:23 +02001926 creates an instance of OSError. If *code* is not specified,
Georg Brandl1d837bc2009-12-29 11:24:00 +00001927 ``GetLastError`` is called to determine the error code. If *descr* is not
Thomas Woutersed03b412007-08-28 21:37:11 +00001928 specified, :func:`FormatError` is called to get a textual description of the
Georg Brandl116aa622007-08-15 14:28:22 +00001929 error.
1930
Antoine Pitrou442ee032011-10-12 18:53:23 +02001931 .. versionchanged:: 3.3
1932 An instance of :exc:`WindowsError` used to be created.
1933
Georg Brandl116aa622007-08-15 14:28:22 +00001934
Georg Brandl8d8f1972009-06-08 13:27:23 +00001935.. function:: wstring_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001936
1937 This function returns the wide character string starting at memory address
Georg Brandl1d837bc2009-12-29 11:24:00 +00001938 *address* as a string. If *size* is specified, it is used as the number of
1939 characters of the string, otherwise the string is assumed to be
Georg Brandl116aa622007-08-15 14:28:22 +00001940 zero-terminated.
1941
1942
1943.. _ctypes-data-types:
1944
1945Data types
1946^^^^^^^^^^
1947
1948
1949.. class:: _CData
1950
Georg Brandl1d837bc2009-12-29 11:24:00 +00001951 This non-public class is the common base class of all ctypes data types.
1952 Among other things, all ctypes type instances contain a memory block that
1953 hold C compatible data; the address of the memory block is returned by the
Georg Brandl8d8f1972009-06-08 13:27:23 +00001954 :func:`addressof` helper function. Another instance variable is exposed as
Georg Brandl1d837bc2009-12-29 11:24:00 +00001955 :attr:`_objects`; this contains other Python objects that need to be kept
1956 alive in case the memory block contains pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001957
Benjamin Petersone41251e2008-04-25 01:59:09 +00001958 Common methods of ctypes data types, these are all class methods (to be
1959 exact, they are methods of the :term:`metaclass`):
Georg Brandl116aa622007-08-15 14:28:22 +00001960
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001961 .. method:: _CData.from_buffer(source[, offset])
1962
Georg Brandl1d837bc2009-12-29 11:24:00 +00001963 This method returns a ctypes instance that shares the buffer of the
1964 *source* object. The *source* object must support the writeable buffer
1965 interface. The optional *offset* parameter specifies an offset into the
1966 source buffer in bytes; the default is zero. If the source buffer is not
1967 large enough a :exc:`ValueError` is raised.
1968
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001969
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001970 .. method:: _CData.from_buffer_copy(source[, offset])
1971
Georg Brandl1d837bc2009-12-29 11:24:00 +00001972 This method creates a ctypes instance, copying the buffer from the
1973 *source* object buffer which must be readable. The optional *offset*
1974 parameter specifies an offset into the source buffer in bytes; the default
1975 is zero. If the source buffer is not large enough a :exc:`ValueError` is
1976 raised.
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001977
Benjamin Petersone41251e2008-04-25 01:59:09 +00001978 .. method:: from_address(address)
Georg Brandl116aa622007-08-15 14:28:22 +00001979
Benjamin Petersone41251e2008-04-25 01:59:09 +00001980 This method returns a ctypes type instance using the memory specified by
Georg Brandl1d837bc2009-12-29 11:24:00 +00001981 *address* which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00001982
Benjamin Petersone41251e2008-04-25 01:59:09 +00001983 .. method:: from_param(obj)
Georg Brandl116aa622007-08-15 14:28:22 +00001984
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001985 This method adapts *obj* to a ctypes type. It is called with the actual
1986 object used in a foreign function call when the type is present in the
1987 foreign function's :attr:`argtypes` tuple; it must return an object that
1988 can be used as a function call parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001989
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001990 All ctypes data types have a default implementation of this classmethod
Georg Brandl8d8f1972009-06-08 13:27:23 +00001991 that normally returns *obj* if that is an instance of the type. Some
Benjamin Petersone41251e2008-04-25 01:59:09 +00001992 types accept other objects as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001993
Benjamin Petersone41251e2008-04-25 01:59:09 +00001994 .. method:: in_dll(library, name)
Georg Brandl116aa622007-08-15 14:28:22 +00001995
Benjamin Petersone41251e2008-04-25 01:59:09 +00001996 This method returns a ctypes type instance exported by a shared
1997 library. *name* is the name of the symbol that exports the data, *library*
1998 is the loaded shared library.
Georg Brandl116aa622007-08-15 14:28:22 +00001999
Benjamin Petersone41251e2008-04-25 01:59:09 +00002000 Common instance variables of ctypes data types:
Georg Brandl116aa622007-08-15 14:28:22 +00002001
Benjamin Petersone41251e2008-04-25 01:59:09 +00002002 .. attribute:: _b_base_
Georg Brandl116aa622007-08-15 14:28:22 +00002003
Benjamin Petersone41251e2008-04-25 01:59:09 +00002004 Sometimes ctypes data instances do not own the memory block they contain,
2005 instead they share part of the memory block of a base object. The
2006 :attr:`_b_base_` read-only member is the root ctypes object that owns the
2007 memory block.
Georg Brandl116aa622007-08-15 14:28:22 +00002008
Benjamin Petersone41251e2008-04-25 01:59:09 +00002009 .. attribute:: _b_needsfree_
Georg Brandl116aa622007-08-15 14:28:22 +00002010
Benjamin Petersone41251e2008-04-25 01:59:09 +00002011 This read-only variable is true when the ctypes data instance has
2012 allocated the memory block itself, false otherwise.
2013
Benjamin Petersone41251e2008-04-25 01:59:09 +00002014 .. attribute:: _objects
2015
2016 This member is either ``None`` or a dictionary containing Python objects
2017 that need to be kept alive so that the memory block contents is kept
2018 valid. This object is only exposed for debugging; never modify the
2019 contents of this dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002020
2021
2022.. _ctypes-fundamental-data-types-2:
2023
2024Fundamental data types
2025^^^^^^^^^^^^^^^^^^^^^^
2026
Georg Brandl116aa622007-08-15 14:28:22 +00002027.. class:: _SimpleCData
2028
Benjamin Peterson35e8c462008-04-24 02:34:53 +00002029 This non-public class is the base class of all fundamental ctypes data
2030 types. It is mentioned here because it contains the common attributes of the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002031 fundamental ctypes data types. :class:`_SimpleCData` is a subclass of
2032 :class:`_CData`, so it inherits their methods and attributes. ctypes data
2033 types that are not and do not contain pointers can now be pickled.
Thomas Heller13394e92008-02-13 20:40:44 +00002034
Benjamin Petersone41251e2008-04-25 01:59:09 +00002035 Instances have a single attribute:
Georg Brandl116aa622007-08-15 14:28:22 +00002036
Benjamin Petersone41251e2008-04-25 01:59:09 +00002037 .. attribute:: value
Georg Brandl116aa622007-08-15 14:28:22 +00002038
Benjamin Petersone41251e2008-04-25 01:59:09 +00002039 This attribute contains the actual value of the instance. For integer and
2040 pointer types, it is an integer, for character types, it is a single
Georg Brandl8d8f1972009-06-08 13:27:23 +00002041 character bytes object or string, for character pointer types it is a
2042 Python bytes object or string.
Georg Brandl116aa622007-08-15 14:28:22 +00002043
Benjamin Petersone41251e2008-04-25 01:59:09 +00002044 When the ``value`` attribute is retrieved from a ctypes instance, usually
Georg Brandl8d8f1972009-06-08 13:27:23 +00002045 a new object is returned each time. :mod:`ctypes` does *not* implement
Benjamin Petersone41251e2008-04-25 01:59:09 +00002046 original object return, always a new object is constructed. The same is
2047 true for all other ctypes object instances.
Georg Brandl116aa622007-08-15 14:28:22 +00002048
Georg Brandl8d8f1972009-06-08 13:27:23 +00002049
Georg Brandl116aa622007-08-15 14:28:22 +00002050Fundamental data types, when returned as foreign function call results, or, for
2051example, by retrieving structure field members or array items, are transparently
2052converted to native Python types. In other words, if a foreign function has a
Georg Brandl8d8f1972009-06-08 13:27:23 +00002053:attr:`restype` of :class:`c_char_p`, you will always receive a Python bytes
2054object, *not* a :class:`c_char_p` instance.
2055
2056.. XXX above is false, it actually returns a Unicode string
Georg Brandl116aa622007-08-15 14:28:22 +00002057
Thomas Woutersed03b412007-08-28 21:37:11 +00002058Subclasses of fundamental data types do *not* inherit this behavior. So, if a
Georg Brandl116aa622007-08-15 14:28:22 +00002059foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2060receive an instance of this subclass from the function call. Of course, you can
2061get the value of the pointer by accessing the ``value`` attribute.
2062
2063These are the fundamental ctypes data types:
2064
Georg Brandl116aa622007-08-15 14:28:22 +00002065.. class:: c_byte
2066
Georg Brandl60203b42010-10-06 10:11:56 +00002067 Represents the C :c:type:`signed char` datatype, and interprets the value as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002068 small integer. The constructor accepts an optional integer initializer; no
2069 overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002070
2071
2072.. class:: c_char
2073
Georg Brandl60203b42010-10-06 10:11:56 +00002074 Represents the C :c:type:`char` datatype, and interprets the value as a single
Georg Brandl1d837bc2009-12-29 11:24:00 +00002075 character. The constructor accepts an optional string initializer, the
2076 length of the string must be exactly one character.
Georg Brandl116aa622007-08-15 14:28:22 +00002077
2078
2079.. class:: c_char_p
2080
Georg Brandl60203b42010-10-06 10:11:56 +00002081 Represents the C :c:type:`char *` datatype when it points to a zero-terminated
Georg Brandl1d837bc2009-12-29 11:24:00 +00002082 string. For a general character pointer that may also point to binary data,
2083 ``POINTER(c_char)`` must be used. The constructor accepts an integer
2084 address, or a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +00002085
2086
2087.. class:: c_double
2088
Georg Brandl60203b42010-10-06 10:11:56 +00002089 Represents the C :c:type:`double` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002090 optional float initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002091
2092
Thomas Wouters89d996e2007-09-08 17:39:28 +00002093.. class:: c_longdouble
2094
Georg Brandl60203b42010-10-06 10:11:56 +00002095 Represents the C :c:type:`long double` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002096 optional float initializer. On platforms where ``sizeof(long double) ==
2097 sizeof(double)`` it is an alias to :class:`c_double`.
Thomas Wouters89d996e2007-09-08 17:39:28 +00002098
Georg Brandl116aa622007-08-15 14:28:22 +00002099.. class:: c_float
2100
Georg Brandl60203b42010-10-06 10:11:56 +00002101 Represents the C :c:type:`float` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002102 optional float initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002103
2104
2105.. class:: c_int
2106
Georg Brandl60203b42010-10-06 10:11:56 +00002107 Represents the C :c:type:`signed int` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002108 optional integer initializer; no overflow checking is done. On platforms
2109 where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
Georg Brandl116aa622007-08-15 14:28:22 +00002110
2111
2112.. class:: c_int8
2113
Georg Brandl60203b42010-10-06 10:11:56 +00002114 Represents the C 8-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002115 :class:`c_byte`.
2116
2117
2118.. class:: c_int16
2119
Georg Brandl60203b42010-10-06 10:11:56 +00002120 Represents the C 16-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002121 :class:`c_short`.
2122
2123
2124.. class:: c_int32
2125
Georg Brandl60203b42010-10-06 10:11:56 +00002126 Represents the C 32-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002127 :class:`c_int`.
2128
2129
2130.. class:: c_int64
2131
Georg Brandl60203b42010-10-06 10:11:56 +00002132 Represents the C 64-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002133 :class:`c_longlong`.
2134
2135
2136.. class:: c_long
2137
Georg Brandl60203b42010-10-06 10:11:56 +00002138 Represents the C :c:type:`signed long` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002139 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002140
2141
2142.. class:: c_longlong
2143
Georg Brandl60203b42010-10-06 10:11:56 +00002144 Represents the C :c:type:`signed long long` datatype. The constructor accepts
Georg Brandl1d837bc2009-12-29 11:24:00 +00002145 an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002146
2147
2148.. class:: c_short
2149
Georg Brandl60203b42010-10-06 10:11:56 +00002150 Represents the C :c:type:`signed short` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002151 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002152
2153
2154.. class:: c_size_t
2155
Georg Brandl60203b42010-10-06 10:11:56 +00002156 Represents the C :c:type:`size_t` datatype.
Georg Brandl116aa622007-08-15 14:28:22 +00002157
2158
Gregory P. Smith1a530912010-03-01 04:59:27 +00002159.. class:: c_ssize_t
2160
Georg Brandl60203b42010-10-06 10:11:56 +00002161 Represents the C :c:type:`ssize_t` datatype.
Gregory P. Smith1a530912010-03-01 04:59:27 +00002162
2163 .. versionadded:: 3.2
2164
2165
Georg Brandl116aa622007-08-15 14:28:22 +00002166.. class:: c_ubyte
2167
Georg Brandl60203b42010-10-06 10:11:56 +00002168 Represents the C :c:type:`unsigned char` datatype, it interprets the value as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002169 small integer. The constructor accepts an optional integer initializer; no
2170 overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002171
2172
2173.. class:: c_uint
2174
Georg Brandl60203b42010-10-06 10:11:56 +00002175 Represents the C :c:type:`unsigned int` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002176 optional integer initializer; no overflow checking is done. On platforms
2177 where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
Georg Brandl116aa622007-08-15 14:28:22 +00002178
2179
2180.. class:: c_uint8
2181
Georg Brandl60203b42010-10-06 10:11:56 +00002182 Represents the C 8-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002183 :class:`c_ubyte`.
2184
2185
2186.. class:: c_uint16
2187
Georg Brandl60203b42010-10-06 10:11:56 +00002188 Represents the C 16-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002189 :class:`c_ushort`.
2190
2191
2192.. class:: c_uint32
2193
Georg Brandl60203b42010-10-06 10:11:56 +00002194 Represents the C 32-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002195 :class:`c_uint`.
2196
2197
2198.. class:: c_uint64
2199
Georg Brandl60203b42010-10-06 10:11:56 +00002200 Represents the C 64-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002201 :class:`c_ulonglong`.
2202
2203
2204.. class:: c_ulong
2205
Georg Brandl60203b42010-10-06 10:11:56 +00002206 Represents the C :c:type:`unsigned long` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002207 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002208
2209
2210.. class:: c_ulonglong
2211
Georg Brandl60203b42010-10-06 10:11:56 +00002212 Represents the C :c:type:`unsigned long long` datatype. The constructor
Georg Brandl1d837bc2009-12-29 11:24:00 +00002213 accepts an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002214
2215
2216.. class:: c_ushort
2217
Georg Brandl60203b42010-10-06 10:11:56 +00002218 Represents the C :c:type:`unsigned short` datatype. The constructor accepts
Georg Brandl1d837bc2009-12-29 11:24:00 +00002219 an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002220
2221
2222.. class:: c_void_p
2223
Georg Brandl60203b42010-10-06 10:11:56 +00002224 Represents the C :c:type:`void *` type. The value is represented as integer.
Georg Brandl1d837bc2009-12-29 11:24:00 +00002225 The constructor accepts an optional integer initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002226
2227
2228.. class:: c_wchar
2229
Georg Brandl60203b42010-10-06 10:11:56 +00002230 Represents the C :c:type:`wchar_t` datatype, and interprets the value as a
Georg Brandl1d837bc2009-12-29 11:24:00 +00002231 single character unicode string. The constructor accepts an optional string
Georg Brandl116aa622007-08-15 14:28:22 +00002232 initializer, the length of the string must be exactly one character.
2233
2234
2235.. class:: c_wchar_p
2236
Georg Brandl60203b42010-10-06 10:11:56 +00002237 Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a
Georg Brandl1d837bc2009-12-29 11:24:00 +00002238 zero-terminated wide character string. The constructor accepts an integer
Georg Brandl116aa622007-08-15 14:28:22 +00002239 address, or a string.
2240
2241
2242.. class:: c_bool
2243
Georg Brandl60203b42010-10-06 10:11:56 +00002244 Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from
Serhiy Storchakafbc1c262013-11-29 12:17:13 +02002245 C99). Its value can be ``True`` or ``False``, and the constructor accepts any object
Georg Brandl1d837bc2009-12-29 11:24:00 +00002246 that has a truth value.
Georg Brandl116aa622007-08-15 14:28:22 +00002247
Georg Brandl116aa622007-08-15 14:28:22 +00002248
2249.. class:: HRESULT
2250
Georg Brandl60203b42010-10-06 10:11:56 +00002251 Windows only: Represents a :c:type:`HRESULT` value, which contains success or
Georg Brandl116aa622007-08-15 14:28:22 +00002252 error information for a function or method call.
2253
2254
2255.. class:: py_object
2256
Georg Brandl60203b42010-10-06 10:11:56 +00002257 Represents the C :c:type:`PyObject *` datatype. Calling this without an
2258 argument creates a ``NULL`` :c:type:`PyObject *` pointer.
Georg Brandl116aa622007-08-15 14:28:22 +00002259
Georg Brandl1d837bc2009-12-29 11:24:00 +00002260The :mod:`ctypes.wintypes` module provides quite some other Windows specific
Georg Brandl60203b42010-10-06 10:11:56 +00002261data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`. Some
2262useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined.
Georg Brandl116aa622007-08-15 14:28:22 +00002263
2264
2265.. _ctypes-structured-data-types:
2266
2267Structured data types
2268^^^^^^^^^^^^^^^^^^^^^
2269
2270
2271.. class:: Union(*args, **kw)
2272
2273 Abstract base class for unions in native byte order.
2274
2275
2276.. class:: BigEndianStructure(*args, **kw)
2277
2278 Abstract base class for structures in *big endian* byte order.
2279
2280
2281.. class:: LittleEndianStructure(*args, **kw)
2282
2283 Abstract base class for structures in *little endian* byte order.
2284
2285Structures with non-native byte order cannot contain pointer type fields, or any
2286other data types containing pointer type fields.
2287
2288
2289.. class:: Structure(*args, **kw)
2290
2291 Abstract base class for structures in *native* byte order.
2292
Benjamin Petersone41251e2008-04-25 01:59:09 +00002293 Concrete structure and union types must be created by subclassing one of these
Georg Brandl8d8f1972009-06-08 13:27:23 +00002294 types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
Benjamin Petersone41251e2008-04-25 01:59:09 +00002295 create :term:`descriptor`\s which allow reading and writing the fields by direct
2296 attribute accesses. These are the
Georg Brandl116aa622007-08-15 14:28:22 +00002297
2298
Benjamin Petersone41251e2008-04-25 01:59:09 +00002299 .. attribute:: _fields_
Georg Brandl116aa622007-08-15 14:28:22 +00002300
Benjamin Petersone41251e2008-04-25 01:59:09 +00002301 A sequence defining the structure fields. The items must be 2-tuples or
2302 3-tuples. The first item is the name of the field, the second item
2303 specifies the type of the field; it can be any ctypes data type.
Georg Brandl116aa622007-08-15 14:28:22 +00002304
Benjamin Petersone41251e2008-04-25 01:59:09 +00002305 For integer type fields like :class:`c_int`, a third optional item can be
2306 given. It must be a small positive integer defining the bit width of the
2307 field.
Georg Brandl116aa622007-08-15 14:28:22 +00002308
Benjamin Petersone41251e2008-04-25 01:59:09 +00002309 Field names must be unique within one structure or union. This is not
2310 checked, only one field can be accessed when names are repeated.
Georg Brandl116aa622007-08-15 14:28:22 +00002311
Benjamin Petersone41251e2008-04-25 01:59:09 +00002312 It is possible to define the :attr:`_fields_` class variable *after* the
2313 class statement that defines the Structure subclass, this allows to create
2314 data types that directly or indirectly reference themselves::
Georg Brandl116aa622007-08-15 14:28:22 +00002315
Benjamin Petersone41251e2008-04-25 01:59:09 +00002316 class List(Structure):
2317 pass
2318 List._fields_ = [("pnext", POINTER(List)),
2319 ...
2320 ]
Georg Brandl116aa622007-08-15 14:28:22 +00002321
Benjamin Petersone41251e2008-04-25 01:59:09 +00002322 The :attr:`_fields_` class variable must, however, be defined before the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002323 type is first used (an instance is created, :func:`sizeof` is called on it,
Benjamin Petersone41251e2008-04-25 01:59:09 +00002324 and so on). Later assignments to the :attr:`_fields_` class variable will
2325 raise an AttributeError.
Georg Brandl116aa622007-08-15 14:28:22 +00002326
Benjamin Petersone41251e2008-04-25 01:59:09 +00002327 Structure and union subclass constructors accept both positional and named
2328 arguments. Positional arguments are used to initialize the fields in the
2329 same order as they appear in the :attr:`_fields_` definition, named
2330 arguments are used to initialize the fields with the corresponding name.
Georg Brandl116aa622007-08-15 14:28:22 +00002331
Benjamin Petersone41251e2008-04-25 01:59:09 +00002332 It is possible to defined sub-subclasses of structure types, they inherit
2333 the fields of the base class plus the :attr:`_fields_` defined in the
2334 sub-subclass, if any.
Georg Brandl116aa622007-08-15 14:28:22 +00002335
2336
Benjamin Petersone41251e2008-04-25 01:59:09 +00002337 .. attribute:: _pack_
Georg Brandl116aa622007-08-15 14:28:22 +00002338
Benjamin Petersone41251e2008-04-25 01:59:09 +00002339 An optional small integer that allows to override the alignment of
2340 structure fields in the instance. :attr:`_pack_` must already be defined
2341 when :attr:`_fields_` is assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002342
2343
Benjamin Petersone41251e2008-04-25 01:59:09 +00002344 .. attribute:: _anonymous_
Georg Brandl116aa622007-08-15 14:28:22 +00002345
Benjamin Petersone41251e2008-04-25 01:59:09 +00002346 An optional sequence that lists the names of unnamed (anonymous) fields.
Georg Brandl1d837bc2009-12-29 11:24:00 +00002347 :attr:`_anonymous_` must be already defined when :attr:`_fields_` is
2348 assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002349
Benjamin Petersone41251e2008-04-25 01:59:09 +00002350 The fields listed in this variable must be structure or union type fields.
Georg Brandl8d8f1972009-06-08 13:27:23 +00002351 :mod:`ctypes` will create descriptors in the structure type that allows to
Benjamin Petersone41251e2008-04-25 01:59:09 +00002352 access the nested fields directly, without the need to create the
2353 structure or union field.
Georg Brandl116aa622007-08-15 14:28:22 +00002354
Benjamin Petersone41251e2008-04-25 01:59:09 +00002355 Here is an example type (Windows)::
Georg Brandl116aa622007-08-15 14:28:22 +00002356
Benjamin Petersone41251e2008-04-25 01:59:09 +00002357 class _U(Union):
2358 _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2359 ("lpadesc", POINTER(ARRAYDESC)),
2360 ("hreftype", HREFTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002361
Benjamin Petersone41251e2008-04-25 01:59:09 +00002362 class TYPEDESC(Structure):
Benjamin Petersonb58dda72009-01-18 22:27:04 +00002363 _anonymous_ = ("u",)
Benjamin Petersone41251e2008-04-25 01:59:09 +00002364 _fields_ = [("u", _U),
2365 ("vt", VARTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002366
Georg Brandl116aa622007-08-15 14:28:22 +00002367
Benjamin Petersone41251e2008-04-25 01:59:09 +00002368 The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2369 specifies which one of the union fields is valid. Since the ``u`` field
2370 is defined as anonymous field, it is now possible to access the members
2371 directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2372 are equivalent, but the former is faster since it does not need to create
2373 a temporary union instance::
Georg Brandl116aa622007-08-15 14:28:22 +00002374
Benjamin Petersone41251e2008-04-25 01:59:09 +00002375 td = TYPEDESC()
2376 td.vt = VT_PTR
2377 td.lptdesc = POINTER(some_type)
2378 td.u.lptdesc = POINTER(some_type)
Georg Brandl116aa622007-08-15 14:28:22 +00002379
Georg Brandl1d837bc2009-12-29 11:24:00 +00002380 It is possible to defined sub-subclasses of structures, they inherit the
2381 fields of the base class. If the subclass definition has a separate
2382 :attr:`_fields_` variable, the fields specified in this are appended to the
2383 fields of the base class.
Georg Brandl116aa622007-08-15 14:28:22 +00002384
Georg Brandl1d837bc2009-12-29 11:24:00 +00002385 Structure and union constructors accept both positional and keyword
2386 arguments. Positional arguments are used to initialize member fields in the
2387 same order as they are appear in :attr:`_fields_`. Keyword arguments in the
2388 constructor are interpreted as attribute assignments, so they will initialize
2389 :attr:`_fields_` with the same name, or create new attributes for names not
2390 present in :attr:`_fields_`.
Georg Brandl116aa622007-08-15 14:28:22 +00002391
2392
2393.. _ctypes-arrays-pointers:
2394
2395Arrays and pointers
2396^^^^^^^^^^^^^^^^^^^
2397
Georg Brandl1d837bc2009-12-29 11:24:00 +00002398Not yet written - please see the sections :ref:`ctypes-pointers` and section
2399:ref:`ctypes-arrays` in the tutorial.
Georg Brandl116aa622007-08-15 14:28:22 +00002400