blob: ad5adee8aa1976f5fd7bebbbd0675efbce82ea97 [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 Brandl116aa622007-08-15 14:28:22 +00009``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 Brandl8d8f1972009-06-08 13:27:23 +000019Note: The code samples in this tutorial use :mod:`doctest` to make sure that they
Georg Brandl116aa622007-08-15 14:28:22 +000020actually work. Since some code samples behave differently under Linux, Windows,
21or Mac OS X, they contain doctest directives in comments.
22
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
41assumes the functions return a Windows :class:`HRESULT` error code. The error
Thomas Heller2fadaa22008-06-16 19:56:33 +000042code is used to automatically raise a :class:`WindowsError` exception when
Georg Brandl116aa622007-08-15 14:28:22 +000043the function call fails.
44
45Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
46library containing most standard C functions, and uses the cdecl calling
47convention::
48
49 >>> from ctypes import *
Georg Brandl6911e3c2007-09-04 07:15:32 +000050 >>> print(windll.kernel32) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000051 <WinDLL 'kernel32', handle ... at ...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000052 >>> print(cdll.msvcrt) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000053 <CDLL 'msvcrt', handle ... at ...>
54 >>> libc = cdll.msvcrt # doctest: +WINDOWS
55 >>>
56
Thomas Heller2fadaa22008-06-16 19:56:33 +000057Windows appends the usual ``.dll`` file suffix automatically.
Georg Brandl116aa622007-08-15 14:28:22 +000058
59On Linux, it is required to specify the filename *including* the extension to
Thomas Heller2fadaa22008-06-16 19:56:33 +000060load a library, so attribute access can not be used to load libraries. Either the
Georg Brandl116aa622007-08-15 14:28:22 +000061:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
62the library by creating an instance of CDLL by calling the constructor::
63
64 >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
65 <CDLL 'libc.so.6', handle ... at ...>
66 >>> libc = CDLL("libc.so.6") # doctest: +LINUX
67 >>> libc # doctest: +LINUX
68 <CDLL 'libc.so.6', handle ... at ...>
69 >>>
70
Christian Heimes5b5e81c2007-12-31 16:14:33 +000071.. XXX Add section for Mac OS X.
Georg Brandl116aa622007-08-15 14:28:22 +000072
73
74.. _ctypes-accessing-functions-from-loaded-dlls:
75
76Accessing functions from loaded dlls
77^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
78
79Functions are accessed as attributes of dll objects::
80
81 >>> from ctypes import *
82 >>> libc.printf
83 <_FuncPtr object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000084 >>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000085 <_FuncPtr object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000086 >>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000087 Traceback (most recent call last):
88 File "<stdin>", line 1, in ?
89 File "ctypes.py", line 239, in __getattr__
90 func = _StdcallFuncPtr(name, self)
91 AttributeError: function 'MyOwnFunction' not found
92 >>>
93
94Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
95as well as UNICODE versions of a function. The UNICODE version is exported with
96an ``W`` appended to the name, while the ANSI version is exported with an ``A``
97appended to the name. The win32 ``GetModuleHandle`` function, which returns a
98*module handle* for a given module name, has the following C prototype, and a
99macro is used to expose one of them as ``GetModuleHandle`` depending on whether
100UNICODE is defined or not::
101
102 /* ANSI version */
103 HMODULE GetModuleHandleA(LPCSTR lpModuleName);
104 /* UNICODE version */
105 HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
106
107*windll* does not try to select one of them by magic, you must access the
108version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
Georg Brandl8d8f1972009-06-08 13:27:23 +0000109explicitly, and then call it with bytes or string objects respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
111Sometimes, dlls export functions with names which aren't valid Python
112identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use ``getattr``
113to retrieve the function::
114
115 >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
116 <_FuncPtr object at 0x...>
117 >>>
118
119On Windows, some dlls export functions not by name but by ordinal. These
120functions can be accessed by indexing the dll object with the ordinal number::
121
122 >>> cdll.kernel32[1] # doctest: +WINDOWS
123 <_FuncPtr object at 0x...>
124 >>> cdll.kernel32[0] # doctest: +WINDOWS
125 Traceback (most recent call last):
126 File "<stdin>", line 1, in ?
127 File "ctypes.py", line 310, in __getitem__
128 func = _StdcallFuncPtr(name, self)
129 AttributeError: function ordinal 0 not found
130 >>>
131
132
133.. _ctypes-calling-functions:
134
135Calling functions
136^^^^^^^^^^^^^^^^^
137
138You can call these functions like any other Python callable. This example uses
139the ``time()`` function, which returns system time in seconds since the Unix
140epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
141handle.
142
143This example calls both functions with a NULL pointer (``None`` should be used
144as the NULL pointer)::
145
Georg Brandl6911e3c2007-09-04 07:15:32 +0000146 >>> print(libc.time(None)) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000147 1150640792
Georg Brandl6911e3c2007-09-04 07:15:32 +0000148 >>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000149 0x1d000000
150 >>>
151
Georg Brandl8d8f1972009-06-08 13:27:23 +0000152:mod:`ctypes` tries to protect you from calling functions with the wrong number of
Georg Brandl116aa622007-08-15 14:28:22 +0000153arguments or the wrong calling convention. Unfortunately this only works on
154Windows. It does this by examining the stack after the function returns, so
155although an error is raised the function *has* been called::
156
157 >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
158 Traceback (most recent call last):
159 File "<stdin>", line 1, in ?
160 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
161 >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
162 Traceback (most recent call last):
163 File "<stdin>", line 1, in ?
164 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
165 >>>
166
167The same exception is raised when you call an ``stdcall`` function with the
168``cdecl`` calling convention, or vice versa::
169
170 >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
171 Traceback (most recent call last):
172 File "<stdin>", line 1, in ?
173 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
174 >>>
175
Georg Brandl8d8f1972009-06-08 13:27:23 +0000176 >>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000177 Traceback (most recent call last):
178 File "<stdin>", line 1, in ?
179 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
180 >>>
181
182To find out the correct calling convention you have to look into the C header
183file or the documentation for the function you want to call.
184
Georg Brandl8d8f1972009-06-08 13:27:23 +0000185On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
Georg Brandl116aa622007-08-15 14:28:22 +0000186crashes from general protection faults when functions are called with invalid
187argument values::
188
189 >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
190 Traceback (most recent call last):
191 File "<stdin>", line 1, in ?
192 WindowsError: exception: access violation reading 0x00000020
193 >>>
194
Georg Brandl8d8f1972009-06-08 13:27:23 +0000195There are, however, enough ways to crash Python with :mod:`ctypes`, so you should
Georg Brandl116aa622007-08-15 14:28:22 +0000196be careful anyway.
197
Georg Brandl8d8f1972009-06-08 13:27:23 +0000198``None``, integers, bytes objects and (unicode) strings are the only native
Georg Brandl116aa622007-08-15 14:28:22 +0000199Python objects that can directly be used as parameters in these function calls.
Georg Brandl8d8f1972009-06-08 13:27:23 +0000200``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are
Georg Brandl116aa622007-08-15 14:28:22 +0000201passed as pointer to the memory block that contains their data (``char *`` or
Georg Brandl5c106642007-11-29 17:41:05 +0000202``wchar_t *``). Python integers are passed as the platforms
Georg Brandl116aa622007-08-15 14:28:22 +0000203default C ``int`` type, their value is masked to fit into the C type.
204
205Before we move on calling functions with other parameter types, we have to learn
Georg Brandl8d8f1972009-06-08 13:27:23 +0000206more about :mod:`ctypes` data types.
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208
209.. _ctypes-fundamental-data-types:
210
211Fundamental data types
212^^^^^^^^^^^^^^^^^^^^^^
213
Georg Brandl8d8f1972009-06-08 13:27:23 +0000214:mod:`ctypes` defines a number of primitive C compatible data types :
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216 +----------------------+--------------------------------+----------------------------+
217 | ctypes type | C type | Python type |
218 +======================+================================+============================+
Georg Brandl8d8f1972009-06-08 13:27:23 +0000219 | :class:`c_char` | ``char`` | 1-character bytes object |
Georg Brandl116aa622007-08-15 14:28:22 +0000220 +----------------------+--------------------------------+----------------------------+
Georg Brandl8d8f1972009-06-08 13:27:23 +0000221 | :class:`c_wchar` | ``wchar_t`` | 1-character string |
Georg Brandl116aa622007-08-15 14:28:22 +0000222 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000223 | :class:`c_byte` | ``char`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000224 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000225 | :class:`c_ubyte` | ``unsigned char`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000226 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000227 | :class:`c_short` | ``short`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000228 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000229 | :class:`c_ushort` | ``unsigned short`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000230 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000231 | :class:`c_int` | ``int`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000232 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000233 | :class:`c_uint` | ``unsigned int`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000234 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000235 | :class:`c_long` | ``long`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000236 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000237 | :class:`c_ulong` | ``unsigned long`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000238 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000239 | :class:`c_longlong` | ``__int64`` or ``long long`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000240 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000241 | :class:`c_ulonglong` | ``unsigned __int64`` or | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000242 | | ``unsigned long long`` | |
243 +----------------------+--------------------------------+----------------------------+
244 | :class:`c_float` | ``float`` | float |
245 +----------------------+--------------------------------+----------------------------+
246 | :class:`c_double` | ``double`` | float |
247 +----------------------+--------------------------------+----------------------------+
Thomas Wouters89d996e2007-09-08 17:39:28 +0000248 | :class:`c_longdouble`| ``long double`` | float |
249 +----------------------+--------------------------------+----------------------------+
Thomas Heller3440c422009-06-08 19:11:54 +0000250 | :class:`c_char_p` | ``char *`` (NUL terminated) | bytes object or ``None`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000251 +----------------------+--------------------------------+----------------------------+
Georg Brandl8d8f1972009-06-08 13:27:23 +0000252 | :class:`c_wchar_p` | ``wchar_t *`` (NUL terminated) | string or ``None`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000253 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000254 | :class:`c_void_p` | ``void *`` | int or ``None`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000255 +----------------------+--------------------------------+----------------------------+
256
257
258All these types can be created by calling them with an optional initializer of
259the correct type and value::
260
261 >>> c_int()
262 c_long(0)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000263 >>> c_wchar_p("Hello, World")
264 c_wchar_p('Hello, World')
Georg Brandl116aa622007-08-15 14:28:22 +0000265 >>> c_ushort(-3)
266 c_ushort(65533)
267 >>>
268
269Since these types are mutable, their value can also be changed afterwards::
270
271 >>> i = c_int(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000272 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000273 c_long(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000274 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000275 42
276 >>> i.value = -99
Georg Brandl6911e3c2007-09-04 07:15:32 +0000277 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000278 -99
279 >>>
280
281Assigning a new value to instances of the pointer types :class:`c_char_p`,
282:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
283point to, *not the contents* of the memory block (of course not, because Python
Georg Brandl8d8f1972009-06-08 13:27:23 +0000284bytes objects are immutable)::
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286 >>> s = "Hello, World"
Georg Brandl8d8f1972009-06-08 13:27:23 +0000287 >>> c_s = c_wchar_p(s)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000288 >>> print(c_s)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000289 c_wchar_p('Hello, World')
Georg Brandl116aa622007-08-15 14:28:22 +0000290 >>> c_s.value = "Hi, there"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000291 >>> print(c_s)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000292 c_wchar_p('Hi, there')
293 >>> print(s) # first object is unchanged
Georg Brandl116aa622007-08-15 14:28:22 +0000294 Hello, World
295 >>>
296
297You should be careful, however, not to pass them to functions expecting pointers
298to mutable memory. If you need mutable memory blocks, ctypes has a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000299:func:`create_string_buffer` function which creates these in various ways. The
Georg Brandl116aa622007-08-15 14:28:22 +0000300current memory block contents can be accessed (or changed) with the ``raw``
301property; if you want to access it as NUL terminated string, use the ``value``
302property::
303
304 >>> from ctypes import *
Georg Brandl8d8f1972009-06-08 13:27:23 +0000305 >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
Georg Brandl6911e3c2007-09-04 07:15:32 +0000306 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000307 3 b'\x00\x00\x00'
308 >>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string
Georg Brandl6911e3c2007-09-04 07:15:32 +0000309 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000310 6 b'Hello\x00'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000311 >>> print(repr(p.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000312 b'Hello'
313 >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000314 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000315 10 b'Hello\x00\x00\x00\x00\x00'
316 >>> p.value = b"Hi"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000317 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000318 10 b'Hi\x00lo\x00\x00\x00\x00\x00'
Georg Brandl116aa622007-08-15 14:28:22 +0000319 >>>
320
Georg Brandl8d8f1972009-06-08 13:27:23 +0000321The :func:`create_string_buffer` function replaces the ``c_buffer`` function
322(which is still available as an alias), as well as the ``c_string`` function
323from earlier ctypes releases. To create a mutable memory block containing
324unicode characters of the C type ``wchar_t`` use the
325:func:`create_unicode_buffer` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000326
327
328.. _ctypes-calling-functions-continued:
329
330Calling functions, continued
331^^^^^^^^^^^^^^^^^^^^^^^^^^^^
332
333Note that printf prints to the real standard output channel, *not* to
Georg Brandl8d8f1972009-06-08 13:27:23 +0000334:data:`sys.stdout`, so these examples will only work at the console prompt, not
335from within *IDLE* or *PythonWin*::
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337 >>> printf = libc.printf
Georg Brandl8d8f1972009-06-08 13:27:23 +0000338 >>> printf(b"Hello, %s\n", b"World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000339 Hello, World!
340 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000341 >>> printf(b"Hello, %S\n", "World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000342 Hello, World!
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000343 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000344 >>> printf(b"%d bottles of beer\n", 42)
Georg Brandl116aa622007-08-15 14:28:22 +0000345 42 bottles of beer
346 19
Georg Brandl8d8f1972009-06-08 13:27:23 +0000347 >>> printf(b"%f bottles of beer\n", 42.5)
Georg Brandl116aa622007-08-15 14:28:22 +0000348 Traceback (most recent call last):
349 File "<stdin>", line 1, in ?
350 ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
351 >>>
352
353As has been mentioned before, all Python types except integers, strings, and
Georg Brandl8d8f1972009-06-08 13:27:23 +0000354bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so
Georg Brandl116aa622007-08-15 14:28:22 +0000355that they can be converted to the required C data type::
356
Georg Brandl8d8f1972009-06-08 13:27:23 +0000357 >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000358 An int 1234, a double 3.140000
Georg Brandl116aa622007-08-15 14:28:22 +0000359 31
360 >>>
361
362
363.. _ctypes-calling-functions-with-own-custom-data-types:
364
365Calling functions with your own custom data types
366^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
367
Georg Brandl8d8f1972009-06-08 13:27:23 +0000368You can also customize :mod:`ctypes` argument conversion to allow instances of your
369own classes be used as function arguments. :mod:`ctypes` looks for an
Georg Brandl116aa622007-08-15 14:28:22 +0000370:attr:`_as_parameter_` attribute and uses this as the function argument. Of
Georg Brandl8d8f1972009-06-08 13:27:23 +0000371course, it must be one of integer, string, or bytes::
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373 >>> class Bottles(object):
374 ... def __init__(self, number):
375 ... self._as_parameter_ = number
376 ...
377 >>> bottles = Bottles(42)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000378 >>> printf(b"%d bottles of beer\n", bottles)
Georg Brandl116aa622007-08-15 14:28:22 +0000379 42 bottles of beer
380 19
381 >>>
382
383If you don't want to store the instance's data in the :attr:`_as_parameter_`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000384instance variable, you could define a :class:`property` which makes the
385attribute available on request.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387
388.. _ctypes-specifying-required-argument-types:
389
390Specifying the required argument types (function prototypes)
391^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
392
393It is possible to specify the required argument types of functions exported from
394DLLs by setting the :attr:`argtypes` attribute.
395
396:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
397probably not a good example here, because it takes a variable number and
398different types of parameters depending on the format string, on the other hand
399this is quite handy to experiment with this feature)::
400
401 >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000402 >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
Georg Brandl116aa622007-08-15 14:28:22 +0000403 String 'Hi', Int 10, Double 2.200000
404 37
405 >>>
406
407Specifying a format protects against incompatible argument types (just as a
408prototype for a C function), and tries to convert the arguments to valid types::
409
Georg Brandl8d8f1972009-06-08 13:27:23 +0000410 >>> printf(b"%d %d %d", 1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000411 Traceback (most recent call last):
412 File "<stdin>", line 1, in ?
413 ArgumentError: argument 2: exceptions.TypeError: wrong type
Georg Brandl8d8f1972009-06-08 13:27:23 +0000414 >>> printf(b"%s %d %f\n", b"X", 2, 3)
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000415 X 2 3.000000
416 13
Georg Brandl116aa622007-08-15 14:28:22 +0000417 >>>
418
419If you have defined your own classes which you pass to function calls, you have
420to implement a :meth:`from_param` class method for them to be able to use them
421in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
422the Python object passed to the function call, it should do a typecheck or
423whatever is needed to make sure this object is acceptable, and then return the
Thomas Heller2fadaa22008-06-16 19:56:33 +0000424object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
Georg Brandl116aa622007-08-15 14:28:22 +0000425pass as the C function argument in this case. Again, the result should be an
Georg Brandl8d8f1972009-06-08 13:27:23 +0000426integer, string, bytes, a :mod:`ctypes` instance, or an object with an
Georg Brandl116aa622007-08-15 14:28:22 +0000427:attr:`_as_parameter_` attribute.
428
429
430.. _ctypes-return-types:
431
432Return types
433^^^^^^^^^^^^
434
435By default functions are assumed to return the C ``int`` type. Other return
436types can be specified by setting the :attr:`restype` attribute of the function
437object.
438
439Here is a more advanced example, it uses the ``strchr`` function, which expects
440a string pointer and a char, and returns a pointer to a string::
441
442 >>> strchr = libc.strchr
Georg Brandl8d8f1972009-06-08 13:27:23 +0000443 >>> strchr(b"abcdef", ord("d")) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000444 8059983
Georg Brandl8d8f1972009-06-08 13:27:23 +0000445 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
446 >>> strchr(b"abcdef", ord("d"))
447 b'def'
448 >>> print(strchr(b"abcdef", ord("x")))
Georg Brandl116aa622007-08-15 14:28:22 +0000449 None
450 >>>
451
452If you want to avoid the ``ord("x")`` calls above, you can set the
453:attr:`argtypes` attribute, and the second argument will be converted from a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000454single character Python bytes object into a C char::
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456 >>> strchr.restype = c_char_p
457 >>> strchr.argtypes = [c_char_p, c_char]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000458 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000459 'def'
Georg Brandl8d8f1972009-06-08 13:27:23 +0000460 >>> strchr(b"abcdef", b"def")
Georg Brandl116aa622007-08-15 14:28:22 +0000461 Traceback (most recent call last):
462 File "<stdin>", line 1, in ?
463 ArgumentError: argument 2: exceptions.TypeError: one character string expected
Georg Brandl8d8f1972009-06-08 13:27:23 +0000464 >>> print(strchr(b"abcdef", b"x"))
Georg Brandl116aa622007-08-15 14:28:22 +0000465 None
Georg Brandl8d8f1972009-06-08 13:27:23 +0000466 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000467 'def'
468 >>>
469
470You can also use a callable Python object (a function or a class for example) as
471the :attr:`restype` attribute, if the foreign function returns an integer. The
472callable will be called with the ``integer`` the C function returns, and the
473result of this call will be used as the result of your function call. This is
474useful to check for error return values and automatically raise an exception::
475
476 >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
477 >>> def ValidHandle(value):
478 ... if value == 0:
479 ... raise WinError()
480 ... return value
481 ...
482 >>>
483 >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
484 >>> GetModuleHandle(None) # doctest: +WINDOWS
485 486539264
486 >>> GetModuleHandle("something silly") # doctest: +WINDOWS
487 Traceback (most recent call last):
488 File "<stdin>", line 1, in ?
489 File "<stdin>", line 3, in ValidHandle
490 WindowsError: [Errno 126] The specified module could not be found.
491 >>>
492
493``WinError`` is a function which will call Windows ``FormatMessage()`` api to
494get the string representation of an error code, and *returns* an exception.
495``WinError`` takes an optional error code parameter, if no one is used, it calls
496:func:`GetLastError` to retrieve it.
497
498Please note that a much more powerful error checking mechanism is available
499through the :attr:`errcheck` attribute; see the reference manual for details.
500
501
502.. _ctypes-passing-pointers:
503
504Passing pointers (or: passing parameters by reference)
505^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
506
507Sometimes a C api function expects a *pointer* to a data type as parameter,
508probably to write into the corresponding location, or if the data is too large
509to be passed by value. This is also known as *passing parameters by reference*.
510
Georg Brandl8d8f1972009-06-08 13:27:23 +0000511:mod:`ctypes` exports the :func:`byref` function which is used to pass parameters
512by reference. The same effect can be achieved with the :func:`pointer` function,
513although :func:`pointer` does a lot more work since it constructs a real pointer
Georg Brandl116aa622007-08-15 14:28:22 +0000514object, so it is faster to use :func:`byref` if you don't need the pointer
515object in Python itself::
516
517 >>> i = c_int()
518 >>> f = c_float()
Georg Brandl8d8f1972009-06-08 13:27:23 +0000519 >>> s = create_string_buffer(b'\000' * 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000520 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000521 0 0.0 b''
522 >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
Georg Brandl116aa622007-08-15 14:28:22 +0000523 ... byref(i), byref(f), s)
524 3
Georg Brandl6911e3c2007-09-04 07:15:32 +0000525 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000526 1 3.1400001049 b'Hello'
Georg Brandl116aa622007-08-15 14:28:22 +0000527 >>>
528
529
530.. _ctypes-structures-unions:
531
532Structures and unions
533^^^^^^^^^^^^^^^^^^^^^
534
535Structures and unions must derive from the :class:`Structure` and :class:`Union`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000536base classes which are defined in the :mod:`ctypes` module. Each subclass must
Georg Brandl116aa622007-08-15 14:28:22 +0000537define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
538*2-tuples*, containing a *field name* and a *field type*.
539
Georg Brandl8d8f1972009-06-08 13:27:23 +0000540The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
541derived :mod:`ctypes` type: structure, union, array, pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000542
543Here is a simple example of a POINT structure, which contains two integers named
Georg Brandl8d8f1972009-06-08 13:27:23 +0000544*x* and *y*, and also shows how to initialize a structure in the constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000545
546 >>> from ctypes import *
547 >>> class POINT(Structure):
548 ... _fields_ = [("x", c_int),
549 ... ("y", c_int)]
550 ...
551 >>> point = POINT(10, 20)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000552 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000553 10 20
554 >>> point = POINT(y=5)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000555 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000556 0 5
557 >>> POINT(1, 2, 3)
558 Traceback (most recent call last):
559 File "<stdin>", line 1, in ?
560 ValueError: too many initializers
561 >>>
562
563You can, however, build much more complicated structures. Structures can itself
564contain other structures by using a structure as a field type.
565
566Here is a RECT structure which contains two POINTs named ``upperleft`` and
567``lowerright`` ::
568
569 >>> class RECT(Structure):
570 ... _fields_ = [("upperleft", POINT),
571 ... ("lowerright", POINT)]
572 ...
573 >>> rc = RECT(point)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000574 >>> print(rc.upperleft.x, rc.upperleft.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000575 0 5
Georg Brandl6911e3c2007-09-04 07:15:32 +0000576 >>> print(rc.lowerright.x, rc.lowerright.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000577 0 0
578 >>>
579
580Nested structures can also be initialized in the constructor in several ways::
581
582 >>> r = RECT(POINT(1, 2), POINT(3, 4))
583 >>> r = RECT((1, 2), (3, 4))
584
Georg Brandl9afde1c2007-11-01 20:32:30 +0000585Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
586for debugging because they can provide useful information::
Georg Brandl116aa622007-08-15 14:28:22 +0000587
Georg Brandl6911e3c2007-09-04 07:15:32 +0000588 >>> print(POINT.x)
Georg Brandl116aa622007-08-15 14:28:22 +0000589 <Field type=c_long, ofs=0, size=4>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000590 >>> print(POINT.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000591 <Field type=c_long, ofs=4, size=4>
592 >>>
593
594
595.. _ctypes-structureunion-alignment-byte-order:
596
597Structure/union alignment and byte order
598^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
599
600By default, Structure and Union fields are aligned in the same way the C
Thomas Woutersed03b412007-08-28 21:37:11 +0000601compiler does it. It is possible to override this behavior be specifying a
Georg Brandl116aa622007-08-15 14:28:22 +0000602:attr:`_pack_` class attribute in the subclass definition. This must be set to a
603positive integer and specifies the maximum alignment for the fields. This is
604what ``#pragma pack(n)`` also does in MSVC.
605
Georg Brandl8d8f1972009-06-08 13:27:23 +0000606:mod:`ctypes` uses the native byte order for Structures and Unions. To build
Georg Brandl116aa622007-08-15 14:28:22 +0000607structures with non-native byte order, you can use one of the
608BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
609base classes. These classes cannot contain pointer fields.
610
611
612.. _ctypes-bit-fields-in-structures-unions:
613
614Bit fields in structures and unions
615^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
616
617It is possible to create structures and unions containing bit fields. Bit fields
618are only possible for integer fields, the bit width is specified as the third
619item in the :attr:`_fields_` tuples::
620
621 >>> class Int(Structure):
622 ... _fields_ = [("first_16", c_int, 16),
623 ... ("second_16", c_int, 16)]
624 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000625 >>> print(Int.first_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000626 <Field type=c_long, ofs=0:0, bits=16>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000627 >>> print(Int.second_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000628 <Field type=c_long, ofs=0:16, bits=16>
629 >>>
630
631
632.. _ctypes-arrays:
633
634Arrays
635^^^^^^
636
637Arrays are sequences, containing a fixed number of instances of the same type.
638
639The recommended way to create array types is by multiplying a data type with a
640positive integer::
641
642 TenPointsArrayType = POINT * 10
643
Thomas Woutersed03b412007-08-28 21:37:11 +0000644Here is an example of an somewhat artificial data type, a structure containing 4
Georg Brandl116aa622007-08-15 14:28:22 +0000645POINTs among other stuff::
646
647 >>> from ctypes import *
648 >>> class POINT(Structure):
649 ... _fields_ = ("x", c_int), ("y", c_int)
650 ...
651 >>> class MyStruct(Structure):
652 ... _fields_ = [("a", c_int),
653 ... ("b", c_float),
654 ... ("point_array", POINT * 4)]
655 >>>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000656 >>> print(len(MyStruct().point_array))
Georg Brandl116aa622007-08-15 14:28:22 +0000657 4
658 >>>
659
660Instances are created in the usual way, by calling the class::
661
662 arr = TenPointsArrayType()
663 for pt in arr:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000664 print(pt.x, pt.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000665
666The above code print a series of ``0 0`` lines, because the array contents is
667initialized to zeros.
668
669Initializers of the correct type can also be specified::
670
671 >>> from ctypes import *
672 >>> TenIntegers = c_int * 10
673 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000674 >>> print(ii)
Georg Brandl116aa622007-08-15 14:28:22 +0000675 <c_long_Array_10 object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000676 >>> for i in ii: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000677 ...
678 1 2 3 4 5 6 7 8 9 10
679 >>>
680
681
682.. _ctypes-pointers:
683
684Pointers
685^^^^^^^^
686
Georg Brandl8d8f1972009-06-08 13:27:23 +0000687Pointer instances are created by calling the :func:`pointer` function on a
688:mod:`ctypes` type::
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690 >>> from ctypes import *
691 >>> i = c_int(42)
692 >>> pi = pointer(i)
693 >>>
694
695Pointer instances have a ``contents`` attribute which returns the object to
696which the pointer points, the ``i`` object above::
697
698 >>> pi.contents
699 c_long(42)
700 >>>
701
Georg Brandl8d8f1972009-06-08 13:27:23 +0000702Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
Georg Brandl116aa622007-08-15 14:28:22 +0000703new, equivalent object each time you retrieve an attribute::
704
705 >>> pi.contents is i
706 False
707 >>> pi.contents is pi.contents
708 False
709 >>>
710
711Assigning another :class:`c_int` instance to the pointer's contents attribute
712would cause the pointer to point to the memory location where this is stored::
713
714 >>> i = c_int(99)
715 >>> pi.contents = i
716 >>> pi.contents
717 c_long(99)
718 >>>
719
Thomas Heller2fadaa22008-06-16 19:56:33 +0000720.. XXX Document dereferencing pointers, and that it is preferred over the .contents attribute.
721
Georg Brandl116aa622007-08-15 14:28:22 +0000722Pointer instances can also be indexed with integers::
723
724 >>> pi[0]
725 99
726 >>>
727
728Assigning to an integer index changes the pointed to value::
729
Georg Brandl6911e3c2007-09-04 07:15:32 +0000730 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000731 c_long(99)
732 >>> pi[0] = 22
Georg Brandl6911e3c2007-09-04 07:15:32 +0000733 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000734 c_long(22)
735 >>>
736
737It is also possible to use indexes different from 0, but you must know what
738you're doing, just as in C: You can access or change arbitrary memory locations.
739Generally you only use this feature if you receive a pointer from a C function,
740and you *know* that the pointer actually points to an array instead of a single
741item.
742
Georg Brandl8d8f1972009-06-08 13:27:23 +0000743Behind the scenes, the :func:`pointer` function does more than simply create
744pointer instances, it has to create pointer *types* first. This is done with the
745:func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a
746new type::
Georg Brandl116aa622007-08-15 14:28:22 +0000747
748 >>> PI = POINTER(c_int)
749 >>> PI
750 <class 'ctypes.LP_c_long'>
751 >>> PI(42)
752 Traceback (most recent call last):
753 File "<stdin>", line 1, in ?
754 TypeError: expected c_long instead of int
755 >>> PI(c_int(42))
756 <ctypes.LP_c_long object at 0x...>
757 >>>
758
759Calling the pointer type without an argument creates a ``NULL`` pointer.
760``NULL`` pointers have a ``False`` boolean value::
761
762 >>> null_ptr = POINTER(c_int)()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000763 >>> print(bool(null_ptr))
Georg Brandl116aa622007-08-15 14:28:22 +0000764 False
765 >>>
766
Georg Brandl8d8f1972009-06-08 13:27:23 +0000767:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
Thomas Heller2fadaa22008-06-16 19:56:33 +0000768invalid non-\ ``NULL`` pointers would crash Python)::
Georg Brandl116aa622007-08-15 14:28:22 +0000769
770 >>> null_ptr[0]
771 Traceback (most recent call last):
772 ....
773 ValueError: NULL pointer access
774 >>>
775
776 >>> null_ptr[0] = 1234
777 Traceback (most recent call last):
778 ....
779 ValueError: NULL pointer access
780 >>>
781
782
783.. _ctypes-type-conversions:
784
785Type conversions
786^^^^^^^^^^^^^^^^
787
788Usually, ctypes does strict type checking. This means, if you have
789``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
790a member field in a structure definition, only instances of exactly the same
791type are accepted. There are some exceptions to this rule, where ctypes accepts
792other objects. For example, you can pass compatible array instances instead of
793pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
794
795 >>> class Bar(Structure):
796 ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
797 ...
798 >>> bar = Bar()
799 >>> bar.values = (c_int * 3)(1, 2, 3)
800 >>> bar.count = 3
801 >>> for i in range(bar.count):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000802 ... print(bar.values[i])
Georg Brandl116aa622007-08-15 14:28:22 +0000803 ...
804 1
805 2
806 3
807 >>>
808
809To set a POINTER type field to ``NULL``, you can assign ``None``::
810
811 >>> bar.values = None
812 >>>
813
Thomas Heller2fadaa22008-06-16 19:56:33 +0000814.. XXX list other conversions...
Georg Brandl116aa622007-08-15 14:28:22 +0000815
Georg Brandl8d8f1972009-06-08 13:27:23 +0000816Sometimes you have instances of incompatible types. In C, you can cast one type
817into another type. :mod:`ctypes` provides a :func:`cast` function which can be
Georg Brandl116aa622007-08-15 14:28:22 +0000818used in the same way. The ``Bar`` structure defined above accepts
819``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
820but not instances of other types::
821
822 >>> bar.values = (c_byte * 4)()
823 Traceback (most recent call last):
824 File "<stdin>", line 1, in ?
825 TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
826 >>>
827
Georg Brandl8d8f1972009-06-08 13:27:23 +0000828For these cases, the :func:`cast` function is handy.
Georg Brandl116aa622007-08-15 14:28:22 +0000829
Georg Brandl8d8f1972009-06-08 13:27:23 +0000830The :func:`cast` function can be used to cast a ctypes instance into a pointer
831to a different ctypes data type. :func:`cast` takes two parameters, a ctypes
832object that is or can be converted to a pointer of some kind, and a ctypes
833pointer type. It returns an instance of the second argument, which references
834the same memory block as the first argument::
Georg Brandl116aa622007-08-15 14:28:22 +0000835
836 >>> a = (c_byte * 4)()
837 >>> cast(a, POINTER(c_int))
838 <ctypes.LP_c_long object at ...>
839 >>>
840
Georg Brandl8d8f1972009-06-08 13:27:23 +0000841So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the
Georg Brandl116aa622007-08-15 14:28:22 +0000842structure::
843
844 >>> bar = Bar()
845 >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
Georg Brandl6911e3c2007-09-04 07:15:32 +0000846 >>> print(bar.values[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000847 0
848 >>>
849
850
851.. _ctypes-incomplete-types:
852
853Incomplete Types
854^^^^^^^^^^^^^^^^
855
856*Incomplete Types* are structures, unions or arrays whose members are not yet
857specified. In C, they are specified by forward declarations, which are defined
858later::
859
860 struct cell; /* forward declaration */
861
862 struct {
863 char *name;
864 struct cell *next;
865 } cell;
866
867The straightforward translation into ctypes code would be this, but it does not
868work::
869
870 >>> class cell(Structure):
871 ... _fields_ = [("name", c_char_p),
872 ... ("next", POINTER(cell))]
873 ...
874 Traceback (most recent call last):
875 File "<stdin>", line 1, in ?
876 File "<stdin>", line 2, in cell
877 NameError: name 'cell' is not defined
878 >>>
879
880because the new ``class cell`` is not available in the class statement itself.
Georg Brandl8d8f1972009-06-08 13:27:23 +0000881In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_`
Georg Brandl116aa622007-08-15 14:28:22 +0000882attribute later, after the class statement::
883
884 >>> from ctypes import *
885 >>> class cell(Structure):
886 ... pass
887 ...
888 >>> cell._fields_ = [("name", c_char_p),
889 ... ("next", POINTER(cell))]
890 >>>
891
892Lets try it. We create two instances of ``cell``, and let them point to each
893other, and finally follow the pointer chain a few times::
894
895 >>> c1 = cell()
896 >>> c1.name = "foo"
897 >>> c2 = cell()
898 >>> c2.name = "bar"
899 >>> c1.next = pointer(c2)
900 >>> c2.next = pointer(c1)
901 >>> p = c1
902 >>> for i in range(8):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000903 ... print(p.name, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000904 ... p = p.next[0]
905 ...
906 foo bar foo bar foo bar foo bar
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000907 >>>
Georg Brandl116aa622007-08-15 14:28:22 +0000908
909
910.. _ctypes-callback-functions:
911
912Callback functions
913^^^^^^^^^^^^^^^^^^
914
Georg Brandl8d8f1972009-06-08 13:27:23 +0000915:mod:`ctypes` allows to create C callable function pointers from Python callables.
Georg Brandl116aa622007-08-15 14:28:22 +0000916These are sometimes called *callback functions*.
917
918First, you must create a class for the callback function, the class knows the
919calling convention, the return type, and the number and types of arguments this
920function will receive.
921
922The CFUNCTYPE factory function creates types for callback functions using the
923normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
924function creates types for callback functions using the stdcall calling
925convention.
926
927Both of these factory functions are called with the result type as first
928argument, and the callback functions expected argument types as the remaining
929arguments.
930
Georg Brandl8d8f1972009-06-08 13:27:23 +0000931I will present an example here which uses the standard C library's
932:cfunc:`qsort` function, this is used to sort items with the help of a callback
933function. :cfunc:`qsort` will be used to sort an array of integers::
Georg Brandl116aa622007-08-15 14:28:22 +0000934
935 >>> IntArray5 = c_int * 5
936 >>> ia = IntArray5(5, 1, 7, 33, 99)
937 >>> qsort = libc.qsort
938 >>> qsort.restype = None
939 >>>
940
941:func:`qsort` must be called with a pointer to the data to sort, the number of
942items in the data array, the size of one item, and a pointer to the comparison
943function, the callback. The callback will then be called with two pointers to
944items, and it must return a negative integer if the first item is smaller than
945the second, a zero if they are equal, and a positive integer else.
946
947So our callback function receives pointers to integers, and must return an
948integer. First we create the ``type`` for the callback function::
949
950 >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
951 >>>
952
953For the first implementation of the callback function, we simply print the
954arguments we get, and return 0 (incremental development ;-)::
955
956 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000957 ... print("py_cmp_func", a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000958 ... return 0
959 ...
960 >>>
961
962Create the C callable callback::
963
964 >>> cmp_func = CMPFUNC(py_cmp_func)
965 >>>
966
967And we're ready to go::
968
969 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
970 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
971 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
972 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
973 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
974 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
975 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
976 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
977 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
978 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
979 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
980 >>>
981
982We know how to access the contents of a pointer, so lets redefine our callback::
983
984 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000985 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000986 ... return 0
987 ...
988 >>> cmp_func = CMPFUNC(py_cmp_func)
989 >>>
990
991Here is what we get on Windows::
992
993 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
994 py_cmp_func 7 1
995 py_cmp_func 33 1
996 py_cmp_func 99 1
997 py_cmp_func 5 1
998 py_cmp_func 7 5
999 py_cmp_func 33 5
1000 py_cmp_func 99 5
1001 py_cmp_func 7 99
1002 py_cmp_func 33 99
1003 py_cmp_func 7 33
1004 >>>
1005
1006It is funny to see that on linux the sort function seems to work much more
1007efficient, it is doing less comparisons::
1008
1009 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
1010 py_cmp_func 5 1
1011 py_cmp_func 33 99
1012 py_cmp_func 7 33
1013 py_cmp_func 5 7
1014 py_cmp_func 1 7
1015 >>>
1016
1017Ah, we're nearly done! The last step is to actually compare the two items and
1018return a useful result::
1019
1020 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001021 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +00001022 ... return a[0] - b[0]
1023 ...
1024 >>>
1025
1026Final run on Windows::
1027
1028 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
1029 py_cmp_func 33 7
1030 py_cmp_func 99 33
1031 py_cmp_func 5 99
1032 py_cmp_func 1 99
1033 py_cmp_func 33 7
1034 py_cmp_func 1 33
1035 py_cmp_func 5 33
1036 py_cmp_func 5 7
1037 py_cmp_func 1 7
1038 py_cmp_func 5 1
1039 >>>
1040
1041and on Linux::
1042
1043 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1044 py_cmp_func 5 1
1045 py_cmp_func 33 99
1046 py_cmp_func 7 33
1047 py_cmp_func 1 7
1048 py_cmp_func 5 7
1049 >>>
1050
1051It is quite interesting to see that the Windows :func:`qsort` function needs
1052more comparisons than the linux version!
1053
1054As we can easily check, our array is sorted now::
1055
Georg Brandl6911e3c2007-09-04 07:15:32 +00001056 >>> for i in ia: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +00001057 ...
1058 1 5 7 33 99
1059 >>>
1060
1061**Important note for callback functions:**
1062
1063Make sure you keep references to CFUNCTYPE objects as long as they are used from
Georg Brandl8d8f1972009-06-08 13:27:23 +00001064C code. :mod:`ctypes` doesn't, and if you don't, they may be garbage collected,
Georg Brandl116aa622007-08-15 14:28:22 +00001065crashing your program when a callback is made.
1066
1067
1068.. _ctypes-accessing-values-exported-from-dlls:
1069
1070Accessing values exported from dlls
1071^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1072
Thomas Heller2fadaa22008-06-16 19:56:33 +00001073Some shared libraries not only export functions, they also export variables. An
Georg Brandl8d8f1972009-06-08 13:27:23 +00001074example in the Python library itself is the :cdata:`Py_OptimizeFlag`, an integer
1075set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
Georg Brandl116aa622007-08-15 14:28:22 +00001076startup.
1077
Georg Brandl8d8f1972009-06-08 13:27:23 +00001078:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of
Georg Brandl116aa622007-08-15 14:28:22 +00001079the type. *pythonapi* is a predefined symbol giving access to the Python C
1080api::
1081
1082 >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
Georg Brandl6911e3c2007-09-04 07:15:32 +00001083 >>> print(opt_flag)
Georg Brandl116aa622007-08-15 14:28:22 +00001084 c_long(0)
1085 >>>
1086
1087If the interpreter would have been started with :option:`-O`, the sample would
1088have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1089specified.
1090
1091An extended example which also demonstrates the use of pointers accesses the
Georg Brandl8d8f1972009-06-08 13:27:23 +00001092:cdata:`PyImport_FrozenModules` pointer exported by Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001093
Georg Brandl8d8f1972009-06-08 13:27:23 +00001094Quoting the docs for that value:
1095
1096 This pointer is initialized to point to an array of :ctype:`struct _frozen`
1097 records, terminated by one whose members are all *NULL* or zero. When a frozen
1098 module is imported, it is searched in this table. Third-party code could play
1099 tricks with this to provide a dynamically created collection of frozen modules.
Georg Brandl116aa622007-08-15 14:28:22 +00001100
1101So manipulating this pointer could even prove useful. To restrict the example
Georg Brandl8d8f1972009-06-08 13:27:23 +00001102size, we show only how this table can be read with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001103
1104 >>> from ctypes import *
1105 >>>
1106 >>> class struct_frozen(Structure):
1107 ... _fields_ = [("name", c_char_p),
1108 ... ("code", POINTER(c_ubyte)),
1109 ... ("size", c_int)]
1110 ...
1111 >>>
1112
Georg Brandl8d8f1972009-06-08 13:27:23 +00001113We have defined the :ctype:`struct _frozen` data type, so we can get the pointer
1114to the table::
Georg Brandl116aa622007-08-15 14:28:22 +00001115
1116 >>> FrozenTable = POINTER(struct_frozen)
1117 >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1118 >>>
1119
1120Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1121can iterate over it, but we just have to make sure that our loop terminates,
1122because pointers have no size. Sooner or later it would probably crash with an
1123access violation or whatever, so it's better to break out of the loop when we
1124hit the NULL entry::
1125
1126 >>> for item in table:
Georg Brandl6911e3c2007-09-04 07:15:32 +00001127 ... print(item.name, item.size)
Georg Brandl116aa622007-08-15 14:28:22 +00001128 ... if item.name is None:
1129 ... break
1130 ...
1131 __hello__ 104
1132 __phello__ -104
1133 __phello__.spam 104
1134 None 0
1135 >>>
1136
1137The fact that standard Python has a frozen module and a frozen package
Thomas Woutersed03b412007-08-28 21:37:11 +00001138(indicated by the negative size member) is not well known, it is only used for
Georg Brandl116aa622007-08-15 14:28:22 +00001139testing. Try it out with ``import __hello__`` for example.
1140
1141
1142.. _ctypes-surprises:
1143
1144Surprises
1145^^^^^^^^^
1146
Georg Brandl8d8f1972009-06-08 13:27:23 +00001147There are some edges in :mod:`ctypes` where you may be expect something else than
Georg Brandl116aa622007-08-15 14:28:22 +00001148what actually happens.
1149
1150Consider the following example::
1151
1152 >>> from ctypes import *
1153 >>> class POINT(Structure):
1154 ... _fields_ = ("x", c_int), ("y", c_int)
1155 ...
1156 >>> class RECT(Structure):
1157 ... _fields_ = ("a", POINT), ("b", POINT)
1158 ...
1159 >>> p1 = POINT(1, 2)
1160 >>> p2 = POINT(3, 4)
1161 >>> rc = RECT(p1, p2)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001162 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001163 1 2 3 4
1164 >>> # now swap the two points
1165 >>> rc.a, rc.b = rc.b, rc.a
Georg Brandl6911e3c2007-09-04 07:15:32 +00001166 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001167 3 4 3 4
1168 >>>
1169
1170Hm. We certainly expected the last statement to print ``3 4 1 2``. What
Thomas Woutersed03b412007-08-28 21:37:11 +00001171happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
Georg Brandl116aa622007-08-15 14:28:22 +00001172
1173 >>> temp0, temp1 = rc.b, rc.a
1174 >>> rc.a = temp0
1175 >>> rc.b = temp1
1176 >>>
1177
1178Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1179the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1180contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1181contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1182the expected effect.
1183
Thomas Woutersed03b412007-08-28 21:37:11 +00001184Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1185doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
Georg Brandl116aa622007-08-15 14:28:22 +00001186the root-object's underlying buffer.
1187
1188Another example that may behave different from what one would expect is this::
1189
1190 >>> s = c_char_p()
1191 >>> s.value = "abc def ghi"
1192 >>> s.value
1193 'abc def ghi'
1194 >>> s.value is s.value
1195 False
1196 >>>
1197
1198Why is it printing ``False``? ctypes instances are objects containing a memory
Georg Brandl9afde1c2007-11-01 20:32:30 +00001199block plus some :term:`descriptor`\s accessing the contents of the memory.
1200Storing a Python object in the memory block does not store the object itself,
1201instead the ``contents`` of the object is stored. Accessing the contents again
1202constructs a new Python object each time!
Georg Brandl116aa622007-08-15 14:28:22 +00001203
1204
1205.. _ctypes-variable-sized-data-types:
1206
1207Variable-sized data types
1208^^^^^^^^^^^^^^^^^^^^^^^^^
1209
Georg Brandl8d8f1972009-06-08 13:27:23 +00001210:mod:`ctypes` provides some support for variable-sized arrays and structures.
Georg Brandl116aa622007-08-15 14:28:22 +00001211
Georg Brandl8d8f1972009-06-08 13:27:23 +00001212The :func:`resize` function can be used to resize the memory buffer of an
1213existing ctypes object. The function takes the object as first argument, and
1214the requested size in bytes as the second argument. The memory block cannot be
1215made smaller than the natural memory block specified by the objects type, a
1216:exc:`ValueError` is raised if this is tried::
Georg Brandl116aa622007-08-15 14:28:22 +00001217
1218 >>> short_array = (c_short * 4)()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001219 >>> print(sizeof(short_array))
Georg Brandl116aa622007-08-15 14:28:22 +00001220 8
1221 >>> resize(short_array, 4)
1222 Traceback (most recent call last):
1223 ...
1224 ValueError: minimum size is 8
1225 >>> resize(short_array, 32)
1226 >>> sizeof(short_array)
1227 32
1228 >>> sizeof(type(short_array))
1229 8
1230 >>>
1231
1232This is nice and fine, but how would one access the additional elements
1233contained in this array? Since the type still only knows about 4 elements, we
1234get errors accessing other elements::
1235
1236 >>> short_array[:]
1237 [0, 0, 0, 0]
1238 >>> short_array[7]
1239 Traceback (most recent call last):
1240 ...
1241 IndexError: invalid index
1242 >>>
1243
Georg Brandl8d8f1972009-06-08 13:27:23 +00001244Another way to use variable-sized data types with :mod:`ctypes` is to use the
Georg Brandl116aa622007-08-15 14:28:22 +00001245dynamic nature of Python, and (re-)define the data type after the required size
1246is already known, on a case by case basis.
1247
1248
Georg Brandl116aa622007-08-15 14:28:22 +00001249.. _ctypes-ctypes-reference:
1250
1251ctypes reference
1252----------------
1253
1254
1255.. _ctypes-finding-shared-libraries:
1256
1257Finding shared libraries
1258^^^^^^^^^^^^^^^^^^^^^^^^
1259
1260When programming in a compiled language, shared libraries are accessed when
1261compiling/linking a program, and when the program is run.
1262
Georg Brandl8d8f1972009-06-08 13:27:23 +00001263The purpose of the :func:`find_library` function is to locate a library in a way
Georg Brandl116aa622007-08-15 14:28:22 +00001264similar to what the compiler does (on platforms with several versions of a
1265shared library the most recent should be loaded), while the ctypes library
1266loaders act like when a program is run, and call the runtime loader directly.
1267
Georg Brandl8d8f1972009-06-08 13:27:23 +00001268The :mod:`ctypes.util` module provides a function which can help to determine
1269the library to load.
Georg Brandl116aa622007-08-15 14:28:22 +00001270
1271
1272.. data:: find_library(name)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001273 :module: ctypes.util
Georg Brandl116aa622007-08-15 14:28:22 +00001274 :noindex:
1275
1276 Try to find a library and return a pathname. *name* is the library name without
1277 any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1278 is the form used for the posix linker option :option:`-l`). If no library can
1279 be found, returns ``None``.
1280
Thomas Woutersed03b412007-08-28 21:37:11 +00001281The exact functionality is system dependent.
Georg Brandl116aa622007-08-15 14:28:22 +00001282
Georg Brandl8d8f1972009-06-08 13:27:23 +00001283On Linux, :func:`find_library` tries to run external programs (/sbin/ldconfig,
1284gcc, and objdump) to find the library file. It returns the filename of the
1285library file. Here are some examples::
Georg Brandl116aa622007-08-15 14:28:22 +00001286
1287 >>> from ctypes.util import find_library
1288 >>> find_library("m")
1289 'libm.so.6'
1290 >>> find_library("c")
1291 'libc.so.6'
1292 >>> find_library("bz2")
1293 'libbz2.so.1.0'
1294 >>>
1295
Georg Brandl8d8f1972009-06-08 13:27:23 +00001296On OS X, :func:`find_library` tries several predefined naming schemes and paths
1297to locate the library, and returns a full pathname if successful::
Georg Brandl116aa622007-08-15 14:28:22 +00001298
1299 >>> from ctypes.util import find_library
1300 >>> find_library("c")
1301 '/usr/lib/libc.dylib'
1302 >>> find_library("m")
1303 '/usr/lib/libm.dylib'
1304 >>> find_library("bz2")
1305 '/usr/lib/libbz2.dylib'
1306 >>> find_library("AGL")
1307 '/System/Library/Frameworks/AGL.framework/AGL'
1308 >>>
1309
Georg Brandl8d8f1972009-06-08 13:27:23 +00001310On Windows, :func:`find_library` searches along the system search path, and
1311returns the full pathname, but since there is no predefined naming scheme a call
1312like ``find_library("c")`` will fail and return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001313
Georg Brandl8d8f1972009-06-08 13:27:23 +00001314If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
Georg Brandl116aa622007-08-15 14:28:22 +00001315the shared library name at development type, and hardcode that into the wrapper
Georg Brandl8d8f1972009-06-08 13:27:23 +00001316module instead of using :func:`find_library` to locate the library at runtime.
Georg Brandl116aa622007-08-15 14:28:22 +00001317
1318
1319.. _ctypes-loading-shared-libraries:
1320
1321Loading shared libraries
1322^^^^^^^^^^^^^^^^^^^^^^^^
1323
1324There are several ways to loaded shared libraries into the Python process. One
1325way is to instantiate one of the following classes:
1326
1327
Thomas Hellerb795f5282008-06-10 15:26:58 +00001328.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001329
1330 Instances of this class represent loaded shared libraries. Functions in these
1331 libraries use the standard C calling convention, and are assumed to return
1332 ``int``.
1333
1334
Thomas Hellerb795f5282008-06-10 15:26:58 +00001335.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001336
1337 Windows only: Instances of this class represent loaded shared libraries,
1338 functions in these libraries use the ``stdcall`` calling convention, and are
1339 assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1340 values contain information specifying whether the function call failed or
1341 succeeded, together with additional error code. If the return value signals a
1342 failure, an :class:`WindowsError` is automatically raised.
1343
1344
Thomas Hellerb795f5282008-06-10 15:26:58 +00001345.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001346
1347 Windows only: Instances of this class represent loaded shared libraries,
1348 functions in these libraries use the ``stdcall`` calling convention, and are
1349 assumed to return ``int`` by default.
1350
1351 On Windows CE only the standard calling convention is used, for convenience the
1352 :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1353 platform.
1354
Georg Brandl9afde1c2007-11-01 20:32:30 +00001355The Python :term:`global interpreter lock` is released before calling any
1356function exported by these libraries, and reacquired afterwards.
Georg Brandl116aa622007-08-15 14:28:22 +00001357
1358
1359.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1360
1361 Instances of this class behave like :class:`CDLL` instances, except that the
1362 Python GIL is *not* released during the function call, and after the function
1363 execution the Python error flag is checked. If the error flag is set, a Python
1364 exception is raised.
1365
1366 Thus, this is only useful to call Python C api functions directly.
1367
1368All these classes can be instantiated by calling them with at least one
1369argument, the pathname of the shared library. If you have an existing handle to
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001370an already loaded shared library, it can be passed as the ``handle`` named
Georg Brandl116aa622007-08-15 14:28:22 +00001371parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
1372function is used to load the library into the process, and to get a handle to
1373it.
1374
1375The *mode* parameter can be used to specify how the library is loaded. For
Georg Brandl8d8f1972009-06-08 13:27:23 +00001376details, consult the :manpage:`dlopen(3)` manpage, on Windows, *mode* is ignored.
Georg Brandl116aa622007-08-15 14:28:22 +00001377
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001378The *use_errno* parameter, when set to True, enables a ctypes mechanism that
1379allows to access the system :data:`errno` error number in a safe way.
1380:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1381variable; if you call foreign functions created with ``use_errno=True`` then the
1382:data:`errno` value before the function call is swapped with the ctypes private
1383copy, the same happens immediately after the function call.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001384
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001385The function :func:`ctypes.get_errno` returns the value of the ctypes private
1386copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1387to a new value and returns the former value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001388
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001389The *use_last_error* parameter, when set to True, enables the same mechanism for
1390the Windows error code which is managed by the :func:`GetLastError` and
1391:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1392:func:`ctypes.set_last_error` are used to request and change the ctypes private
1393copy of the windows error code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001394
Georg Brandl116aa622007-08-15 14:28:22 +00001395.. data:: RTLD_GLOBAL
1396 :noindex:
1397
1398 Flag to use as *mode* parameter. On platforms where this flag is not available,
1399 it is defined as the integer zero.
1400
1401
1402.. data:: RTLD_LOCAL
1403 :noindex:
1404
1405 Flag to use as *mode* parameter. On platforms where this is not available, it
1406 is the same as *RTLD_GLOBAL*.
1407
1408
1409.. data:: DEFAULT_MODE
1410 :noindex:
1411
1412 The default mode which is used to load shared libraries. On OSX 10.3, this is
1413 *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1414
1415Instances of these classes have no public methods, however :meth:`__getattr__`
Thomas Woutersed03b412007-08-28 21:37:11 +00001416and :meth:`__getitem__` have special behavior: functions exported by the shared
Georg Brandl116aa622007-08-15 14:28:22 +00001417library can be accessed as attributes of by index. Please note that both
1418:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1419repeatedly returns the same object each time.
1420
1421The following public attributes are available, their name starts with an
1422underscore to not clash with exported function names:
1423
1424
1425.. attribute:: PyDLL._handle
1426
1427 The system handle used to access the library.
1428
1429
1430.. attribute:: PyDLL._name
1431
Thomas Woutersed03b412007-08-28 21:37:11 +00001432 The name of the library passed in the constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001433
1434Shared libraries can also be loaded by using one of the prefabricated objects,
1435which are instances of the :class:`LibraryLoader` class, either by calling the
1436:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1437loader instance.
1438
1439
1440.. class:: LibraryLoader(dlltype)
1441
1442 Class which loads shared libraries. ``dlltype`` should be one of the
1443 :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1444
Thomas Woutersed03b412007-08-28 21:37:11 +00001445 :meth:`__getattr__` has special behavior: It allows to load a shared library by
Georg Brandl116aa622007-08-15 14:28:22 +00001446 accessing it as attribute of a library loader instance. The result is cached,
1447 so repeated attribute accesses return the same library each time.
1448
Benjamin Petersone41251e2008-04-25 01:59:09 +00001449 .. method:: LoadLibrary(name)
Georg Brandl116aa622007-08-15 14:28:22 +00001450
Benjamin Petersone41251e2008-04-25 01:59:09 +00001451 Load a shared library into the process and return it. This method always
1452 returns a new instance of the library.
Georg Brandl116aa622007-08-15 14:28:22 +00001453
Georg Brandl116aa622007-08-15 14:28:22 +00001454
Georg Brandl8d8f1972009-06-08 13:27:23 +00001455These prefabricated library loaders are available:
Georg Brandl116aa622007-08-15 14:28:22 +00001456
1457.. data:: cdll
1458 :noindex:
1459
1460 Creates :class:`CDLL` instances.
1461
1462
1463.. data:: windll
1464 :noindex:
1465
1466 Windows only: Creates :class:`WinDLL` instances.
1467
1468
1469.. data:: oledll
1470 :noindex:
1471
1472 Windows only: Creates :class:`OleDLL` instances.
1473
1474
1475.. data:: pydll
1476 :noindex:
1477
1478 Creates :class:`PyDLL` instances.
1479
Georg Brandl8d8f1972009-06-08 13:27:23 +00001480
Georg Brandl116aa622007-08-15 14:28:22 +00001481For accessing the C Python api directly, a ready-to-use Python shared library
1482object is available:
1483
Georg Brandl116aa622007-08-15 14:28:22 +00001484.. data:: pythonapi
1485 :noindex:
1486
1487 An instance of :class:`PyDLL` that exposes Python C api functions as attributes.
1488 Note that all these functions are assumed to return C ``int``, which is of
1489 course not always the truth, so you have to assign the correct :attr:`restype`
1490 attribute to use these functions.
1491
1492
1493.. _ctypes-foreign-functions:
1494
1495Foreign functions
1496^^^^^^^^^^^^^^^^^
1497
1498As explained in the previous section, foreign functions can be accessed as
1499attributes of loaded shared libraries. The function objects created in this way
1500by default accept any number of arguments, accept any ctypes data instances as
1501arguments, and return the default result type specified by the library loader.
1502They are instances of a private class:
1503
1504
1505.. class:: _FuncPtr
1506
1507 Base class for C callable foreign functions.
1508
Benjamin Petersone41251e2008-04-25 01:59:09 +00001509 Instances of foreign functions are also C compatible data types; they
1510 represent C function pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001511
Benjamin Petersone41251e2008-04-25 01:59:09 +00001512 This behavior can be customized by assigning to special attributes of the
1513 foreign function object.
Georg Brandl116aa622007-08-15 14:28:22 +00001514
Benjamin Petersone41251e2008-04-25 01:59:09 +00001515 .. attribute:: restype
Georg Brandl116aa622007-08-15 14:28:22 +00001516
Benjamin Petersone41251e2008-04-25 01:59:09 +00001517 Assign a ctypes type to specify the result type of the foreign function.
1518 Use ``None`` for ``void`` a function not returning anything.
Georg Brandl116aa622007-08-15 14:28:22 +00001519
Benjamin Petersone41251e2008-04-25 01:59:09 +00001520 It is possible to assign a callable Python object that is not a ctypes
1521 type, in this case the function is assumed to return a C ``int``, and the
1522 callable will be called with this integer, allowing to do further
1523 processing or error checking. Using this is deprecated, for more flexible
1524 post processing or error checking use a ctypes data type as
1525 :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001526
Benjamin Petersone41251e2008-04-25 01:59:09 +00001527 .. attribute:: argtypes
Georg Brandl116aa622007-08-15 14:28:22 +00001528
Benjamin Petersone41251e2008-04-25 01:59:09 +00001529 Assign a tuple of ctypes types to specify the argument types that the
1530 function accepts. Functions using the ``stdcall`` calling convention can
1531 only be called with the same number of arguments as the length of this
1532 tuple; functions using the C calling convention accept additional,
1533 unspecified arguments as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001534
Benjamin Petersone41251e2008-04-25 01:59:09 +00001535 When a foreign function is called, each actual argument is passed to the
1536 :meth:`from_param` class method of the items in the :attr:`argtypes`
1537 tuple, this method allows to adapt the actual argument to an object that
1538 the foreign function accepts. For example, a :class:`c_char_p` item in
Georg Brandl8d8f1972009-06-08 13:27:23 +00001539 the :attr:`argtypes` tuple will convert a string passed as argument into
1540 a bytes object using ctypes conversion rules.
Georg Brandl116aa622007-08-15 14:28:22 +00001541
Benjamin Petersone41251e2008-04-25 01:59:09 +00001542 New: It is now possible to put items in argtypes which are not ctypes
1543 types, but each item must have a :meth:`from_param` method which returns a
1544 value usable as argument (integer, string, ctypes instance). This allows
1545 to define adapters that can adapt custom objects as function parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001546
Benjamin Petersone41251e2008-04-25 01:59:09 +00001547 .. attribute:: errcheck
Georg Brandl116aa622007-08-15 14:28:22 +00001548
Benjamin Petersone41251e2008-04-25 01:59:09 +00001549 Assign a Python function or another callable to this attribute. The
1550 callable will be called with three or more arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001551
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001552 .. function:: callable(result, func, arguments)
1553 :noindex:
Georg Brandl8d8f1972009-06-08 13:27:23 +00001554 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001555
Georg Brandl8d8f1972009-06-08 13:27:23 +00001556 *result* is what the foreign function returns, as specified
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001557 by the :attr:`restype` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001558
Georg Brandl8d8f1972009-06-08 13:27:23 +00001559 *func* is the foreign function object itself, this allows
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001560 to reuse the same callable object to check or post process
1561 the results of several functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001562
Georg Brandl8d8f1972009-06-08 13:27:23 +00001563 *arguments* is a tuple containing the parameters originally
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001564 passed to the function call, this allows to specialize the
1565 behavior on the arguments used.
Georg Brandl116aa622007-08-15 14:28:22 +00001566
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001567 The object that this function returns will be returned from the
1568 foreign function call, but it can also check the result value
1569 and raise an exception if the foreign function call failed.
Georg Brandl116aa622007-08-15 14:28:22 +00001570
1571
Georg Brandl8d8f1972009-06-08 13:27:23 +00001572.. exception:: ArgumentError
Georg Brandl116aa622007-08-15 14:28:22 +00001573
1574 This exception is raised when a foreign function call cannot convert one of the
1575 passed arguments.
1576
1577
1578.. _ctypes-function-prototypes:
1579
1580Function prototypes
1581^^^^^^^^^^^^^^^^^^^
1582
1583Foreign functions can also be created by instantiating function prototypes.
1584Function prototypes are similar to function prototypes in C; they describe a
1585function (return type, argument types, calling convention) without defining an
1586implementation. The factory functions must be called with the desired result
1587type and the argument types of the function.
1588
1589
Thomas Hellerb795f5282008-06-10 15:26:58 +00001590.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001591
1592 The returned function prototype creates functions that use the standard C
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001593 calling convention. The function will release the GIL during the call. If
1594 *use_errno* is set to True, the ctypes private copy of the system
Georg Brandla6053b42009-09-01 08:11:14 +00001595 :data:`errno` variable is exchanged with the real :data:`errno` value before
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001596 and after the call; *use_last_error* does the same for the Windows error
1597 code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001598
Georg Brandl116aa622007-08-15 14:28:22 +00001599
Thomas Hellerb795f5282008-06-10 15:26:58 +00001600.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001601
1602 Windows only: The returned function prototype creates functions that use the
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001603 ``stdcall`` calling convention, except on Windows CE where
1604 :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
1605 release the GIL during the call. *use_errno* and *use_last_error* have the
1606 same meaning as above.
Georg Brandl116aa622007-08-15 14:28:22 +00001607
1608
1609.. function:: PYFUNCTYPE(restype, *argtypes)
1610
1611 The returned function prototype creates functions that use the Python calling
1612 convention. The function will *not* release the GIL during the call.
1613
Thomas Heller2fadaa22008-06-16 19:56:33 +00001614Function prototypes created by these factory functions can be instantiated in
1615different ways, depending on the type and number of the parameters in the call:
Georg Brandl116aa622007-08-15 14:28:22 +00001616
1617
Thomas Heller2fadaa22008-06-16 19:56:33 +00001618 .. function:: prototype(address)
1619 :noindex:
1620 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001621
Thomas Heller2fadaa22008-06-16 19:56:33 +00001622 Returns a foreign function at the specified address which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00001623
1624
Thomas Heller2fadaa22008-06-16 19:56:33 +00001625 .. function:: prototype(callable)
1626 :noindex:
1627 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001628
Georg Brandl8d8f1972009-06-08 13:27:23 +00001629 Create a C callable function (a callback function) from a Python *callable*.
Georg Brandl116aa622007-08-15 14:28:22 +00001630
1631
Thomas Heller2fadaa22008-06-16 19:56:33 +00001632 .. function:: prototype(func_spec[, paramflags])
1633 :noindex:
1634 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001635
Georg Brandl8d8f1972009-06-08 13:27:23 +00001636 Returns a foreign function exported by a shared library. *func_spec*
1637 must be a 2-tuple ``(name_or_ordinal, library)``. The first item is the
1638 name of the exported function as string, or the ordinal of the exported
1639 function as small integer. The second item is the shared library
1640 instance.
Georg Brandl116aa622007-08-15 14:28:22 +00001641
1642
Thomas Heller2fadaa22008-06-16 19:56:33 +00001643 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1644 :noindex:
1645 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001646
Georg Brandl8d8f1972009-06-08 13:27:23 +00001647 Returns a foreign function that will call a COM method. *vtbl_index* is
1648 the index into the virtual function table, a small non-negative
1649 integer. *name* is name of the COM method. *iid* is an optional pointer to
1650 the interface identifier which is used in extended error reporting.
Georg Brandl116aa622007-08-15 14:28:22 +00001651
Georg Brandl8d8f1972009-06-08 13:27:23 +00001652 COM methods use a special calling convention: They require a pointer to
1653 the COM interface as first argument, in addition to those parameters that
1654 are specified in the :attr:`argtypes` tuple.
Georg Brandl116aa622007-08-15 14:28:22 +00001655
Thomas Heller2fadaa22008-06-16 19:56:33 +00001656 The optional *paramflags* parameter creates foreign function wrappers with much
1657 more functionality than the features described above.
Georg Brandl116aa622007-08-15 14:28:22 +00001658
Thomas Heller2fadaa22008-06-16 19:56:33 +00001659 *paramflags* must be a tuple of the same length as :attr:`argtypes`.
Georg Brandl116aa622007-08-15 14:28:22 +00001660
Thomas Heller2fadaa22008-06-16 19:56:33 +00001661 Each item in this tuple contains further information about a parameter, it must
1662 be a tuple containing one, two, or three items.
Georg Brandl116aa622007-08-15 14:28:22 +00001663
Thomas Heller2fadaa22008-06-16 19:56:33 +00001664 The first item is an integer containing a combination of direction
1665 flags for the parameter:
Georg Brandl116aa622007-08-15 14:28:22 +00001666
Thomas Heller2fadaa22008-06-16 19:56:33 +00001667 1
1668 Specifies an input parameter to the function.
Georg Brandl116aa622007-08-15 14:28:22 +00001669
Thomas Heller2fadaa22008-06-16 19:56:33 +00001670 2
1671 Output parameter. The foreign function fills in a value.
Georg Brandl116aa622007-08-15 14:28:22 +00001672
Thomas Heller2fadaa22008-06-16 19:56:33 +00001673 4
1674 Input parameter which defaults to the integer zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001675
Thomas Heller2fadaa22008-06-16 19:56:33 +00001676 The optional second item is the parameter name as string. If this is specified,
1677 the foreign function can be called with named parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001678
Thomas Heller2fadaa22008-06-16 19:56:33 +00001679 The optional third item is the default value for this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001680
1681This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
1682that it supports default parameters and named arguments. The C declaration from
1683the windows header file is this::
1684
1685 WINUSERAPI int WINAPI
1686 MessageBoxA(
1687 HWND hWnd ,
1688 LPCSTR lpText,
1689 LPCSTR lpCaption,
1690 UINT uType);
1691
Georg Brandl8d8f1972009-06-08 13:27:23 +00001692Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001693
Thomas Heller2fadaa22008-06-16 19:56:33 +00001694 >>> from ctypes import c_int, WINFUNCTYPE, windll
1695 >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1696 >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
1697 >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1698 >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1699 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001700
1701The MessageBox foreign function can now be called in these ways::
1702
1703 >>> MessageBox()
1704 >>> MessageBox(text="Spam, spam, spam")
1705 >>> MessageBox(flags=2, text="foo bar")
1706 >>>
1707
1708A second example demonstrates output parameters. The win32 ``GetWindowRect``
1709function retrieves the dimensions of a specified window by copying them into
1710``RECT`` structure that the caller has to supply. Here is the C declaration::
1711
1712 WINUSERAPI BOOL WINAPI
1713 GetWindowRect(
1714 HWND hWnd,
1715 LPRECT lpRect);
1716
Georg Brandl8d8f1972009-06-08 13:27:23 +00001717Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001718
Thomas Heller2fadaa22008-06-16 19:56:33 +00001719 >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1720 >>> from ctypes.wintypes import BOOL, HWND, RECT
1721 >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1722 >>> paramflags = (1, "hwnd"), (2, "lprect")
1723 >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1724 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001725
1726Functions with output parameters will automatically return the output parameter
1727value if there is a single one, or a tuple containing the output parameter
1728values when there are more than one, so the GetWindowRect function now returns a
1729RECT instance, when called.
1730
1731Output parameters can be combined with the :attr:`errcheck` protocol to do
1732further output processing and error checking. The win32 ``GetWindowRect`` api
1733function returns a ``BOOL`` to signal success or failure, so this function could
1734do the error checking, and raises an exception when the api call failed::
1735
1736 >>> def errcheck(result, func, args):
1737 ... if not result:
1738 ... raise WinError()
1739 ... return args
Thomas Heller2fadaa22008-06-16 19:56:33 +00001740 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001741 >>> GetWindowRect.errcheck = errcheck
1742 >>>
1743
1744If the :attr:`errcheck` function returns the argument tuple it receives
Georg Brandl8d8f1972009-06-08 13:27:23 +00001745unchanged, :mod:`ctypes` continues the normal processing it does on the output
Georg Brandl116aa622007-08-15 14:28:22 +00001746parameters. If you want to return a tuple of window coordinates instead of a
1747``RECT`` instance, you can retrieve the fields in the function and return them
1748instead, the normal processing will no longer take place::
1749
1750 >>> def errcheck(result, func, args):
1751 ... if not result:
1752 ... raise WinError()
1753 ... rc = args[1]
1754 ... return rc.left, rc.top, rc.bottom, rc.right
Thomas Heller2fadaa22008-06-16 19:56:33 +00001755 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001756 >>> GetWindowRect.errcheck = errcheck
1757 >>>
1758
1759
1760.. _ctypes-utility-functions:
1761
1762Utility functions
1763^^^^^^^^^^^^^^^^^
1764
Georg Brandl116aa622007-08-15 14:28:22 +00001765.. function:: addressof(obj)
1766
Georg Brandl8d8f1972009-06-08 13:27:23 +00001767 Returns the address of the memory buffer as integer. *obj* must be an
Georg Brandl116aa622007-08-15 14:28:22 +00001768 instance of a ctypes type.
1769
1770
1771.. function:: alignment(obj_or_type)
1772
Georg Brandl8d8f1972009-06-08 13:27:23 +00001773 Returns the alignment requirements of a ctypes type. *obj_or_type* must be a
Georg Brandl116aa622007-08-15 14:28:22 +00001774 ctypes type or instance.
1775
1776
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001777.. function:: byref(obj[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +00001778
Georg Brandl8d8f1972009-06-08 13:27:23 +00001779 Returns a light-weight pointer to *obj*, which must be an
1780 instance of a ctypes type. *offset* defaults to zero, and must be
Georg Brandl2ee470f2008-07-16 12:55:28 +00001781 an integer that will be added to the internal pointer value.
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001782
1783 ``byref(obj, offset)`` corresponds to this C code::
1784
1785 (((char *)&obj) + offset)
1786
1787 The returned object can only be used as a foreign function call
1788 parameter. It behaves similar to ``pointer(obj)``, but the
1789 construction is a lot faster.
Georg Brandl116aa622007-08-15 14:28:22 +00001790
1791
1792.. function:: cast(obj, type)
1793
Georg Brandl8d8f1972009-06-08 13:27:23 +00001794 This function is similar to the cast operator in C. It returns a new instance
1795 of *type* which points to the same memory block as *obj*. *type* must be a
1796 pointer type, and *obj* must be an object that can be interpreted as a
Georg Brandl116aa622007-08-15 14:28:22 +00001797 pointer.
1798
1799
Georg Brandl8d8f1972009-06-08 13:27:23 +00001800.. function:: create_string_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001801
1802 This function creates a mutable character buffer. The returned object is a
1803 ctypes array of :class:`c_char`.
1804
Georg Brandl8d8f1972009-06-08 13:27:23 +00001805 *init_or_size* must be an integer which specifies the size of the array, or a
1806 bytes object which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001807
Georg Brandl8d8f1972009-06-08 13:27:23 +00001808 If a bytes object is specified as first argument, the buffer is made one item
1809 larger than its length so that the last element in the array is a NUL
Georg Brandl116aa622007-08-15 14:28:22 +00001810 termination character. An integer can be passed as second argument which allows
Georg Brandl8d8f1972009-06-08 13:27:23 +00001811 to specify the size of the array if the length of the bytes should not be used.
Georg Brandl116aa622007-08-15 14:28:22 +00001812
Georg Brandl8d8f1972009-06-08 13:27:23 +00001813 If the first parameter is a string, it is converted into a bytes object
Georg Brandl116aa622007-08-15 14:28:22 +00001814 according to ctypes conversion rules.
1815
1816
Georg Brandl8d8f1972009-06-08 13:27:23 +00001817.. function:: create_unicode_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001818
1819 This function creates a mutable unicode character buffer. The returned object is
1820 a ctypes array of :class:`c_wchar`.
1821
Georg Brandl8d8f1972009-06-08 13:27:23 +00001822 *init_or_size* must be an integer which specifies the size of the array, or a
1823 string which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001824
Georg Brandl8d8f1972009-06-08 13:27:23 +00001825 If a string is specified as first argument, the buffer is made one item
Georg Brandl116aa622007-08-15 14:28:22 +00001826 larger than the length of the string so that the last element in the array is a
1827 NUL termination character. An integer can be passed as second argument which
1828 allows to specify the size of the array if the length of the string should not
1829 be used.
1830
Georg Brandl8d8f1972009-06-08 13:27:23 +00001831 If the first parameter is a bytes object, it is converted into an unicode string
Georg Brandl116aa622007-08-15 14:28:22 +00001832 according to ctypes conversion rules.
1833
1834
1835.. function:: DllCanUnloadNow()
1836
Thomas Woutersed03b412007-08-28 21:37:11 +00001837 Windows only: This function is a hook which allows to implement in-process COM
Georg Brandl116aa622007-08-15 14:28:22 +00001838 servers with ctypes. It is called from the DllCanUnloadNow function that the
1839 _ctypes extension dll exports.
1840
1841
1842.. function:: DllGetClassObject()
1843
Thomas Woutersed03b412007-08-28 21:37:11 +00001844 Windows only: This function is a hook which allows to implement in-process COM
Georg Brandl116aa622007-08-15 14:28:22 +00001845 servers with ctypes. It is called from the DllGetClassObject function that the
1846 ``_ctypes`` extension dll exports.
1847
Thomas Heller2fadaa22008-06-16 19:56:33 +00001848.. function:: find_library(name)
1849 :module: ctypes.util
1850
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001851 Try to find a library and return a pathname. *name* is the library name
Benjamin Peterson28d88b42009-01-09 03:03:23 +00001852 without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001853 number (this is the form used for the posix linker option :option:`-l`). If
1854 no library can be found, returns ``None``.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001855
1856 The exact functionality is system dependent.
1857
Thomas Heller2fadaa22008-06-16 19:56:33 +00001858
1859.. function:: find_msvcrt()
1860 :module: ctypes.util
1861
1862 Windows only: return the filename of the VC runtype library used
1863 by Python, and by the extension modules. If the name of the
1864 library cannot be determined, ``None`` is returned.
1865
1866 If you need to free memory, for example, allocated by an extension
1867 module with a call to the ``free(void *)``, it is important that you
1868 use the function in the same library that allocated the memory.
1869
Georg Brandl116aa622007-08-15 14:28:22 +00001870.. function:: FormatError([code])
1871
1872 Windows only: Returns a textual description of the error code. If no error code
1873 is specified, the last error code is used by calling the Windows api function
1874 GetLastError.
1875
1876
1877.. function:: GetLastError()
1878
1879 Windows only: Returns the last error code set by Windows in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001880 This function calls the Windows `GetLastError()` function directly,
1881 it does not return the ctypes-private copy of the error code.
Georg Brandl116aa622007-08-15 14:28:22 +00001882
Thomas Hellerb795f5282008-06-10 15:26:58 +00001883.. function:: get_errno()
1884
1885 Returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001886 :data:`errno` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001887
Thomas Hellerb795f5282008-06-10 15:26:58 +00001888.. function:: get_last_error()
1889
1890 Windows only: returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001891 :data:`LastError` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001892
Georg Brandl116aa622007-08-15 14:28:22 +00001893.. function:: memmove(dst, src, count)
1894
1895 Same as the standard C memmove library function: copies *count* bytes from
Georg Brandl8d8f1972009-06-08 13:27:23 +00001896 *src* to *dst*. *dst* and *src* must be integers or ctypes instances that
Georg Brandl116aa622007-08-15 14:28:22 +00001897 can be converted to pointers.
1898
1899
1900.. function:: memset(dst, c, count)
1901
1902 Same as the standard C memset library function: fills the memory block at
1903 address *dst* with *count* bytes of value *c*. *dst* must be an integer
1904 specifying an address, or a ctypes instance.
1905
1906
1907.. function:: POINTER(type)
1908
1909 This factory function creates and returns a new ctypes pointer type. Pointer
1910 types are cached an reused internally, so calling this function repeatedly is
1911 cheap. type must be a ctypes type.
1912
1913
1914.. function:: pointer(obj)
1915
Georg Brandl8d8f1972009-06-08 13:27:23 +00001916 This function creates a new pointer instance, pointing to *obj*. The returned
Georg Brandl116aa622007-08-15 14:28:22 +00001917 object is of the type POINTER(type(obj)).
1918
1919 Note: If you just want to pass a pointer to an object to a foreign function
1920 call, you should use ``byref(obj)`` which is much faster.
1921
1922
1923.. function:: resize(obj, size)
1924
1925 This function resizes the internal memory buffer of obj, which must be an
1926 instance of a ctypes type. It is not possible to make the buffer smaller than
Georg Brandl8d8f1972009-06-08 13:27:23 +00001927 the native size of the objects type, as given by ``sizeof(type(obj))``, but
1928 it is possible to enlarge the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00001929
1930
1931.. function:: set_conversion_mode(encoding, errors)
1932
1933 This function sets the rules that ctypes objects use when converting between
Georg Brandl8d8f1972009-06-08 13:27:23 +00001934 bytes objects and (unicode) strings. *encoding* must be a string specifying an
1935 encoding, like ``'utf-8'`` or ``'mbcs'``, *errors* must be a string specifying
1936 the error handling on encoding/decoding errors. Examples of possible values are
1937 ``'strict'``, ``'replace'``, or ``'ignore'``.
Georg Brandl116aa622007-08-15 14:28:22 +00001938
Georg Brandl8d8f1972009-06-08 13:27:23 +00001939 :func:`set_conversion_mode` returns a 2-tuple containing the previous conversion
Georg Brandl116aa622007-08-15 14:28:22 +00001940 rules. On windows, the initial conversion rules are ``('mbcs', 'ignore')``, on
1941 other systems ``('ascii', 'strict')``.
1942
Georg Brandl8d8f1972009-06-08 13:27:23 +00001943 You can set the *encoding* to ``'undefined'`` to completely disable automatic
1944 conversions.
1945
Georg Brandl116aa622007-08-15 14:28:22 +00001946
Thomas Hellerb795f5282008-06-10 15:26:58 +00001947.. function:: set_errno(value)
1948
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001949 Set the current value of the ctypes-private copy of the system :data:`errno`
1950 variable in the calling thread to *value* and return the previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001951
Georg Brandl8d8f1972009-06-08 13:27:23 +00001952
Thomas Hellerb795f5282008-06-10 15:26:58 +00001953.. function:: set_last_error(value)
1954
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001955 Windows only: set the current value of the ctypes-private copy of the system
1956 :data:`LastError` variable in the calling thread to *value* and return the
1957 previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001958
Georg Brandl8d8f1972009-06-08 13:27:23 +00001959
Georg Brandl116aa622007-08-15 14:28:22 +00001960.. function:: sizeof(obj_or_type)
1961
1962 Returns the size in bytes of a ctypes type or instance memory buffer. Does the
1963 same as the C ``sizeof()`` function.
1964
1965
Georg Brandl8d8f1972009-06-08 13:27:23 +00001966.. function:: string_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001967
Georg Brandl8d8f1972009-06-08 13:27:23 +00001968 This function returns the C string starting at memory address address as a bytes
1969 object. If size is specified, it is used as size, otherwise the string is assumed
1970 to be zero-terminated.
Georg Brandl116aa622007-08-15 14:28:22 +00001971
1972
1973.. function:: WinError(code=None, descr=None)
1974
1975 Windows only: this function is probably the worst-named thing in ctypes. It
Georg Brandl8d8f1972009-06-08 13:27:23 +00001976 creates an instance of WindowsError. If *code* is not specified,
Georg Brandl116aa622007-08-15 14:28:22 +00001977 ``GetLastError`` is called to determine the error code. If ``descr`` is not
Thomas Woutersed03b412007-08-28 21:37:11 +00001978 specified, :func:`FormatError` is called to get a textual description of the
Georg Brandl116aa622007-08-15 14:28:22 +00001979 error.
1980
1981
Georg Brandl8d8f1972009-06-08 13:27:23 +00001982.. function:: wstring_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001983
1984 This function returns the wide character string starting at memory address
Georg Brandl8d8f1972009-06-08 13:27:23 +00001985 *address* as a string. If ``size`` is specified, it is used as the
Georg Brandl116aa622007-08-15 14:28:22 +00001986 number of characters of the string, otherwise the string is assumed to be
1987 zero-terminated.
1988
1989
1990.. _ctypes-data-types:
1991
1992Data types
1993^^^^^^^^^^
1994
1995
1996.. class:: _CData
1997
1998 This non-public class is the common base class of all ctypes data types. Among
1999 other things, all ctypes type instances contain a memory block that hold C
2000 compatible data; the address of the memory block is returned by the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002001 :func:`addressof` helper function. Another instance variable is exposed as
Georg Brandl116aa622007-08-15 14:28:22 +00002002 :attr:`_objects`; this contains other Python objects that need to be kept alive
2003 in case the memory block contains pointers.
2004
Benjamin Petersone41251e2008-04-25 01:59:09 +00002005 Common methods of ctypes data types, these are all class methods (to be
2006 exact, they are methods of the :term:`metaclass`):
Georg Brandl116aa622007-08-15 14:28:22 +00002007
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002008 .. method:: _CData.from_buffer(source[, offset])
2009
2010 This method returns a ctypes instance that shares the buffer of
2011 the ``source`` object. The ``source`` object must support the
2012 writeable buffer interface. The optional ``offset`` parameter
2013 specifies an offset into the source buffer in bytes; the default
2014 is zero. If the source buffer is not large enough a ValueError
2015 is raised.
2016
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002017 .. method:: _CData.from_buffer_copy(source[, offset])
2018
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002019 This method creates a ctypes instance, copying the buffer from
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002020 the source object buffer which must be readable. The optional
Georg Brandl8d8f1972009-06-08 13:27:23 +00002021 *offset* parameter specifies an offset into the source buffer
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002022 in bytes; the default is zero. If the source buffer is not
2023 large enough a ValueError is raised.
2024
Benjamin Petersone41251e2008-04-25 01:59:09 +00002025 .. method:: from_address(address)
Georg Brandl116aa622007-08-15 14:28:22 +00002026
Benjamin Petersone41251e2008-04-25 01:59:09 +00002027 This method returns a ctypes type instance using the memory specified by
2028 address which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00002029
Benjamin Petersone41251e2008-04-25 01:59:09 +00002030 .. method:: from_param(obj)
Georg Brandl116aa622007-08-15 14:28:22 +00002031
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002032 This method adapts *obj* to a ctypes type. It is called with the actual
2033 object used in a foreign function call when the type is present in the
2034 foreign function's :attr:`argtypes` tuple; it must return an object that
2035 can be used as a function call parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00002036
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002037 All ctypes data types have a default implementation of this classmethod
Georg Brandl8d8f1972009-06-08 13:27:23 +00002038 that normally returns *obj* if that is an instance of the type. Some
Benjamin Petersone41251e2008-04-25 01:59:09 +00002039 types accept other objects as well.
Georg Brandl116aa622007-08-15 14:28:22 +00002040
Benjamin Petersone41251e2008-04-25 01:59:09 +00002041 .. method:: in_dll(library, name)
Georg Brandl116aa622007-08-15 14:28:22 +00002042
Benjamin Petersone41251e2008-04-25 01:59:09 +00002043 This method returns a ctypes type instance exported by a shared
2044 library. *name* is the name of the symbol that exports the data, *library*
2045 is the loaded shared library.
Georg Brandl116aa622007-08-15 14:28:22 +00002046
Benjamin Petersone41251e2008-04-25 01:59:09 +00002047 Common instance variables of ctypes data types:
Georg Brandl116aa622007-08-15 14:28:22 +00002048
Benjamin Petersone41251e2008-04-25 01:59:09 +00002049 .. attribute:: _b_base_
Georg Brandl116aa622007-08-15 14:28:22 +00002050
Benjamin Petersone41251e2008-04-25 01:59:09 +00002051 Sometimes ctypes data instances do not own the memory block they contain,
2052 instead they share part of the memory block of a base object. The
2053 :attr:`_b_base_` read-only member is the root ctypes object that owns the
2054 memory block.
Georg Brandl116aa622007-08-15 14:28:22 +00002055
Benjamin Petersone41251e2008-04-25 01:59:09 +00002056 .. attribute:: _b_needsfree_
Georg Brandl116aa622007-08-15 14:28:22 +00002057
Benjamin Petersone41251e2008-04-25 01:59:09 +00002058 This read-only variable is true when the ctypes data instance has
2059 allocated the memory block itself, false otherwise.
2060
Benjamin Petersone41251e2008-04-25 01:59:09 +00002061 .. attribute:: _objects
2062
2063 This member is either ``None`` or a dictionary containing Python objects
2064 that need to be kept alive so that the memory block contents is kept
2065 valid. This object is only exposed for debugging; never modify the
2066 contents of this dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002067
2068
2069.. _ctypes-fundamental-data-types-2:
2070
2071Fundamental data types
2072^^^^^^^^^^^^^^^^^^^^^^
2073
Georg Brandl116aa622007-08-15 14:28:22 +00002074.. class:: _SimpleCData
2075
Benjamin Peterson35e8c462008-04-24 02:34:53 +00002076 This non-public class is the base class of all fundamental ctypes data
2077 types. It is mentioned here because it contains the common attributes of the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002078 fundamental ctypes data types. :class:`_SimpleCData` is a subclass of
2079 :class:`_CData`, so it inherits their methods and attributes. ctypes data
2080 types that are not and do not contain pointers can now be pickled.
Thomas Heller13394e92008-02-13 20:40:44 +00002081
Benjamin Petersone41251e2008-04-25 01:59:09 +00002082 Instances have a single attribute:
Georg Brandl116aa622007-08-15 14:28:22 +00002083
Benjamin Petersone41251e2008-04-25 01:59:09 +00002084 .. attribute:: value
Georg Brandl116aa622007-08-15 14:28:22 +00002085
Benjamin Petersone41251e2008-04-25 01:59:09 +00002086 This attribute contains the actual value of the instance. For integer and
2087 pointer types, it is an integer, for character types, it is a single
Georg Brandl8d8f1972009-06-08 13:27:23 +00002088 character bytes object or string, for character pointer types it is a
2089 Python bytes object or string.
Georg Brandl116aa622007-08-15 14:28:22 +00002090
Benjamin Petersone41251e2008-04-25 01:59:09 +00002091 When the ``value`` attribute is retrieved from a ctypes instance, usually
Georg Brandl8d8f1972009-06-08 13:27:23 +00002092 a new object is returned each time. :mod:`ctypes` does *not* implement
Benjamin Petersone41251e2008-04-25 01:59:09 +00002093 original object return, always a new object is constructed. The same is
2094 true for all other ctypes object instances.
Georg Brandl116aa622007-08-15 14:28:22 +00002095
Georg Brandl8d8f1972009-06-08 13:27:23 +00002096
Georg Brandl116aa622007-08-15 14:28:22 +00002097Fundamental data types, when returned as foreign function call results, or, for
2098example, by retrieving structure field members or array items, are transparently
2099converted to native Python types. In other words, if a foreign function has a
Georg Brandl8d8f1972009-06-08 13:27:23 +00002100:attr:`restype` of :class:`c_char_p`, you will always receive a Python bytes
2101object, *not* a :class:`c_char_p` instance.
2102
2103.. XXX above is false, it actually returns a Unicode string
Georg Brandl116aa622007-08-15 14:28:22 +00002104
Thomas Woutersed03b412007-08-28 21:37:11 +00002105Subclasses of fundamental data types do *not* inherit this behavior. So, if a
Georg Brandl116aa622007-08-15 14:28:22 +00002106foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2107receive an instance of this subclass from the function call. Of course, you can
2108get the value of the pointer by accessing the ``value`` attribute.
2109
2110These are the fundamental ctypes data types:
2111
Georg Brandl116aa622007-08-15 14:28:22 +00002112.. class:: c_byte
2113
2114 Represents the C signed char datatype, and interprets the value as small
2115 integer. The constructor accepts an optional integer initializer; no overflow
2116 checking is done.
2117
2118
2119.. class:: c_char
2120
2121 Represents the C char datatype, and interprets the value as a single character.
2122 The constructor accepts an optional string initializer, the length of the string
2123 must be exactly one character.
2124
2125
2126.. class:: c_char_p
2127
2128 Represents the C char \* datatype, which must be a pointer to a zero-terminated
Georg Brandl8d8f1972009-06-08 13:27:23 +00002129 string. The constructor accepts an integer address, or a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +00002130
2131
2132.. class:: c_double
2133
2134 Represents the C double datatype. The constructor accepts an optional float
2135 initializer.
2136
2137
Thomas Wouters89d996e2007-09-08 17:39:28 +00002138.. class:: c_longdouble
2139
2140 Represents the C long double datatype. The constructor accepts an
2141 optional float initializer. On platforms where ``sizeof(long
2142 double) == sizeof(double)`` it is an alias to :class:`c_double`.
2143
Georg Brandl116aa622007-08-15 14:28:22 +00002144.. class:: c_float
2145
Thomas Wouters89d996e2007-09-08 17:39:28 +00002146 Represents the C float datatype. The constructor accepts an optional float
Georg Brandl116aa622007-08-15 14:28:22 +00002147 initializer.
2148
2149
2150.. class:: c_int
2151
2152 Represents the C signed int datatype. The constructor accepts an optional
2153 integer initializer; no overflow checking is done. On platforms where
2154 ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
2155
2156
2157.. class:: c_int8
2158
2159 Represents the C 8-bit ``signed int`` datatype. Usually an alias for
2160 :class:`c_byte`.
2161
2162
2163.. class:: c_int16
2164
2165 Represents the C 16-bit signed int datatype. Usually an alias for
2166 :class:`c_short`.
2167
2168
2169.. class:: c_int32
2170
2171 Represents the C 32-bit signed int datatype. Usually an alias for
2172 :class:`c_int`.
2173
2174
2175.. class:: c_int64
2176
2177 Represents the C 64-bit ``signed int`` datatype. Usually an alias for
2178 :class:`c_longlong`.
2179
2180
2181.. class:: c_long
2182
2183 Represents the C ``signed long`` datatype. The constructor accepts an optional
2184 integer initializer; no overflow checking is done.
2185
2186
2187.. class:: c_longlong
2188
2189 Represents the C ``signed long long`` datatype. The constructor accepts an
2190 optional integer initializer; no overflow checking is done.
2191
2192
2193.. class:: c_short
2194
2195 Represents the C ``signed short`` datatype. The constructor accepts an optional
2196 integer initializer; no overflow checking is done.
2197
2198
2199.. class:: c_size_t
2200
2201 Represents the C ``size_t`` datatype.
2202
2203
2204.. class:: c_ubyte
2205
2206 Represents the C ``unsigned char`` datatype, it interprets the value as small
2207 integer. The constructor accepts an optional integer initializer; no overflow
2208 checking is done.
2209
2210
2211.. class:: c_uint
2212
2213 Represents the C ``unsigned int`` datatype. The constructor accepts an optional
2214 integer initializer; no overflow checking is done. On platforms where
2215 ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
2216
2217
2218.. class:: c_uint8
2219
2220 Represents the C 8-bit unsigned int datatype. Usually an alias for
2221 :class:`c_ubyte`.
2222
2223
2224.. class:: c_uint16
2225
2226 Represents the C 16-bit unsigned int datatype. Usually an alias for
2227 :class:`c_ushort`.
2228
2229
2230.. class:: c_uint32
2231
2232 Represents the C 32-bit unsigned int datatype. Usually an alias for
2233 :class:`c_uint`.
2234
2235
2236.. class:: c_uint64
2237
2238 Represents the C 64-bit unsigned int datatype. Usually an alias for
2239 :class:`c_ulonglong`.
2240
2241
2242.. class:: c_ulong
2243
2244 Represents the C ``unsigned long`` datatype. The constructor accepts an optional
2245 integer initializer; no overflow checking is done.
2246
2247
2248.. class:: c_ulonglong
2249
2250 Represents the C ``unsigned long long`` datatype. The constructor accepts an
2251 optional integer initializer; no overflow checking is done.
2252
2253
2254.. class:: c_ushort
2255
2256 Represents the C ``unsigned short`` datatype. The constructor accepts an
2257 optional integer initializer; no overflow checking is done.
2258
2259
2260.. class:: c_void_p
2261
2262 Represents the C ``void *`` type. The value is represented as integer. The
2263 constructor accepts an optional integer initializer.
2264
2265
2266.. class:: c_wchar
2267
2268 Represents the C ``wchar_t`` datatype, and interprets the value as a single
2269 character unicode string. The constructor accepts an optional string
2270 initializer, the length of the string must be exactly one character.
2271
2272
2273.. class:: c_wchar_p
2274
2275 Represents the C ``wchar_t *`` datatype, which must be a pointer to a
2276 zero-terminated wide character string. The constructor accepts an integer
2277 address, or a string.
2278
2279
2280.. class:: c_bool
2281
2282 Represent the C ``bool`` datatype (more accurately, _Bool from C99). Its value
2283 can be True or False, and the constructor accepts any object that has a truth
2284 value.
2285
Georg Brandl116aa622007-08-15 14:28:22 +00002286
2287.. class:: HRESULT
2288
2289 Windows only: Represents a :class:`HRESULT` value, which contains success or
2290 error information for a function or method call.
2291
2292
2293.. class:: py_object
2294
2295 Represents the C ``PyObject *`` datatype. Calling this without an argument
2296 creates a ``NULL`` ``PyObject *`` pointer.
2297
2298The ``ctypes.wintypes`` module provides quite some other Windows specific data
2299types, for example ``HWND``, ``WPARAM``, or ``DWORD``. Some useful structures
2300like ``MSG`` or ``RECT`` are also defined.
2301
2302
2303.. _ctypes-structured-data-types:
2304
2305Structured data types
2306^^^^^^^^^^^^^^^^^^^^^
2307
2308
2309.. class:: Union(*args, **kw)
2310
2311 Abstract base class for unions in native byte order.
2312
2313
2314.. class:: BigEndianStructure(*args, **kw)
2315
2316 Abstract base class for structures in *big endian* byte order.
2317
2318
2319.. class:: LittleEndianStructure(*args, **kw)
2320
2321 Abstract base class for structures in *little endian* byte order.
2322
2323Structures with non-native byte order cannot contain pointer type fields, or any
2324other data types containing pointer type fields.
2325
2326
2327.. class:: Structure(*args, **kw)
2328
2329 Abstract base class for structures in *native* byte order.
2330
Benjamin Petersone41251e2008-04-25 01:59:09 +00002331 Concrete structure and union types must be created by subclassing one of these
Georg Brandl8d8f1972009-06-08 13:27:23 +00002332 types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
Benjamin Petersone41251e2008-04-25 01:59:09 +00002333 create :term:`descriptor`\s which allow reading and writing the fields by direct
2334 attribute accesses. These are the
Georg Brandl116aa622007-08-15 14:28:22 +00002335
2336
Benjamin Petersone41251e2008-04-25 01:59:09 +00002337 .. attribute:: _fields_
Georg Brandl116aa622007-08-15 14:28:22 +00002338
Benjamin Petersone41251e2008-04-25 01:59:09 +00002339 A sequence defining the structure fields. The items must be 2-tuples or
2340 3-tuples. The first item is the name of the field, the second item
2341 specifies the type of the field; it can be any ctypes data type.
Georg Brandl116aa622007-08-15 14:28:22 +00002342
Benjamin Petersone41251e2008-04-25 01:59:09 +00002343 For integer type fields like :class:`c_int`, a third optional item can be
2344 given. It must be a small positive integer defining the bit width of the
2345 field.
Georg Brandl116aa622007-08-15 14:28:22 +00002346
Benjamin Petersone41251e2008-04-25 01:59:09 +00002347 Field names must be unique within one structure or union. This is not
2348 checked, only one field can be accessed when names are repeated.
Georg Brandl116aa622007-08-15 14:28:22 +00002349
Benjamin Petersone41251e2008-04-25 01:59:09 +00002350 It is possible to define the :attr:`_fields_` class variable *after* the
2351 class statement that defines the Structure subclass, this allows to create
2352 data types that directly or indirectly reference themselves::
Georg Brandl116aa622007-08-15 14:28:22 +00002353
Benjamin Petersone41251e2008-04-25 01:59:09 +00002354 class List(Structure):
2355 pass
2356 List._fields_ = [("pnext", POINTER(List)),
2357 ...
2358 ]
Georg Brandl116aa622007-08-15 14:28:22 +00002359
Benjamin Petersone41251e2008-04-25 01:59:09 +00002360 The :attr:`_fields_` class variable must, however, be defined before the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002361 type is first used (an instance is created, :func:`sizeof` is called on it,
Benjamin Petersone41251e2008-04-25 01:59:09 +00002362 and so on). Later assignments to the :attr:`_fields_` class variable will
2363 raise an AttributeError.
Georg Brandl116aa622007-08-15 14:28:22 +00002364
Benjamin Petersone41251e2008-04-25 01:59:09 +00002365 Structure and union subclass constructors accept both positional and named
2366 arguments. Positional arguments are used to initialize the fields in the
2367 same order as they appear in the :attr:`_fields_` definition, named
2368 arguments are used to initialize the fields with the corresponding name.
Georg Brandl116aa622007-08-15 14:28:22 +00002369
Benjamin Petersone41251e2008-04-25 01:59:09 +00002370 It is possible to defined sub-subclasses of structure types, they inherit
2371 the fields of the base class plus the :attr:`_fields_` defined in the
2372 sub-subclass, if any.
Georg Brandl116aa622007-08-15 14:28:22 +00002373
2374
Benjamin Petersone41251e2008-04-25 01:59:09 +00002375 .. attribute:: _pack_
Georg Brandl116aa622007-08-15 14:28:22 +00002376
Benjamin Petersone41251e2008-04-25 01:59:09 +00002377 An optional small integer that allows to override the alignment of
2378 structure fields in the instance. :attr:`_pack_` must already be defined
2379 when :attr:`_fields_` is assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002380
2381
Benjamin Petersone41251e2008-04-25 01:59:09 +00002382 .. attribute:: _anonymous_
Georg Brandl116aa622007-08-15 14:28:22 +00002383
Benjamin Petersone41251e2008-04-25 01:59:09 +00002384 An optional sequence that lists the names of unnamed (anonymous) fields.
2385 ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
2386 otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002387
Benjamin Petersone41251e2008-04-25 01:59:09 +00002388 The fields listed in this variable must be structure or union type fields.
Georg Brandl8d8f1972009-06-08 13:27:23 +00002389 :mod:`ctypes` will create descriptors in the structure type that allows to
Benjamin Petersone41251e2008-04-25 01:59:09 +00002390 access the nested fields directly, without the need to create the
2391 structure or union field.
Georg Brandl116aa622007-08-15 14:28:22 +00002392
Benjamin Petersone41251e2008-04-25 01:59:09 +00002393 Here is an example type (Windows)::
Georg Brandl116aa622007-08-15 14:28:22 +00002394
Benjamin Petersone41251e2008-04-25 01:59:09 +00002395 class _U(Union):
2396 _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2397 ("lpadesc", POINTER(ARRAYDESC)),
2398 ("hreftype", HREFTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002399
Benjamin Petersone41251e2008-04-25 01:59:09 +00002400 class TYPEDESC(Structure):
Benjamin Petersonb58dda72009-01-18 22:27:04 +00002401 _anonymous_ = ("u",)
Benjamin Petersone41251e2008-04-25 01:59:09 +00002402 _fields_ = [("u", _U),
2403 ("vt", VARTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002404
Georg Brandl116aa622007-08-15 14:28:22 +00002405
Benjamin Petersone41251e2008-04-25 01:59:09 +00002406 The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2407 specifies which one of the union fields is valid. Since the ``u`` field
2408 is defined as anonymous field, it is now possible to access the members
2409 directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2410 are equivalent, but the former is faster since it does not need to create
2411 a temporary union instance::
Georg Brandl116aa622007-08-15 14:28:22 +00002412
Benjamin Petersone41251e2008-04-25 01:59:09 +00002413 td = TYPEDESC()
2414 td.vt = VT_PTR
2415 td.lptdesc = POINTER(some_type)
2416 td.u.lptdesc = POINTER(some_type)
Georg Brandl116aa622007-08-15 14:28:22 +00002417
2418It is possible to defined sub-subclasses of structures, they inherit the fields
2419of the base class. If the subclass definition has a separate :attr:`_fields_`
2420variable, the fields specified in this are appended to the fields of the base
2421class.
2422
2423Structure and union constructors accept both positional and keyword arguments.
2424Positional arguments are used to initialize member fields in the same order as
2425they are appear in :attr:`_fields_`. Keyword arguments in the constructor are
2426interpreted as attribute assignments, so they will initialize :attr:`_fields_`
2427with the same name, or create new attributes for names not present in
2428:attr:`_fields_`.
2429
2430
2431.. _ctypes-arrays-pointers:
2432
2433Arrays and pointers
2434^^^^^^^^^^^^^^^^^^^
2435
2436Not yet written - please see the sections :ref:`ctypes-pointers` and
2437section :ref:`ctypes-arrays` in the tutorial.
2438