blob: fce59135ace261ba5876bfb8c392d3af7c31391d [file] [log] [blame]
Georg Brandl71515ca2009-05-17 12:29:12 +00001:mod:`ctypes` --- A foreign function library for Python
2=======================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: ctypes
5 :synopsis: A foreign function library for Python.
6.. moduleauthor:: Thomas Heller <theller@python.net>
7
8
Georg Brandl1d837bc2009-12-29 11:24:00 +00009:mod:`ctypes` is a foreign function library for Python. It provides C compatible
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000010data types, and allows calling functions in DLLs or shared libraries. It can be
Georg Brandl116aa622007-08-15 14:28:22 +000011used to wrap these libraries in pure Python.
12
13
14.. _ctypes-ctypes-tutorial:
15
16ctypes tutorial
17---------------
18
Georg Brandl1d837bc2009-12-29 11:24:00 +000019Note: The code samples in this tutorial use :mod:`doctest` to make sure that
20they actually work. Since some code samples behave differently under Linux,
21Windows, or Mac OS X, they contain doctest directives in comments.
Georg Brandl116aa622007-08-15 14:28:22 +000022
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000023Note: Some code samples reference the ctypes :class:`c_int` type. This type is
24an alias for the :class:`c_long` type on 32-bit systems. So, you should not be
Georg Brandl116aa622007-08-15 14:28:22 +000025confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
26they are actually the same type.
27
28
29.. _ctypes-loading-dynamic-link-libraries:
30
31Loading dynamic link libraries
32^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
33
Georg Brandl8d8f1972009-06-08 13:27:23 +000034:mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll*
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000035objects, for loading dynamic link libraries.
Georg Brandl116aa622007-08-15 14:28:22 +000036
37You load libraries by accessing them as attributes of these objects. *cdll*
38loads libraries which export functions using the standard ``cdecl`` calling
39convention, while *windll* libraries call functions using the ``stdcall``
40calling convention. *oledll* also uses the ``stdcall`` calling convention, and
Georg Brandl60203b42010-10-06 10:11:56 +000041assumes the functions return a Windows :c:type:`HRESULT` error code. The error
Georg Brandl1d837bc2009-12-29 11:24:00 +000042code is used to automatically raise a :class:`WindowsError` exception when the
43function call fails.
Georg Brandl116aa622007-08-15 14:28:22 +000044
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
Georg Brandl1d837bc2009-12-29 11:24:00 +0000112identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
113:func:`getattr` to retrieve the function::
Georg Brandl116aa622007-08-15 14:28:22 +0000114
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 Brandl1d837bc2009-12-29 11:24:00 +0000152:mod:`ctypes` tries to protect you from calling functions with the wrong number
153of arguments or the wrong calling convention. Unfortunately this only works on
Georg Brandl116aa622007-08-15 14:28:22 +0000154Windows. 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 Brandl1d837bc2009-12-29 11:24:00 +0000195There are, however, enough ways to crash Python with :mod:`ctypes`, so you
196should be careful anyway.
Georg Brandl116aa622007-08-15 14:28:22 +0000197
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 Brandl1d837bc2009-12-29 11:24:00 +0000200``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are passed
Georg Brandl60203b42010-10-06 10:11:56 +0000201as pointer to the memory block that contains their data (:c:type:`char *` or
202:c:type:`wchar_t *`). Python integers are passed as the platforms default C
203:c:type:`int` type, their value is masked to fit into the C type.
Georg Brandl116aa622007-08-15 14:28:22 +0000204
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
Georg Brandl60203b42010-10-06 10:11:56 +0000216+----------------------+------------------------------------------+----------------------------+
217| ctypes type | C type | Python type |
218+======================+==========================================+============================+
Georg Brandlecdd63f2011-01-19 20:05:49 +0000219| :class:`c_bool` | :c:type:`_Bool` | bool (1) |
220+----------------------+------------------------------------------+----------------------------+
Georg Brandl60203b42010-10-06 10:11:56 +0000221| :class:`c_char` | :c:type:`char` | 1-character bytes object |
222+----------------------+------------------------------------------+----------------------------+
223| :class:`c_wchar` | :c:type:`wchar_t` | 1-character string |
224+----------------------+------------------------------------------+----------------------------+
225| :class:`c_byte` | :c:type:`char` | int |
226+----------------------+------------------------------------------+----------------------------+
227| :class:`c_ubyte` | :c:type:`unsigned char` | int |
228+----------------------+------------------------------------------+----------------------------+
229| :class:`c_short` | :c:type:`short` | int |
230+----------------------+------------------------------------------+----------------------------+
231| :class:`c_ushort` | :c:type:`unsigned short` | int |
232+----------------------+------------------------------------------+----------------------------+
233| :class:`c_int` | :c:type:`int` | int |
234+----------------------+------------------------------------------+----------------------------+
235| :class:`c_uint` | :c:type:`unsigned int` | int |
236+----------------------+------------------------------------------+----------------------------+
237| :class:`c_long` | :c:type:`long` | int |
238+----------------------+------------------------------------------+----------------------------+
239| :class:`c_ulong` | :c:type:`unsigned long` | int |
240+----------------------+------------------------------------------+----------------------------+
241| :class:`c_longlong` | :c:type:`__int64` or :c:type:`long long` | int |
242+----------------------+------------------------------------------+----------------------------+
243| :class:`c_ulonglong` | :c:type:`unsigned __int64` or | int |
244| | :c:type:`unsigned long long` | |
245+----------------------+------------------------------------------+----------------------------+
246| :class:`c_float` | :c:type:`float` | float |
247+----------------------+------------------------------------------+----------------------------+
248| :class:`c_double` | :c:type:`double` | float |
249+----------------------+------------------------------------------+----------------------------+
250| :class:`c_longdouble`| :c:type:`long double` | float |
251+----------------------+------------------------------------------+----------------------------+
252| :class:`c_char_p` | :c:type:`char *` (NUL terminated) | bytes object or ``None`` |
253+----------------------+------------------------------------------+----------------------------+
254| :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | string or ``None`` |
255+----------------------+------------------------------------------+----------------------------+
256| :class:`c_void_p` | :c:type:`void *` | int or ``None`` |
257+----------------------+------------------------------------------+----------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000258
Georg Brandlecdd63f2011-01-19 20:05:49 +0000259(1)
260 The constructor accepts any object with a truth value.
261
Georg Brandl116aa622007-08-15 14:28:22 +0000262All these types can be created by calling them with an optional initializer of
263the correct type and value::
264
265 >>> c_int()
266 c_long(0)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000267 >>> c_wchar_p("Hello, World")
268 c_wchar_p('Hello, World')
Georg Brandl116aa622007-08-15 14:28:22 +0000269 >>> c_ushort(-3)
270 c_ushort(65533)
271 >>>
272
273Since these types are mutable, their value can also be changed afterwards::
274
275 >>> i = c_int(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000276 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000277 c_long(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000278 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000279 42
280 >>> i.value = -99
Georg Brandl6911e3c2007-09-04 07:15:32 +0000281 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000282 -99
283 >>>
284
285Assigning a new value to instances of the pointer types :class:`c_char_p`,
286:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
287point to, *not the contents* of the memory block (of course not, because Python
Georg Brandl8d8f1972009-06-08 13:27:23 +0000288bytes objects are immutable)::
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290 >>> s = "Hello, World"
Georg Brandl8d8f1972009-06-08 13:27:23 +0000291 >>> c_s = c_wchar_p(s)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000292 >>> print(c_s)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000293 c_wchar_p('Hello, World')
Georg Brandl116aa622007-08-15 14:28:22 +0000294 >>> c_s.value = "Hi, there"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000295 >>> print(c_s)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000296 c_wchar_p('Hi, there')
297 >>> print(s) # first object is unchanged
Georg Brandl116aa622007-08-15 14:28:22 +0000298 Hello, World
299 >>>
300
301You should be careful, however, not to pass them to functions expecting pointers
302to mutable memory. If you need mutable memory blocks, ctypes has a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000303:func:`create_string_buffer` function which creates these in various ways. The
Georg Brandl116aa622007-08-15 14:28:22 +0000304current memory block contents can be accessed (or changed) with the ``raw``
305property; if you want to access it as NUL terminated string, use the ``value``
306property::
307
308 >>> from ctypes import *
Georg Brandl8d8f1972009-06-08 13:27:23 +0000309 >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
Georg Brandl6911e3c2007-09-04 07:15:32 +0000310 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000311 3 b'\x00\x00\x00'
312 >>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string
Georg Brandl6911e3c2007-09-04 07:15:32 +0000313 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000314 6 b'Hello\x00'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000315 >>> print(repr(p.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000316 b'Hello'
317 >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000318 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000319 10 b'Hello\x00\x00\x00\x00\x00'
320 >>> p.value = b"Hi"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000321 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000322 10 b'Hi\x00lo\x00\x00\x00\x00\x00'
Georg Brandl116aa622007-08-15 14:28:22 +0000323 >>>
324
Georg Brandl1d837bc2009-12-29 11:24:00 +0000325The :func:`create_string_buffer` function replaces the :func:`c_buffer` function
326(which is still available as an alias), as well as the :func:`c_string` function
Georg Brandl8d8f1972009-06-08 13:27:23 +0000327from earlier ctypes releases. To create a mutable memory block containing
Georg Brandl60203b42010-10-06 10:11:56 +0000328unicode characters of the C type :c:type:`wchar_t` use the
Georg Brandl8d8f1972009-06-08 13:27:23 +0000329:func:`create_unicode_buffer` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331
332.. _ctypes-calling-functions-continued:
333
334Calling functions, continued
335^^^^^^^^^^^^^^^^^^^^^^^^^^^^
336
337Note that printf prints to the real standard output channel, *not* to
Georg Brandl8d8f1972009-06-08 13:27:23 +0000338:data:`sys.stdout`, so these examples will only work at the console prompt, not
339from within *IDLE* or *PythonWin*::
Georg Brandl116aa622007-08-15 14:28:22 +0000340
341 >>> printf = libc.printf
Georg Brandl8d8f1972009-06-08 13:27:23 +0000342 >>> printf(b"Hello, %s\n", b"World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000343 Hello, World!
344 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000345 >>> printf(b"Hello, %S\n", "World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000346 Hello, World!
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000347 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000348 >>> printf(b"%d bottles of beer\n", 42)
Georg Brandl116aa622007-08-15 14:28:22 +0000349 42 bottles of beer
350 19
Georg Brandl8d8f1972009-06-08 13:27:23 +0000351 >>> printf(b"%f bottles of beer\n", 42.5)
Georg Brandl116aa622007-08-15 14:28:22 +0000352 Traceback (most recent call last):
353 File "<stdin>", line 1, in ?
354 ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
355 >>>
356
357As has been mentioned before, all Python types except integers, strings, and
Georg Brandl8d8f1972009-06-08 13:27:23 +0000358bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so
Georg Brandl116aa622007-08-15 14:28:22 +0000359that they can be converted to the required C data type::
360
Georg Brandl8d8f1972009-06-08 13:27:23 +0000361 >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000362 An int 1234, a double 3.140000
Georg Brandl116aa622007-08-15 14:28:22 +0000363 31
364 >>>
365
366
367.. _ctypes-calling-functions-with-own-custom-data-types:
368
369Calling functions with your own custom data types
370^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
371
Georg Brandl1d837bc2009-12-29 11:24:00 +0000372You can also customize :mod:`ctypes` argument conversion to allow instances of
373your own classes be used as function arguments. :mod:`ctypes` looks for an
374:attr:`_as_parameter_` attribute and uses this as the function argument. Of
Georg Brandl8d8f1972009-06-08 13:27:23 +0000375course, it must be one of integer, string, or bytes::
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Éric Araujo28053fb2010-11-22 03:09:19 +0000377 >>> class Bottles:
Georg Brandl116aa622007-08-15 14:28:22 +0000378 ... def __init__(self, number):
379 ... self._as_parameter_ = number
380 ...
381 >>> bottles = Bottles(42)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000382 >>> printf(b"%d bottles of beer\n", bottles)
Georg Brandl116aa622007-08-15 14:28:22 +0000383 42 bottles of beer
384 19
385 >>>
386
387If you don't want to store the instance's data in the :attr:`_as_parameter_`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000388instance variable, you could define a :class:`property` which makes the
389attribute available on request.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391
392.. _ctypes-specifying-required-argument-types:
393
394Specifying the required argument types (function prototypes)
395^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
396
397It is possible to specify the required argument types of functions exported from
398DLLs by setting the :attr:`argtypes` attribute.
399
400:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
401probably not a good example here, because it takes a variable number and
402different types of parameters depending on the format string, on the other hand
403this is quite handy to experiment with this feature)::
404
405 >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000406 >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
Georg Brandl116aa622007-08-15 14:28:22 +0000407 String 'Hi', Int 10, Double 2.200000
408 37
409 >>>
410
411Specifying a format protects against incompatible argument types (just as a
412prototype for a C function), and tries to convert the arguments to valid types::
413
Georg Brandl8d8f1972009-06-08 13:27:23 +0000414 >>> printf(b"%d %d %d", 1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000415 Traceback (most recent call last):
416 File "<stdin>", line 1, in ?
417 ArgumentError: argument 2: exceptions.TypeError: wrong type
Georg Brandl8d8f1972009-06-08 13:27:23 +0000418 >>> printf(b"%s %d %f\n", b"X", 2, 3)
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000419 X 2 3.000000
420 13
Georg Brandl116aa622007-08-15 14:28:22 +0000421 >>>
422
423If you have defined your own classes which you pass to function calls, you have
424to implement a :meth:`from_param` class method for them to be able to use them
425in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
426the Python object passed to the function call, it should do a typecheck or
427whatever is needed to make sure this object is acceptable, and then return the
Thomas Heller2fadaa22008-06-16 19:56:33 +0000428object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
Georg Brandl116aa622007-08-15 14:28:22 +0000429pass as the C function argument in this case. Again, the result should be an
Georg Brandl8d8f1972009-06-08 13:27:23 +0000430integer, string, bytes, a :mod:`ctypes` instance, or an object with an
Georg Brandl116aa622007-08-15 14:28:22 +0000431:attr:`_as_parameter_` attribute.
432
433
434.. _ctypes-return-types:
435
436Return types
437^^^^^^^^^^^^
438
Georg Brandl60203b42010-10-06 10:11:56 +0000439By default functions are assumed to return the C :c:type:`int` type. Other
Georg Brandl1d837bc2009-12-29 11:24:00 +0000440return types can be specified by setting the :attr:`restype` attribute of the
441function object.
Georg Brandl116aa622007-08-15 14:28:22 +0000442
443Here is a more advanced example, it uses the ``strchr`` function, which expects
444a string pointer and a char, and returns a pointer to a string::
445
446 >>> strchr = libc.strchr
Georg Brandl8d8f1972009-06-08 13:27:23 +0000447 >>> strchr(b"abcdef", ord("d")) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000448 8059983
Georg Brandl8d8f1972009-06-08 13:27:23 +0000449 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
450 >>> strchr(b"abcdef", ord("d"))
451 b'def'
452 >>> print(strchr(b"abcdef", ord("x")))
Georg Brandl116aa622007-08-15 14:28:22 +0000453 None
454 >>>
455
456If you want to avoid the ``ord("x")`` calls above, you can set the
457:attr:`argtypes` attribute, and the second argument will be converted from a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000458single character Python bytes object into a C char::
Georg Brandl116aa622007-08-15 14:28:22 +0000459
460 >>> strchr.restype = c_char_p
461 >>> strchr.argtypes = [c_char_p, c_char]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000462 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000463 'def'
Georg Brandl8d8f1972009-06-08 13:27:23 +0000464 >>> strchr(b"abcdef", b"def")
Georg Brandl116aa622007-08-15 14:28:22 +0000465 Traceback (most recent call last):
466 File "<stdin>", line 1, in ?
467 ArgumentError: argument 2: exceptions.TypeError: one character string expected
Georg Brandl8d8f1972009-06-08 13:27:23 +0000468 >>> print(strchr(b"abcdef", b"x"))
Georg Brandl116aa622007-08-15 14:28:22 +0000469 None
Georg Brandl8d8f1972009-06-08 13:27:23 +0000470 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000471 'def'
472 >>>
473
474You can also use a callable Python object (a function or a class for example) as
475the :attr:`restype` attribute, if the foreign function returns an integer. The
Georg Brandl1d837bc2009-12-29 11:24:00 +0000476callable will be called with the *integer* the C function returns, and the
Georg Brandl116aa622007-08-15 14:28:22 +0000477result of this call will be used as the result of your function call. This is
478useful to check for error return values and automatically raise an exception::
479
480 >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
481 >>> def ValidHandle(value):
482 ... if value == 0:
483 ... raise WinError()
484 ... return value
485 ...
486 >>>
487 >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
488 >>> GetModuleHandle(None) # doctest: +WINDOWS
489 486539264
490 >>> GetModuleHandle("something silly") # doctest: +WINDOWS
491 Traceback (most recent call last):
492 File "<stdin>", line 1, in ?
493 File "<stdin>", line 3, in ValidHandle
494 WindowsError: [Errno 126] The specified module could not be found.
495 >>>
496
497``WinError`` is a function which will call Windows ``FormatMessage()`` api to
498get the string representation of an error code, and *returns* an exception.
499``WinError`` takes an optional error code parameter, if no one is used, it calls
500:func:`GetLastError` to retrieve it.
501
502Please note that a much more powerful error checking mechanism is available
503through the :attr:`errcheck` attribute; see the reference manual for details.
504
505
506.. _ctypes-passing-pointers:
507
508Passing pointers (or: passing parameters by reference)
509^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
510
511Sometimes a C api function expects a *pointer* to a data type as parameter,
512probably to write into the corresponding location, or if the data is too large
513to be passed by value. This is also known as *passing parameters by reference*.
514
Georg Brandl8d8f1972009-06-08 13:27:23 +0000515:mod:`ctypes` exports the :func:`byref` function which is used to pass parameters
516by reference. The same effect can be achieved with the :func:`pointer` function,
517although :func:`pointer` does a lot more work since it constructs a real pointer
Georg Brandl116aa622007-08-15 14:28:22 +0000518object, so it is faster to use :func:`byref` if you don't need the pointer
519object in Python itself::
520
521 >>> i = c_int()
522 >>> f = c_float()
Georg Brandl8d8f1972009-06-08 13:27:23 +0000523 >>> s = create_string_buffer(b'\000' * 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000524 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000525 0 0.0 b''
526 >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
Georg Brandl116aa622007-08-15 14:28:22 +0000527 ... byref(i), byref(f), s)
528 3
Georg Brandl6911e3c2007-09-04 07:15:32 +0000529 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000530 1 3.1400001049 b'Hello'
Georg Brandl116aa622007-08-15 14:28:22 +0000531 >>>
532
533
534.. _ctypes-structures-unions:
535
536Structures and unions
537^^^^^^^^^^^^^^^^^^^^^
538
539Structures and unions must derive from the :class:`Structure` and :class:`Union`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000540base classes which are defined in the :mod:`ctypes` module. Each subclass must
Georg Brandl116aa622007-08-15 14:28:22 +0000541define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
542*2-tuples*, containing a *field name* and a *field type*.
543
Georg Brandl8d8f1972009-06-08 13:27:23 +0000544The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
545derived :mod:`ctypes` type: structure, union, array, pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547Here is a simple example of a POINT structure, which contains two integers named
Georg Brandl8d8f1972009-06-08 13:27:23 +0000548*x* and *y*, and also shows how to initialize a structure in the constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000549
550 >>> from ctypes import *
551 >>> class POINT(Structure):
552 ... _fields_ = [("x", c_int),
553 ... ("y", c_int)]
554 ...
555 >>> point = POINT(10, 20)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000556 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000557 10 20
558 >>> point = POINT(y=5)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000559 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000560 0 5
561 >>> POINT(1, 2, 3)
562 Traceback (most recent call last):
563 File "<stdin>", line 1, in ?
564 ValueError: too many initializers
565 >>>
566
567You can, however, build much more complicated structures. Structures can itself
568contain other structures by using a structure as a field type.
569
Georg Brandl1d837bc2009-12-29 11:24:00 +0000570Here is a RECT structure which contains two POINTs named *upperleft* and
571*lowerright*::
Georg Brandl116aa622007-08-15 14:28:22 +0000572
573 >>> class RECT(Structure):
574 ... _fields_ = [("upperleft", POINT),
575 ... ("lowerright", POINT)]
576 ...
577 >>> rc = RECT(point)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000578 >>> print(rc.upperleft.x, rc.upperleft.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000579 0 5
Georg Brandl6911e3c2007-09-04 07:15:32 +0000580 >>> print(rc.lowerright.x, rc.lowerright.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000581 0 0
582 >>>
583
584Nested structures can also be initialized in the constructor in several ways::
585
586 >>> r = RECT(POINT(1, 2), POINT(3, 4))
587 >>> r = RECT((1, 2), (3, 4))
588
Georg Brandl9afde1c2007-11-01 20:32:30 +0000589Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
590for debugging because they can provide useful information::
Georg Brandl116aa622007-08-15 14:28:22 +0000591
Georg Brandl6911e3c2007-09-04 07:15:32 +0000592 >>> print(POINT.x)
Georg Brandl116aa622007-08-15 14:28:22 +0000593 <Field type=c_long, ofs=0, size=4>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000594 >>> print(POINT.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000595 <Field type=c_long, ofs=4, size=4>
596 >>>
597
598
599.. _ctypes-structureunion-alignment-byte-order:
600
601Structure/union alignment and byte order
602^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
603
604By default, Structure and Union fields are aligned in the same way the C
Thomas Woutersed03b412007-08-28 21:37:11 +0000605compiler does it. It is possible to override this behavior be specifying a
Georg Brandl116aa622007-08-15 14:28:22 +0000606:attr:`_pack_` class attribute in the subclass definition. This must be set to a
607positive integer and specifies the maximum alignment for the fields. This is
608what ``#pragma pack(n)`` also does in MSVC.
609
Georg Brandl8d8f1972009-06-08 13:27:23 +0000610:mod:`ctypes` uses the native byte order for Structures and Unions. To build
Georg Brandl116aa622007-08-15 14:28:22 +0000611structures with non-native byte order, you can use one of the
Georg Brandl1d837bc2009-12-29 11:24:00 +0000612:class:`BigEndianStructure`, :class:`LittleEndianStructure`,
613:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These
614classes cannot contain pointer fields.
Georg Brandl116aa622007-08-15 14:28:22 +0000615
616
617.. _ctypes-bit-fields-in-structures-unions:
618
619Bit fields in structures and unions
620^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
621
622It is possible to create structures and unions containing bit fields. Bit fields
623are only possible for integer fields, the bit width is specified as the third
624item in the :attr:`_fields_` tuples::
625
626 >>> class Int(Structure):
627 ... _fields_ = [("first_16", c_int, 16),
628 ... ("second_16", c_int, 16)]
629 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000630 >>> print(Int.first_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000631 <Field type=c_long, ofs=0:0, bits=16>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000632 >>> print(Int.second_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000633 <Field type=c_long, ofs=0:16, bits=16>
634 >>>
635
636
637.. _ctypes-arrays:
638
639Arrays
640^^^^^^
641
642Arrays are sequences, containing a fixed number of instances of the same type.
643
644The recommended way to create array types is by multiplying a data type with a
645positive integer::
646
647 TenPointsArrayType = POINT * 10
648
Thomas Woutersed03b412007-08-28 21:37:11 +0000649Here is an example of an somewhat artificial data type, a structure containing 4
Georg Brandl116aa622007-08-15 14:28:22 +0000650POINTs among other stuff::
651
652 >>> from ctypes import *
653 >>> class POINT(Structure):
654 ... _fields_ = ("x", c_int), ("y", c_int)
655 ...
656 >>> class MyStruct(Structure):
657 ... _fields_ = [("a", c_int),
658 ... ("b", c_float),
659 ... ("point_array", POINT * 4)]
660 >>>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000661 >>> print(len(MyStruct().point_array))
Georg Brandl116aa622007-08-15 14:28:22 +0000662 4
663 >>>
664
665Instances are created in the usual way, by calling the class::
666
667 arr = TenPointsArrayType()
668 for pt in arr:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000669 print(pt.x, pt.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000670
671The above code print a series of ``0 0`` lines, because the array contents is
672initialized to zeros.
673
674Initializers of the correct type can also be specified::
675
676 >>> from ctypes import *
677 >>> TenIntegers = c_int * 10
678 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000679 >>> print(ii)
Georg Brandl116aa622007-08-15 14:28:22 +0000680 <c_long_Array_10 object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000681 >>> for i in ii: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000682 ...
683 1 2 3 4 5 6 7 8 9 10
684 >>>
685
686
687.. _ctypes-pointers:
688
689Pointers
690^^^^^^^^
691
Georg Brandl8d8f1972009-06-08 13:27:23 +0000692Pointer instances are created by calling the :func:`pointer` function on a
693:mod:`ctypes` type::
Georg Brandl116aa622007-08-15 14:28:22 +0000694
695 >>> from ctypes import *
696 >>> i = c_int(42)
697 >>> pi = pointer(i)
698 >>>
699
Georg Brandl1d837bc2009-12-29 11:24:00 +0000700Pointer instances have a :attr:`contents` attribute which returns the object to
Georg Brandl116aa622007-08-15 14:28:22 +0000701which the pointer points, the ``i`` object above::
702
703 >>> pi.contents
704 c_long(42)
705 >>>
706
Georg Brandl8d8f1972009-06-08 13:27:23 +0000707Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
Georg Brandl116aa622007-08-15 14:28:22 +0000708new, equivalent object each time you retrieve an attribute::
709
710 >>> pi.contents is i
711 False
712 >>> pi.contents is pi.contents
713 False
714 >>>
715
716Assigning another :class:`c_int` instance to the pointer's contents attribute
717would cause the pointer to point to the memory location where this is stored::
718
719 >>> i = c_int(99)
720 >>> pi.contents = i
721 >>> pi.contents
722 c_long(99)
723 >>>
724
Georg Brandl1d837bc2009-12-29 11:24:00 +0000725.. XXX Document dereferencing pointers, and that it is preferred over the
726 .contents attribute.
Thomas Heller2fadaa22008-06-16 19:56:33 +0000727
Georg Brandl116aa622007-08-15 14:28:22 +0000728Pointer instances can also be indexed with integers::
729
730 >>> pi[0]
731 99
732 >>>
733
734Assigning to an integer index changes the pointed to value::
735
Georg Brandl6911e3c2007-09-04 07:15:32 +0000736 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000737 c_long(99)
738 >>> pi[0] = 22
Georg Brandl6911e3c2007-09-04 07:15:32 +0000739 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000740 c_long(22)
741 >>>
742
743It is also possible to use indexes different from 0, but you must know what
744you're doing, just as in C: You can access or change arbitrary memory locations.
745Generally you only use this feature if you receive a pointer from a C function,
746and you *know* that the pointer actually points to an array instead of a single
747item.
748
Georg Brandl8d8f1972009-06-08 13:27:23 +0000749Behind the scenes, the :func:`pointer` function does more than simply create
750pointer instances, it has to create pointer *types* first. This is done with the
751:func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a
752new type::
Georg Brandl116aa622007-08-15 14:28:22 +0000753
754 >>> PI = POINTER(c_int)
755 >>> PI
756 <class 'ctypes.LP_c_long'>
757 >>> PI(42)
758 Traceback (most recent call last):
759 File "<stdin>", line 1, in ?
760 TypeError: expected c_long instead of int
761 >>> PI(c_int(42))
762 <ctypes.LP_c_long object at 0x...>
763 >>>
764
765Calling the pointer type without an argument creates a ``NULL`` pointer.
766``NULL`` pointers have a ``False`` boolean value::
767
768 >>> null_ptr = POINTER(c_int)()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000769 >>> print(bool(null_ptr))
Georg Brandl116aa622007-08-15 14:28:22 +0000770 False
771 >>>
772
Georg Brandl8d8f1972009-06-08 13:27:23 +0000773:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
Thomas Heller2fadaa22008-06-16 19:56:33 +0000774invalid non-\ ``NULL`` pointers would crash Python)::
Georg Brandl116aa622007-08-15 14:28:22 +0000775
776 >>> null_ptr[0]
777 Traceback (most recent call last):
778 ....
779 ValueError: NULL pointer access
780 >>>
781
782 >>> null_ptr[0] = 1234
783 Traceback (most recent call last):
784 ....
785 ValueError: NULL pointer access
786 >>>
787
788
789.. _ctypes-type-conversions:
790
791Type conversions
792^^^^^^^^^^^^^^^^
793
794Usually, ctypes does strict type checking. This means, if you have
795``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
796a member field in a structure definition, only instances of exactly the same
797type are accepted. There are some exceptions to this rule, where ctypes accepts
798other objects. For example, you can pass compatible array instances instead of
799pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
800
801 >>> class Bar(Structure):
802 ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
803 ...
804 >>> bar = Bar()
805 >>> bar.values = (c_int * 3)(1, 2, 3)
806 >>> bar.count = 3
807 >>> for i in range(bar.count):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000808 ... print(bar.values[i])
Georg Brandl116aa622007-08-15 14:28:22 +0000809 ...
810 1
811 2
812 3
813 >>>
814
815To set a POINTER type field to ``NULL``, you can assign ``None``::
816
817 >>> bar.values = None
818 >>>
819
Thomas Heller2fadaa22008-06-16 19:56:33 +0000820.. XXX list other conversions...
Georg Brandl116aa622007-08-15 14:28:22 +0000821
Georg Brandl8d8f1972009-06-08 13:27:23 +0000822Sometimes you have instances of incompatible types. In C, you can cast one type
823into another type. :mod:`ctypes` provides a :func:`cast` function which can be
Georg Brandl116aa622007-08-15 14:28:22 +0000824used in the same way. The ``Bar`` structure defined above accepts
825``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
826but not instances of other types::
827
828 >>> bar.values = (c_byte * 4)()
829 Traceback (most recent call last):
830 File "<stdin>", line 1, in ?
831 TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
832 >>>
833
Georg Brandl8d8f1972009-06-08 13:27:23 +0000834For these cases, the :func:`cast` function is handy.
Georg Brandl116aa622007-08-15 14:28:22 +0000835
Georg Brandl8d8f1972009-06-08 13:27:23 +0000836The :func:`cast` function can be used to cast a ctypes instance into a pointer
837to a different ctypes data type. :func:`cast` takes two parameters, a ctypes
838object that is or can be converted to a pointer of some kind, and a ctypes
839pointer type. It returns an instance of the second argument, which references
840the same memory block as the first argument::
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842 >>> a = (c_byte * 4)()
843 >>> cast(a, POINTER(c_int))
844 <ctypes.LP_c_long object at ...>
845 >>>
846
Georg Brandl8d8f1972009-06-08 13:27:23 +0000847So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the
Georg Brandl116aa622007-08-15 14:28:22 +0000848structure::
849
850 >>> bar = Bar()
851 >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
Georg Brandl6911e3c2007-09-04 07:15:32 +0000852 >>> print(bar.values[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000853 0
854 >>>
855
856
857.. _ctypes-incomplete-types:
858
859Incomplete Types
860^^^^^^^^^^^^^^^^
861
862*Incomplete Types* are structures, unions or arrays whose members are not yet
863specified. In C, they are specified by forward declarations, which are defined
864later::
865
866 struct cell; /* forward declaration */
867
Sandro Tosi692dba22011-08-02 16:17:14 +0200868 struct cell {
Georg Brandl116aa622007-08-15 14:28:22 +0000869 char *name;
870 struct cell *next;
Sandro Tosi692dba22011-08-02 16:17:14 +0200871 };
Georg Brandl116aa622007-08-15 14:28:22 +0000872
873The straightforward translation into ctypes code would be this, but it does not
874work::
875
876 >>> class cell(Structure):
877 ... _fields_ = [("name", c_char_p),
878 ... ("next", POINTER(cell))]
879 ...
880 Traceback (most recent call last):
881 File "<stdin>", line 1, in ?
882 File "<stdin>", line 2, in cell
883 NameError: name 'cell' is not defined
884 >>>
885
886because the new ``class cell`` is not available in the class statement itself.
Georg Brandl8d8f1972009-06-08 13:27:23 +0000887In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_`
Georg Brandl116aa622007-08-15 14:28:22 +0000888attribute later, after the class statement::
889
890 >>> from ctypes import *
891 >>> class cell(Structure):
892 ... pass
893 ...
894 >>> cell._fields_ = [("name", c_char_p),
895 ... ("next", POINTER(cell))]
896 >>>
897
898Lets try it. We create two instances of ``cell``, and let them point to each
899other, and finally follow the pointer chain a few times::
900
901 >>> c1 = cell()
902 >>> c1.name = "foo"
903 >>> c2 = cell()
904 >>> c2.name = "bar"
905 >>> c1.next = pointer(c2)
906 >>> c2.next = pointer(c1)
907 >>> p = c1
908 >>> for i in range(8):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000909 ... print(p.name, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000910 ... p = p.next[0]
911 ...
912 foo bar foo bar foo bar foo bar
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000913 >>>
Georg Brandl116aa622007-08-15 14:28:22 +0000914
915
916.. _ctypes-callback-functions:
917
918Callback functions
919^^^^^^^^^^^^^^^^^^
920
Georg Brandl8d8f1972009-06-08 13:27:23 +0000921:mod:`ctypes` allows to create C callable function pointers from Python callables.
Georg Brandl116aa622007-08-15 14:28:22 +0000922These are sometimes called *callback functions*.
923
924First, you must create a class for the callback function, the class knows the
925calling convention, the return type, and the number and types of arguments this
926function will receive.
927
928The CFUNCTYPE factory function creates types for callback functions using the
929normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
930function creates types for callback functions using the stdcall calling
931convention.
932
933Both of these factory functions are called with the result type as first
934argument, and the callback functions expected argument types as the remaining
935arguments.
936
Georg Brandl8d8f1972009-06-08 13:27:23 +0000937I will present an example here which uses the standard C library's
Georg Brandl60203b42010-10-06 10:11:56 +0000938:c:func:`qsort` function, this is used to sort items with the help of a callback
939function. :c:func:`qsort` will be used to sort an array of integers::
Georg Brandl116aa622007-08-15 14:28:22 +0000940
941 >>> IntArray5 = c_int * 5
942 >>> ia = IntArray5(5, 1, 7, 33, 99)
943 >>> qsort = libc.qsort
944 >>> qsort.restype = None
945 >>>
946
947:func:`qsort` must be called with a pointer to the data to sort, the number of
948items in the data array, the size of one item, and a pointer to the comparison
949function, the callback. The callback will then be called with two pointers to
950items, and it must return a negative integer if the first item is smaller than
951the second, a zero if they are equal, and a positive integer else.
952
953So our callback function receives pointers to integers, and must return an
954integer. First we create the ``type`` for the callback function::
955
956 >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
957 >>>
958
959For the first implementation of the callback function, we simply print the
960arguments we get, and return 0 (incremental development ;-)::
961
962 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000963 ... print("py_cmp_func", a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000964 ... return 0
965 ...
966 >>>
967
968Create the C callable callback::
969
970 >>> cmp_func = CMPFUNC(py_cmp_func)
971 >>>
972
973And we're ready to go::
974
975 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
976 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
977 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
978 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
979 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
980 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
981 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
982 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
983 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
984 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
985 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
986 >>>
987
988We know how to access the contents of a pointer, so lets redefine our callback::
989
990 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000991 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000992 ... return 0
993 ...
994 >>> cmp_func = CMPFUNC(py_cmp_func)
995 >>>
996
997Here is what we get on Windows::
998
999 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
1000 py_cmp_func 7 1
1001 py_cmp_func 33 1
1002 py_cmp_func 99 1
1003 py_cmp_func 5 1
1004 py_cmp_func 7 5
1005 py_cmp_func 33 5
1006 py_cmp_func 99 5
1007 py_cmp_func 7 99
1008 py_cmp_func 33 99
1009 py_cmp_func 7 33
1010 >>>
1011
1012It is funny to see that on linux the sort function seems to work much more
Benjamin Peterson1baf4652009-12-31 03:11:23 +00001013efficiently, it is doing less comparisons::
Georg Brandl116aa622007-08-15 14:28:22 +00001014
1015 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
1016 py_cmp_func 5 1
1017 py_cmp_func 33 99
1018 py_cmp_func 7 33
1019 py_cmp_func 5 7
1020 py_cmp_func 1 7
1021 >>>
1022
1023Ah, we're nearly done! The last step is to actually compare the two items and
1024return a useful result::
1025
1026 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001027 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +00001028 ... return a[0] - b[0]
1029 ...
1030 >>>
1031
1032Final run on Windows::
1033
1034 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
1035 py_cmp_func 33 7
1036 py_cmp_func 99 33
1037 py_cmp_func 5 99
1038 py_cmp_func 1 99
1039 py_cmp_func 33 7
1040 py_cmp_func 1 33
1041 py_cmp_func 5 33
1042 py_cmp_func 5 7
1043 py_cmp_func 1 7
1044 py_cmp_func 5 1
1045 >>>
1046
1047and on Linux::
1048
1049 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1050 py_cmp_func 5 1
1051 py_cmp_func 33 99
1052 py_cmp_func 7 33
1053 py_cmp_func 1 7
1054 py_cmp_func 5 7
1055 >>>
1056
1057It is quite interesting to see that the Windows :func:`qsort` function needs
1058more comparisons than the linux version!
1059
1060As we can easily check, our array is sorted now::
1061
Georg Brandl6911e3c2007-09-04 07:15:32 +00001062 >>> for i in ia: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +00001063 ...
1064 1 5 7 33 99
1065 >>>
1066
1067**Important note for callback functions:**
1068
1069Make sure you keep references to CFUNCTYPE objects as long as they are used from
Georg Brandl8d8f1972009-06-08 13:27:23 +00001070C code. :mod:`ctypes` doesn't, and if you don't, they may be garbage collected,
Georg Brandl116aa622007-08-15 14:28:22 +00001071crashing your program when a callback is made.
1072
1073
1074.. _ctypes-accessing-values-exported-from-dlls:
1075
1076Accessing values exported from dlls
1077^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1078
Thomas Heller2fadaa22008-06-16 19:56:33 +00001079Some shared libraries not only export functions, they also export variables. An
Georg Brandl60203b42010-10-06 10:11:56 +00001080example in the Python library itself is the :c:data:`Py_OptimizeFlag`, an integer
Georg Brandl8d8f1972009-06-08 13:27:23 +00001081set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
Georg Brandl116aa622007-08-15 14:28:22 +00001082startup.
1083
Georg Brandl8d8f1972009-06-08 13:27:23 +00001084:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of
Georg Brandl116aa622007-08-15 14:28:22 +00001085the type. *pythonapi* is a predefined symbol giving access to the Python C
1086api::
1087
1088 >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
Georg Brandl6911e3c2007-09-04 07:15:32 +00001089 >>> print(opt_flag)
Georg Brandl116aa622007-08-15 14:28:22 +00001090 c_long(0)
1091 >>>
1092
1093If the interpreter would have been started with :option:`-O`, the sample would
1094have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1095specified.
1096
1097An extended example which also demonstrates the use of pointers accesses the
Georg Brandl60203b42010-10-06 10:11:56 +00001098:c:data:`PyImport_FrozenModules` pointer exported by Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001099
Georg Brandl8d8f1972009-06-08 13:27:23 +00001100Quoting the docs for that value:
1101
Georg Brandl60203b42010-10-06 10:11:56 +00001102 This pointer is initialized to point to an array of :c:type:`struct _frozen`
Georg Brandl8d8f1972009-06-08 13:27:23 +00001103 records, terminated by one whose members are all *NULL* or zero. When a frozen
1104 module is imported, it is searched in this table. Third-party code could play
1105 tricks with this to provide a dynamically created collection of frozen modules.
Georg Brandl116aa622007-08-15 14:28:22 +00001106
1107So manipulating this pointer could even prove useful. To restrict the example
Georg Brandl8d8f1972009-06-08 13:27:23 +00001108size, we show only how this table can be read with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001109
1110 >>> from ctypes import *
1111 >>>
1112 >>> class struct_frozen(Structure):
1113 ... _fields_ = [("name", c_char_p),
1114 ... ("code", POINTER(c_ubyte)),
1115 ... ("size", c_int)]
1116 ...
1117 >>>
1118
Georg Brandl60203b42010-10-06 10:11:56 +00001119We have defined the :c:type:`struct _frozen` data type, so we can get the pointer
Georg Brandl8d8f1972009-06-08 13:27:23 +00001120to the table::
Georg Brandl116aa622007-08-15 14:28:22 +00001121
1122 >>> FrozenTable = POINTER(struct_frozen)
1123 >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1124 >>>
1125
1126Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1127can iterate over it, but we just have to make sure that our loop terminates,
1128because pointers have no size. Sooner or later it would probably crash with an
1129access violation or whatever, so it's better to break out of the loop when we
1130hit the NULL entry::
1131
1132 >>> for item in table:
Georg Brandl6911e3c2007-09-04 07:15:32 +00001133 ... print(item.name, item.size)
Georg Brandl116aa622007-08-15 14:28:22 +00001134 ... if item.name is None:
1135 ... break
1136 ...
1137 __hello__ 104
1138 __phello__ -104
1139 __phello__.spam 104
1140 None 0
1141 >>>
1142
1143The fact that standard Python has a frozen module and a frozen package
Thomas Woutersed03b412007-08-28 21:37:11 +00001144(indicated by the negative size member) is not well known, it is only used for
Georg Brandl116aa622007-08-15 14:28:22 +00001145testing. Try it out with ``import __hello__`` for example.
1146
1147
1148.. _ctypes-surprises:
1149
1150Surprises
1151^^^^^^^^^
1152
Georg Brandl8d8f1972009-06-08 13:27:23 +00001153There are some edges in :mod:`ctypes` where you may be expect something else than
Georg Brandl116aa622007-08-15 14:28:22 +00001154what actually happens.
1155
1156Consider the following example::
1157
1158 >>> from ctypes import *
1159 >>> class POINT(Structure):
1160 ... _fields_ = ("x", c_int), ("y", c_int)
1161 ...
1162 >>> class RECT(Structure):
1163 ... _fields_ = ("a", POINT), ("b", POINT)
1164 ...
1165 >>> p1 = POINT(1, 2)
1166 >>> p2 = POINT(3, 4)
1167 >>> rc = RECT(p1, p2)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001168 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001169 1 2 3 4
1170 >>> # now swap the two points
1171 >>> rc.a, rc.b = rc.b, rc.a
Georg Brandl6911e3c2007-09-04 07:15:32 +00001172 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001173 3 4 3 4
1174 >>>
1175
1176Hm. We certainly expected the last statement to print ``3 4 1 2``. What
Thomas Woutersed03b412007-08-28 21:37:11 +00001177happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
Georg Brandl116aa622007-08-15 14:28:22 +00001178
1179 >>> temp0, temp1 = rc.b, rc.a
1180 >>> rc.a = temp0
1181 >>> rc.b = temp1
1182 >>>
1183
1184Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1185the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1186contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1187contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1188the expected effect.
1189
Thomas Woutersed03b412007-08-28 21:37:11 +00001190Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1191doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
Georg Brandl116aa622007-08-15 14:28:22 +00001192the root-object's underlying buffer.
1193
1194Another example that may behave different from what one would expect is this::
1195
1196 >>> s = c_char_p()
1197 >>> s.value = "abc def ghi"
1198 >>> s.value
1199 'abc def ghi'
1200 >>> s.value is s.value
1201 False
1202 >>>
1203
1204Why is it printing ``False``? ctypes instances are objects containing a memory
Georg Brandl9afde1c2007-11-01 20:32:30 +00001205block plus some :term:`descriptor`\s accessing the contents of the memory.
1206Storing a Python object in the memory block does not store the object itself,
1207instead the ``contents`` of the object is stored. Accessing the contents again
1208constructs a new Python object each time!
Georg Brandl116aa622007-08-15 14:28:22 +00001209
1210
1211.. _ctypes-variable-sized-data-types:
1212
1213Variable-sized data types
1214^^^^^^^^^^^^^^^^^^^^^^^^^
1215
Georg Brandl8d8f1972009-06-08 13:27:23 +00001216:mod:`ctypes` provides some support for variable-sized arrays and structures.
Georg Brandl116aa622007-08-15 14:28:22 +00001217
Georg Brandl8d8f1972009-06-08 13:27:23 +00001218The :func:`resize` function can be used to resize the memory buffer of an
1219existing ctypes object. The function takes the object as first argument, and
1220the requested size in bytes as the second argument. The memory block cannot be
1221made smaller than the natural memory block specified by the objects type, a
1222:exc:`ValueError` is raised if this is tried::
Georg Brandl116aa622007-08-15 14:28:22 +00001223
1224 >>> short_array = (c_short * 4)()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001225 >>> print(sizeof(short_array))
Georg Brandl116aa622007-08-15 14:28:22 +00001226 8
1227 >>> resize(short_array, 4)
1228 Traceback (most recent call last):
1229 ...
1230 ValueError: minimum size is 8
1231 >>> resize(short_array, 32)
1232 >>> sizeof(short_array)
1233 32
1234 >>> sizeof(type(short_array))
1235 8
1236 >>>
1237
1238This is nice and fine, but how would one access the additional elements
1239contained in this array? Since the type still only knows about 4 elements, we
1240get errors accessing other elements::
1241
1242 >>> short_array[:]
1243 [0, 0, 0, 0]
1244 >>> short_array[7]
1245 Traceback (most recent call last):
1246 ...
1247 IndexError: invalid index
1248 >>>
1249
Georg Brandl8d8f1972009-06-08 13:27:23 +00001250Another way to use variable-sized data types with :mod:`ctypes` is to use the
Georg Brandl116aa622007-08-15 14:28:22 +00001251dynamic nature of Python, and (re-)define the data type after the required size
1252is already known, on a case by case basis.
1253
1254
Georg Brandl116aa622007-08-15 14:28:22 +00001255.. _ctypes-ctypes-reference:
1256
1257ctypes reference
1258----------------
1259
1260
1261.. _ctypes-finding-shared-libraries:
1262
1263Finding shared libraries
1264^^^^^^^^^^^^^^^^^^^^^^^^
1265
1266When programming in a compiled language, shared libraries are accessed when
1267compiling/linking a program, and when the program is run.
1268
Georg Brandl8d8f1972009-06-08 13:27:23 +00001269The purpose of the :func:`find_library` function is to locate a library in a way
Georg Brandl116aa622007-08-15 14:28:22 +00001270similar to what the compiler does (on platforms with several versions of a
1271shared library the most recent should be loaded), while the ctypes library
1272loaders act like when a program is run, and call the runtime loader directly.
1273
Georg Brandl8d8f1972009-06-08 13:27:23 +00001274The :mod:`ctypes.util` module provides a function which can help to determine
1275the library to load.
Georg Brandl116aa622007-08-15 14:28:22 +00001276
1277
1278.. data:: find_library(name)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001279 :module: ctypes.util
Georg Brandl116aa622007-08-15 14:28:22 +00001280 :noindex:
1281
1282 Try to find a library and return a pathname. *name* is the library name without
1283 any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1284 is the form used for the posix linker option :option:`-l`). If no library can
1285 be found, returns ``None``.
1286
Thomas Woutersed03b412007-08-28 21:37:11 +00001287The exact functionality is system dependent.
Georg Brandl116aa622007-08-15 14:28:22 +00001288
Georg Brandl1d837bc2009-12-29 11:24:00 +00001289On Linux, :func:`find_library` tries to run external programs
1290(``/sbin/ldconfig``, ``gcc``, and ``objdump``) to find the library file. It
1291returns the filename of the library file. Here are some examples::
Georg Brandl116aa622007-08-15 14:28:22 +00001292
1293 >>> from ctypes.util import find_library
1294 >>> find_library("m")
1295 'libm.so.6'
1296 >>> find_library("c")
1297 'libc.so.6'
1298 >>> find_library("bz2")
1299 'libbz2.so.1.0'
1300 >>>
1301
Georg Brandl8d8f1972009-06-08 13:27:23 +00001302On OS X, :func:`find_library` tries several predefined naming schemes and paths
1303to locate the library, and returns a full pathname if successful::
Georg Brandl116aa622007-08-15 14:28:22 +00001304
1305 >>> from ctypes.util import find_library
1306 >>> find_library("c")
1307 '/usr/lib/libc.dylib'
1308 >>> find_library("m")
1309 '/usr/lib/libm.dylib'
1310 >>> find_library("bz2")
1311 '/usr/lib/libbz2.dylib'
1312 >>> find_library("AGL")
1313 '/System/Library/Frameworks/AGL.framework/AGL'
1314 >>>
1315
Georg Brandl8d8f1972009-06-08 13:27:23 +00001316On Windows, :func:`find_library` searches along the system search path, and
1317returns the full pathname, but since there is no predefined naming scheme a call
1318like ``find_library("c")`` will fail and return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001319
Georg Brandl8d8f1972009-06-08 13:27:23 +00001320If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
Georg Brandl116aa622007-08-15 14:28:22 +00001321the shared library name at development type, and hardcode that into the wrapper
Georg Brandl8d8f1972009-06-08 13:27:23 +00001322module instead of using :func:`find_library` to locate the library at runtime.
Georg Brandl116aa622007-08-15 14:28:22 +00001323
1324
1325.. _ctypes-loading-shared-libraries:
1326
1327Loading shared libraries
1328^^^^^^^^^^^^^^^^^^^^^^^^
1329
1330There are several ways to loaded shared libraries into the Python process. One
1331way is to instantiate one of the following classes:
1332
1333
Thomas Hellerb795f5282008-06-10 15:26:58 +00001334.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001335
1336 Instances of this class represent loaded shared libraries. Functions in these
1337 libraries use the standard C calling convention, and are assumed to return
Georg Brandl60203b42010-10-06 10:11:56 +00001338 :c:type:`int`.
Georg Brandl116aa622007-08-15 14:28:22 +00001339
1340
Thomas Hellerb795f5282008-06-10 15:26:58 +00001341.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001342
1343 Windows only: Instances of this class represent loaded shared libraries,
1344 functions in these libraries use the ``stdcall`` calling convention, and are
1345 assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1346 values contain information specifying whether the function call failed or
1347 succeeded, together with additional error code. If the return value signals a
1348 failure, an :class:`WindowsError` is automatically raised.
1349
1350
Thomas Hellerb795f5282008-06-10 15:26:58 +00001351.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001352
1353 Windows only: Instances of this class represent loaded shared libraries,
1354 functions in these libraries use the ``stdcall`` calling convention, and are
Georg Brandl60203b42010-10-06 10:11:56 +00001355 assumed to return :c:type:`int` by default.
Georg Brandl116aa622007-08-15 14:28:22 +00001356
1357 On Windows CE only the standard calling convention is used, for convenience the
1358 :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1359 platform.
1360
Georg Brandl9afde1c2007-11-01 20:32:30 +00001361The Python :term:`global interpreter lock` is released before calling any
1362function exported by these libraries, and reacquired afterwards.
Georg Brandl116aa622007-08-15 14:28:22 +00001363
1364
1365.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1366
1367 Instances of this class behave like :class:`CDLL` instances, except that the
1368 Python GIL is *not* released during the function call, and after the function
1369 execution the Python error flag is checked. If the error flag is set, a Python
1370 exception is raised.
1371
1372 Thus, this is only useful to call Python C api functions directly.
1373
1374All these classes can be instantiated by calling them with at least one
1375argument, the pathname of the shared library. If you have an existing handle to
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001376an already loaded shared library, it can be passed as the ``handle`` named
Georg Brandl1d837bc2009-12-29 11:24:00 +00001377parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary``
Georg Brandl116aa622007-08-15 14:28:22 +00001378function is used to load the library into the process, and to get a handle to
1379it.
1380
1381The *mode* parameter can be used to specify how the library is loaded. For
Georg Brandl1d837bc2009-12-29 11:24:00 +00001382details, consult the :manpage:`dlopen(3)` manpage, on Windows, *mode* is
1383ignored.
Georg Brandl116aa622007-08-15 14:28:22 +00001384
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001385The *use_errno* parameter, when set to True, enables a ctypes mechanism that
1386allows to access the system :data:`errno` error number in a safe way.
1387:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1388variable; if you call foreign functions created with ``use_errno=True`` then the
1389:data:`errno` value before the function call is swapped with the ctypes private
1390copy, the same happens immediately after the function call.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001391
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001392The function :func:`ctypes.get_errno` returns the value of the ctypes private
1393copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1394to a new value and returns the former value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001395
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001396The *use_last_error* parameter, when set to True, enables the same mechanism for
1397the Windows error code which is managed by the :func:`GetLastError` and
1398:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1399:func:`ctypes.set_last_error` are used to request and change the ctypes private
1400copy of the windows error code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001401
Georg Brandl116aa622007-08-15 14:28:22 +00001402.. data:: RTLD_GLOBAL
1403 :noindex:
1404
1405 Flag to use as *mode* parameter. On platforms where this flag is not available,
1406 it is defined as the integer zero.
1407
1408
1409.. data:: RTLD_LOCAL
1410 :noindex:
1411
1412 Flag to use as *mode* parameter. On platforms where this is not available, it
1413 is the same as *RTLD_GLOBAL*.
1414
1415
1416.. data:: DEFAULT_MODE
1417 :noindex:
1418
1419 The default mode which is used to load shared libraries. On OSX 10.3, this is
1420 *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1421
1422Instances of these classes have no public methods, however :meth:`__getattr__`
Thomas Woutersed03b412007-08-28 21:37:11 +00001423and :meth:`__getitem__` have special behavior: functions exported by the shared
Georg Brandl116aa622007-08-15 14:28:22 +00001424library can be accessed as attributes of by index. Please note that both
1425:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1426repeatedly returns the same object each time.
1427
1428The following public attributes are available, their name starts with an
1429underscore to not clash with exported function names:
1430
1431
1432.. attribute:: PyDLL._handle
1433
1434 The system handle used to access the library.
1435
1436
1437.. attribute:: PyDLL._name
1438
Thomas Woutersed03b412007-08-28 21:37:11 +00001439 The name of the library passed in the constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001440
1441Shared libraries can also be loaded by using one of the prefabricated objects,
1442which are instances of the :class:`LibraryLoader` class, either by calling the
1443:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1444loader instance.
1445
1446
1447.. class:: LibraryLoader(dlltype)
1448
Georg Brandl1d837bc2009-12-29 11:24:00 +00001449 Class which loads shared libraries. *dlltype* should be one of the
Georg Brandl116aa622007-08-15 14:28:22 +00001450 :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1451
Thomas Woutersed03b412007-08-28 21:37:11 +00001452 :meth:`__getattr__` has special behavior: It allows to load a shared library by
Georg Brandl116aa622007-08-15 14:28:22 +00001453 accessing it as attribute of a library loader instance. The result is cached,
1454 so repeated attribute accesses return the same library each time.
1455
Benjamin Petersone41251e2008-04-25 01:59:09 +00001456 .. method:: LoadLibrary(name)
Georg Brandl116aa622007-08-15 14:28:22 +00001457
Benjamin Petersone41251e2008-04-25 01:59:09 +00001458 Load a shared library into the process and return it. This method always
1459 returns a new instance of the library.
Georg Brandl116aa622007-08-15 14:28:22 +00001460
Georg Brandl116aa622007-08-15 14:28:22 +00001461
Georg Brandl8d8f1972009-06-08 13:27:23 +00001462These prefabricated library loaders are available:
Georg Brandl116aa622007-08-15 14:28:22 +00001463
1464.. data:: cdll
1465 :noindex:
1466
1467 Creates :class:`CDLL` instances.
1468
1469
1470.. data:: windll
1471 :noindex:
1472
1473 Windows only: Creates :class:`WinDLL` instances.
1474
1475
1476.. data:: oledll
1477 :noindex:
1478
1479 Windows only: Creates :class:`OleDLL` instances.
1480
1481
1482.. data:: pydll
1483 :noindex:
1484
1485 Creates :class:`PyDLL` instances.
1486
Georg Brandl8d8f1972009-06-08 13:27:23 +00001487
Georg Brandl116aa622007-08-15 14:28:22 +00001488For accessing the C Python api directly, a ready-to-use Python shared library
1489object is available:
1490
Georg Brandl116aa622007-08-15 14:28:22 +00001491.. data:: pythonapi
1492 :noindex:
1493
Georg Brandl1d837bc2009-12-29 11:24:00 +00001494 An instance of :class:`PyDLL` that exposes Python C API functions as
1495 attributes. Note that all these functions are assumed to return C
Georg Brandl60203b42010-10-06 10:11:56 +00001496 :c:type:`int`, which is of course not always the truth, so you have to assign
Georg Brandl1d837bc2009-12-29 11:24:00 +00001497 the correct :attr:`restype` attribute to use these functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001498
1499
1500.. _ctypes-foreign-functions:
1501
1502Foreign functions
1503^^^^^^^^^^^^^^^^^
1504
1505As explained in the previous section, foreign functions can be accessed as
1506attributes of loaded shared libraries. The function objects created in this way
1507by default accept any number of arguments, accept any ctypes data instances as
1508arguments, and return the default result type specified by the library loader.
1509They are instances of a private class:
1510
1511
1512.. class:: _FuncPtr
1513
1514 Base class for C callable foreign functions.
1515
Benjamin Petersone41251e2008-04-25 01:59:09 +00001516 Instances of foreign functions are also C compatible data types; they
1517 represent C function pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001518
Benjamin Petersone41251e2008-04-25 01:59:09 +00001519 This behavior can be customized by assigning to special attributes of the
1520 foreign function object.
Georg Brandl116aa622007-08-15 14:28:22 +00001521
Benjamin Petersone41251e2008-04-25 01:59:09 +00001522 .. attribute:: restype
Georg Brandl116aa622007-08-15 14:28:22 +00001523
Benjamin Petersone41251e2008-04-25 01:59:09 +00001524 Assign a ctypes type to specify the result type of the foreign function.
Georg Brandl60203b42010-10-06 10:11:56 +00001525 Use ``None`` for :c:type:`void`, a function not returning anything.
Georg Brandl116aa622007-08-15 14:28:22 +00001526
Benjamin Petersone41251e2008-04-25 01:59:09 +00001527 It is possible to assign a callable Python object that is not a ctypes
Georg Brandl60203b42010-10-06 10:11:56 +00001528 type, in this case the function is assumed to return a C :c:type:`int`, and
Georg Brandl1d837bc2009-12-29 11:24:00 +00001529 the callable will be called with this integer, allowing to do further
Benjamin Petersone41251e2008-04-25 01:59:09 +00001530 processing or error checking. Using this is deprecated, for more flexible
1531 post processing or error checking use a ctypes data type as
1532 :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001533
Benjamin Petersone41251e2008-04-25 01:59:09 +00001534 .. attribute:: argtypes
Georg Brandl116aa622007-08-15 14:28:22 +00001535
Benjamin Petersone41251e2008-04-25 01:59:09 +00001536 Assign a tuple of ctypes types to specify the argument types that the
1537 function accepts. Functions using the ``stdcall`` calling convention can
1538 only be called with the same number of arguments as the length of this
1539 tuple; functions using the C calling convention accept additional,
1540 unspecified arguments as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001541
Benjamin Petersone41251e2008-04-25 01:59:09 +00001542 When a foreign function is called, each actual argument is passed to the
1543 :meth:`from_param` class method of the items in the :attr:`argtypes`
1544 tuple, this method allows to adapt the actual argument to an object that
1545 the foreign function accepts. For example, a :class:`c_char_p` item in
Georg Brandl8d8f1972009-06-08 13:27:23 +00001546 the :attr:`argtypes` tuple will convert a string passed as argument into
1547 a bytes object using ctypes conversion rules.
Georg Brandl116aa622007-08-15 14:28:22 +00001548
Benjamin Petersone41251e2008-04-25 01:59:09 +00001549 New: It is now possible to put items in argtypes which are not ctypes
1550 types, but each item must have a :meth:`from_param` method which returns a
1551 value usable as argument (integer, string, ctypes instance). This allows
1552 to define adapters that can adapt custom objects as function parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001553
Benjamin Petersone41251e2008-04-25 01:59:09 +00001554 .. attribute:: errcheck
Georg Brandl116aa622007-08-15 14:28:22 +00001555
Benjamin Petersone41251e2008-04-25 01:59:09 +00001556 Assign a Python function or another callable to this attribute. The
1557 callable will be called with three or more arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001558
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001559 .. function:: callable(result, func, arguments)
1560 :noindex:
Georg Brandl8d8f1972009-06-08 13:27:23 +00001561 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001562
Georg Brandl1d837bc2009-12-29 11:24:00 +00001563 *result* is what the foreign function returns, as specified by the
1564 :attr:`restype` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001565
Georg Brandl1d837bc2009-12-29 11:24:00 +00001566 *func* is the foreign function object itself, this allows to reuse the
1567 same callable object to check or post process the results of several
1568 functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001569
Georg Brandl1d837bc2009-12-29 11:24:00 +00001570 *arguments* is a tuple containing the parameters originally passed to
1571 the function call, this allows to specialize the behavior on the
1572 arguments used.
Georg Brandl116aa622007-08-15 14:28:22 +00001573
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001574 The object that this function returns will be returned from the
1575 foreign function call, but it can also check the result value
1576 and raise an exception if the foreign function call failed.
Georg Brandl116aa622007-08-15 14:28:22 +00001577
1578
Georg Brandl8d8f1972009-06-08 13:27:23 +00001579.. exception:: ArgumentError
Georg Brandl116aa622007-08-15 14:28:22 +00001580
1581 This exception is raised when a foreign function call cannot convert one of the
1582 passed arguments.
1583
1584
1585.. _ctypes-function-prototypes:
1586
1587Function prototypes
1588^^^^^^^^^^^^^^^^^^^
1589
1590Foreign functions can also be created by instantiating function prototypes.
1591Function prototypes are similar to function prototypes in C; they describe a
1592function (return type, argument types, calling convention) without defining an
1593implementation. The factory functions must be called with the desired result
1594type and the argument types of the function.
1595
1596
Thomas Hellerb795f5282008-06-10 15:26:58 +00001597.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001598
1599 The returned function prototype creates functions that use the standard C
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001600 calling convention. The function will release the GIL during the call. If
1601 *use_errno* is set to True, the ctypes private copy of the system
Georg Brandla6053b42009-09-01 08:11:14 +00001602 :data:`errno` variable is exchanged with the real :data:`errno` value before
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001603 and after the call; *use_last_error* does the same for the Windows error
1604 code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001605
Georg Brandl116aa622007-08-15 14:28:22 +00001606
Thomas Hellerb795f5282008-06-10 15:26:58 +00001607.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001608
1609 Windows only: The returned function prototype creates functions that use the
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001610 ``stdcall`` calling convention, except on Windows CE where
1611 :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
1612 release the GIL during the call. *use_errno* and *use_last_error* have the
1613 same meaning as above.
Georg Brandl116aa622007-08-15 14:28:22 +00001614
1615
1616.. function:: PYFUNCTYPE(restype, *argtypes)
1617
1618 The returned function prototype creates functions that use the Python calling
1619 convention. The function will *not* release the GIL during the call.
1620
Thomas Heller2fadaa22008-06-16 19:56:33 +00001621Function prototypes created by these factory functions can be instantiated in
1622different ways, depending on the type and number of the parameters in the call:
Georg Brandl116aa622007-08-15 14:28:22 +00001623
1624
Thomas Heller2fadaa22008-06-16 19:56:33 +00001625 .. function:: prototype(address)
1626 :noindex:
1627 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001628
Thomas Heller2fadaa22008-06-16 19:56:33 +00001629 Returns a foreign function at the specified address which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00001630
1631
Thomas Heller2fadaa22008-06-16 19:56:33 +00001632 .. function:: prototype(callable)
1633 :noindex:
1634 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001635
Georg Brandl8d8f1972009-06-08 13:27:23 +00001636 Create a C callable function (a callback function) from a Python *callable*.
Georg Brandl116aa622007-08-15 14:28:22 +00001637
1638
Thomas Heller2fadaa22008-06-16 19:56:33 +00001639 .. function:: prototype(func_spec[, paramflags])
1640 :noindex:
1641 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001642
Georg Brandl1d837bc2009-12-29 11:24:00 +00001643 Returns a foreign function exported by a shared library. *func_spec* must
1644 be a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of
1645 the exported function as string, or the ordinal of the exported function
1646 as small integer. The second item is the shared library instance.
Georg Brandl116aa622007-08-15 14:28:22 +00001647
1648
Thomas Heller2fadaa22008-06-16 19:56:33 +00001649 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1650 :noindex:
1651 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001652
Georg Brandl8d8f1972009-06-08 13:27:23 +00001653 Returns a foreign function that will call a COM method. *vtbl_index* is
1654 the index into the virtual function table, a small non-negative
1655 integer. *name* is name of the COM method. *iid* is an optional pointer to
1656 the interface identifier which is used in extended error reporting.
Georg Brandl116aa622007-08-15 14:28:22 +00001657
Georg Brandl8d8f1972009-06-08 13:27:23 +00001658 COM methods use a special calling convention: They require a pointer to
1659 the COM interface as first argument, in addition to those parameters that
1660 are specified in the :attr:`argtypes` tuple.
Georg Brandl116aa622007-08-15 14:28:22 +00001661
Thomas Heller2fadaa22008-06-16 19:56:33 +00001662 The optional *paramflags* parameter creates foreign function wrappers with much
1663 more functionality than the features described above.
Georg Brandl116aa622007-08-15 14:28:22 +00001664
Thomas Heller2fadaa22008-06-16 19:56:33 +00001665 *paramflags* must be a tuple of the same length as :attr:`argtypes`.
Georg Brandl116aa622007-08-15 14:28:22 +00001666
Thomas Heller2fadaa22008-06-16 19:56:33 +00001667 Each item in this tuple contains further information about a parameter, it must
1668 be a tuple containing one, two, or three items.
Georg Brandl116aa622007-08-15 14:28:22 +00001669
Thomas Heller2fadaa22008-06-16 19:56:33 +00001670 The first item is an integer containing a combination of direction
1671 flags for the parameter:
Georg Brandl116aa622007-08-15 14:28:22 +00001672
Thomas Heller2fadaa22008-06-16 19:56:33 +00001673 1
1674 Specifies an input parameter to the function.
Georg Brandl116aa622007-08-15 14:28:22 +00001675
Thomas Heller2fadaa22008-06-16 19:56:33 +00001676 2
1677 Output parameter. The foreign function fills in a value.
Georg Brandl116aa622007-08-15 14:28:22 +00001678
Thomas Heller2fadaa22008-06-16 19:56:33 +00001679 4
1680 Input parameter which defaults to the integer zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001681
Thomas Heller2fadaa22008-06-16 19:56:33 +00001682 The optional second item is the parameter name as string. If this is specified,
1683 the foreign function can be called with named parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001684
Thomas Heller2fadaa22008-06-16 19:56:33 +00001685 The optional third item is the default value for this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001686
1687This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
1688that it supports default parameters and named arguments. The C declaration from
1689the windows header file is this::
1690
1691 WINUSERAPI int WINAPI
1692 MessageBoxA(
1693 HWND hWnd ,
1694 LPCSTR lpText,
1695 LPCSTR lpCaption,
1696 UINT uType);
1697
Georg Brandl8d8f1972009-06-08 13:27:23 +00001698Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001699
Thomas Heller2fadaa22008-06-16 19:56:33 +00001700 >>> from ctypes import c_int, WINFUNCTYPE, windll
1701 >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1702 >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
1703 >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1704 >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1705 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001706
1707The MessageBox foreign function can now be called in these ways::
1708
1709 >>> MessageBox()
1710 >>> MessageBox(text="Spam, spam, spam")
1711 >>> MessageBox(flags=2, text="foo bar")
1712 >>>
1713
1714A second example demonstrates output parameters. The win32 ``GetWindowRect``
1715function retrieves the dimensions of a specified window by copying them into
1716``RECT`` structure that the caller has to supply. Here is the C declaration::
1717
1718 WINUSERAPI BOOL WINAPI
1719 GetWindowRect(
1720 HWND hWnd,
1721 LPRECT lpRect);
1722
Georg Brandl8d8f1972009-06-08 13:27:23 +00001723Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001724
Thomas Heller2fadaa22008-06-16 19:56:33 +00001725 >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1726 >>> from ctypes.wintypes import BOOL, HWND, RECT
1727 >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1728 >>> paramflags = (1, "hwnd"), (2, "lprect")
1729 >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1730 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001731
1732Functions with output parameters will automatically return the output parameter
1733value if there is a single one, or a tuple containing the output parameter
1734values when there are more than one, so the GetWindowRect function now returns a
1735RECT instance, when called.
1736
1737Output parameters can be combined with the :attr:`errcheck` protocol to do
1738further output processing and error checking. The win32 ``GetWindowRect`` api
1739function returns a ``BOOL`` to signal success or failure, so this function could
1740do the error checking, and raises an exception when the api call failed::
1741
1742 >>> def errcheck(result, func, args):
1743 ... if not result:
1744 ... raise WinError()
1745 ... return args
Thomas Heller2fadaa22008-06-16 19:56:33 +00001746 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001747 >>> GetWindowRect.errcheck = errcheck
1748 >>>
1749
1750If the :attr:`errcheck` function returns the argument tuple it receives
Georg Brandl8d8f1972009-06-08 13:27:23 +00001751unchanged, :mod:`ctypes` continues the normal processing it does on the output
Georg Brandl116aa622007-08-15 14:28:22 +00001752parameters. If you want to return a tuple of window coordinates instead of a
1753``RECT`` instance, you can retrieve the fields in the function and return them
1754instead, the normal processing will no longer take place::
1755
1756 >>> def errcheck(result, func, args):
1757 ... if not result:
1758 ... raise WinError()
1759 ... rc = args[1]
1760 ... return rc.left, rc.top, rc.bottom, rc.right
Thomas Heller2fadaa22008-06-16 19:56:33 +00001761 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001762 >>> GetWindowRect.errcheck = errcheck
1763 >>>
1764
1765
1766.. _ctypes-utility-functions:
1767
1768Utility functions
1769^^^^^^^^^^^^^^^^^
1770
Georg Brandl116aa622007-08-15 14:28:22 +00001771.. function:: addressof(obj)
1772
Georg Brandl8d8f1972009-06-08 13:27:23 +00001773 Returns the address of the memory buffer as integer. *obj* must be an
Georg Brandl116aa622007-08-15 14:28:22 +00001774 instance of a ctypes type.
1775
1776
1777.. function:: alignment(obj_or_type)
1778
Georg Brandl8d8f1972009-06-08 13:27:23 +00001779 Returns the alignment requirements of a ctypes type. *obj_or_type* must be a
Georg Brandl116aa622007-08-15 14:28:22 +00001780 ctypes type or instance.
1781
1782
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001783.. function:: byref(obj[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +00001784
Georg Brandl1d837bc2009-12-29 11:24:00 +00001785 Returns a light-weight pointer to *obj*, which must be an instance of a
1786 ctypes type. *offset* defaults to zero, and must be an integer that will be
1787 added to the internal pointer value.
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001788
1789 ``byref(obj, offset)`` corresponds to this C code::
1790
1791 (((char *)&obj) + offset)
1792
Georg Brandl1d837bc2009-12-29 11:24:00 +00001793 The returned object can only be used as a foreign function call parameter.
1794 It behaves similar to ``pointer(obj)``, but the construction is a lot faster.
Georg Brandl116aa622007-08-15 14:28:22 +00001795
1796
1797.. function:: cast(obj, type)
1798
Georg Brandl8d8f1972009-06-08 13:27:23 +00001799 This function is similar to the cast operator in C. It returns a new instance
Georg Brandl1d837bc2009-12-29 11:24:00 +00001800 of *type* which points to the same memory block as *obj*. *type* must be a
Georg Brandl8d8f1972009-06-08 13:27:23 +00001801 pointer type, and *obj* must be an object that can be interpreted as a
Georg Brandl116aa622007-08-15 14:28:22 +00001802 pointer.
1803
1804
Georg Brandl8d8f1972009-06-08 13:27:23 +00001805.. function:: create_string_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001806
1807 This function creates a mutable character buffer. The returned object is a
1808 ctypes array of :class:`c_char`.
1809
Georg Brandl8d8f1972009-06-08 13:27:23 +00001810 *init_or_size* must be an integer which specifies the size of the array, or a
1811 bytes object which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001812
Georg Brandl8d8f1972009-06-08 13:27:23 +00001813 If a bytes object is specified as first argument, the buffer is made one item
1814 larger than its length so that the last element in the array is a NUL
Georg Brandl116aa622007-08-15 14:28:22 +00001815 termination character. An integer can be passed as second argument which allows
Georg Brandl8d8f1972009-06-08 13:27:23 +00001816 to specify the size of the array if the length of the bytes should not be used.
Georg Brandl116aa622007-08-15 14:28:22 +00001817
Georg Brandl8d8f1972009-06-08 13:27:23 +00001818 If the first parameter is a string, it is converted into a bytes object
Georg Brandl116aa622007-08-15 14:28:22 +00001819 according to ctypes conversion rules.
1820
1821
Georg Brandl8d8f1972009-06-08 13:27:23 +00001822.. function:: create_unicode_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001823
1824 This function creates a mutable unicode character buffer. The returned object is
1825 a ctypes array of :class:`c_wchar`.
1826
Georg Brandl8d8f1972009-06-08 13:27:23 +00001827 *init_or_size* must be an integer which specifies the size of the array, or a
1828 string which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001829
Georg Brandl8d8f1972009-06-08 13:27:23 +00001830 If a string is specified as first argument, the buffer is made one item
Georg Brandl116aa622007-08-15 14:28:22 +00001831 larger than the length of the string so that the last element in the array is a
1832 NUL termination character. An integer can be passed as second argument which
1833 allows to specify the size of the array if the length of the string should not
1834 be used.
1835
Georg Brandl8d8f1972009-06-08 13:27:23 +00001836 If the first parameter is a bytes object, it is converted into an unicode string
Georg Brandl116aa622007-08-15 14:28:22 +00001837 according to ctypes conversion rules.
1838
1839
1840.. function:: DllCanUnloadNow()
1841
Georg Brandl1d837bc2009-12-29 11:24:00 +00001842 Windows only: This function is a hook which allows to implement in-process
1843 COM servers with ctypes. It is called from the DllCanUnloadNow function that
1844 the _ctypes extension dll exports.
Georg Brandl116aa622007-08-15 14:28:22 +00001845
1846
1847.. function:: DllGetClassObject()
1848
Georg Brandl1d837bc2009-12-29 11:24:00 +00001849 Windows only: This function is a hook which allows to implement in-process
1850 COM servers with ctypes. It is called from the DllGetClassObject function
1851 that the ``_ctypes`` extension dll exports.
1852
Georg Brandl116aa622007-08-15 14:28:22 +00001853
Thomas Heller2fadaa22008-06-16 19:56:33 +00001854.. function:: find_library(name)
1855 :module: ctypes.util
1856
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001857 Try to find a library and return a pathname. *name* is the library name
Benjamin Peterson28d88b42009-01-09 03:03:23 +00001858 without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001859 number (this is the form used for the posix linker option :option:`-l`). If
1860 no library can be found, returns ``None``.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001861
1862 The exact functionality is system dependent.
1863
Thomas Heller2fadaa22008-06-16 19:56:33 +00001864
1865.. function:: find_msvcrt()
1866 :module: ctypes.util
1867
Georg Brandl1d837bc2009-12-29 11:24:00 +00001868 Windows only: return the filename of the VC runtype library used by Python,
1869 and by the extension modules. If the name of the library cannot be
1870 determined, ``None`` is returned.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001871
Georg Brandl1d837bc2009-12-29 11:24:00 +00001872 If you need to free memory, for example, allocated by an extension module
1873 with a call to the ``free(void *)``, it is important that you use the
1874 function in the same library that allocated the memory.
1875
Thomas Heller2fadaa22008-06-16 19:56:33 +00001876
Georg Brandl116aa622007-08-15 14:28:22 +00001877.. function:: FormatError([code])
1878
Georg Brandl1d837bc2009-12-29 11:24:00 +00001879 Windows only: Returns a textual description of the error code *code*. If no
1880 error code is specified, the last error code is used by calling the Windows
1881 api function GetLastError.
Georg Brandl116aa622007-08-15 14:28:22 +00001882
1883
1884.. function:: GetLastError()
1885
1886 Windows only: Returns the last error code set by Windows in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001887 This function calls the Windows `GetLastError()` function directly,
1888 it does not return the ctypes-private copy of the error code.
Georg Brandl116aa622007-08-15 14:28:22 +00001889
Thomas Hellerb795f5282008-06-10 15:26:58 +00001890.. function:: get_errno()
1891
1892 Returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001893 :data:`errno` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001894
Thomas Hellerb795f5282008-06-10 15:26:58 +00001895.. function:: get_last_error()
1896
1897 Windows only: returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001898 :data:`LastError` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001899
Georg Brandl116aa622007-08-15 14:28:22 +00001900.. function:: memmove(dst, src, count)
1901
1902 Same as the standard C memmove library function: copies *count* bytes from
Georg Brandl1d837bc2009-12-29 11:24:00 +00001903 *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can
1904 be converted to pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001905
1906
1907.. function:: memset(dst, c, count)
1908
1909 Same as the standard C memset library function: fills the memory block at
1910 address *dst* with *count* bytes of value *c*. *dst* must be an integer
1911 specifying an address, or a ctypes instance.
1912
1913
1914.. function:: POINTER(type)
1915
1916 This factory function creates and returns a new ctypes pointer type. Pointer
1917 types are cached an reused internally, so calling this function repeatedly is
Georg Brandl1d837bc2009-12-29 11:24:00 +00001918 cheap. *type* must be a ctypes type.
Georg Brandl116aa622007-08-15 14:28:22 +00001919
1920
1921.. function:: pointer(obj)
1922
Georg Brandl8d8f1972009-06-08 13:27:23 +00001923 This function creates a new pointer instance, pointing to *obj*. The returned
Georg Brandl1d837bc2009-12-29 11:24:00 +00001924 object is of the type ``POINTER(type(obj))``.
Georg Brandl116aa622007-08-15 14:28:22 +00001925
1926 Note: If you just want to pass a pointer to an object to a foreign function
1927 call, you should use ``byref(obj)`` which is much faster.
1928
1929
1930.. function:: resize(obj, size)
1931
Georg Brandl1d837bc2009-12-29 11:24:00 +00001932 This function resizes the internal memory buffer of *obj*, which must be an
1933 instance of a ctypes type. It is not possible to make the buffer smaller
1934 than the native size of the objects type, as given by ``sizeof(type(obj))``,
1935 but it is possible to enlarge the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00001936
1937
Thomas Hellerb795f5282008-06-10 15:26:58 +00001938.. function:: set_errno(value)
1939
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001940 Set the current value of the ctypes-private copy of the system :data:`errno`
1941 variable in the calling thread to *value* and return the previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001942
Georg Brandl8d8f1972009-06-08 13:27:23 +00001943
Georg Brandl1d837bc2009-12-29 11:24:00 +00001944
Thomas Hellerb795f5282008-06-10 15:26:58 +00001945.. function:: set_last_error(value)
1946
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001947 Windows only: set the current value of the ctypes-private copy of the system
1948 :data:`LastError` variable in the calling thread to *value* and return the
1949 previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001950
Georg Brandl8d8f1972009-06-08 13:27:23 +00001951
Georg Brandl1d837bc2009-12-29 11:24:00 +00001952
Georg Brandl116aa622007-08-15 14:28:22 +00001953.. function:: sizeof(obj_or_type)
1954
1955 Returns the size in bytes of a ctypes type or instance memory buffer. Does the
1956 same as the C ``sizeof()`` function.
1957
1958
Georg Brandl8d8f1972009-06-08 13:27:23 +00001959.. function:: string_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001960
Ezio Melottie130a522011-10-19 10:58:56 +03001961 This function returns the C string starting at memory address *address* as a bytes
Georg Brandl8d8f1972009-06-08 13:27:23 +00001962 object. If size is specified, it is used as size, otherwise the string is assumed
1963 to be zero-terminated.
Georg Brandl116aa622007-08-15 14:28:22 +00001964
1965
1966.. function:: WinError(code=None, descr=None)
1967
1968 Windows only: this function is probably the worst-named thing in ctypes. It
Georg Brandl8d8f1972009-06-08 13:27:23 +00001969 creates an instance of WindowsError. If *code* is not specified,
Georg Brandl1d837bc2009-12-29 11:24:00 +00001970 ``GetLastError`` is called to determine the error code. If *descr* is not
Thomas Woutersed03b412007-08-28 21:37:11 +00001971 specified, :func:`FormatError` is called to get a textual description of the
Georg Brandl116aa622007-08-15 14:28:22 +00001972 error.
1973
1974
Georg Brandl8d8f1972009-06-08 13:27:23 +00001975.. function:: wstring_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001976
1977 This function returns the wide character string starting at memory address
Georg Brandl1d837bc2009-12-29 11:24:00 +00001978 *address* as a string. If *size* is specified, it is used as the number of
1979 characters of the string, otherwise the string is assumed to be
Georg Brandl116aa622007-08-15 14:28:22 +00001980 zero-terminated.
1981
1982
1983.. _ctypes-data-types:
1984
1985Data types
1986^^^^^^^^^^
1987
1988
1989.. class:: _CData
1990
Georg Brandl1d837bc2009-12-29 11:24:00 +00001991 This non-public class is the common base class of all ctypes data types.
1992 Among other things, all ctypes type instances contain a memory block that
1993 hold C compatible data; the address of the memory block is returned by the
Georg Brandl8d8f1972009-06-08 13:27:23 +00001994 :func:`addressof` helper function. Another instance variable is exposed as
Georg Brandl1d837bc2009-12-29 11:24:00 +00001995 :attr:`_objects`; this contains other Python objects that need to be kept
1996 alive in case the memory block contains pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001997
Benjamin Petersone41251e2008-04-25 01:59:09 +00001998 Common methods of ctypes data types, these are all class methods (to be
1999 exact, they are methods of the :term:`metaclass`):
Georg Brandl116aa622007-08-15 14:28:22 +00002000
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002001 .. method:: _CData.from_buffer(source[, offset])
2002
Georg Brandl1d837bc2009-12-29 11:24:00 +00002003 This method returns a ctypes instance that shares the buffer of the
2004 *source* object. The *source* object must support the writeable buffer
2005 interface. The optional *offset* parameter specifies an offset into the
2006 source buffer in bytes; the default is zero. If the source buffer is not
2007 large enough a :exc:`ValueError` is raised.
2008
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002009
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002010 .. method:: _CData.from_buffer_copy(source[, offset])
2011
Georg Brandl1d837bc2009-12-29 11:24:00 +00002012 This method creates a ctypes instance, copying the buffer from the
2013 *source* object buffer which must be readable. The optional *offset*
2014 parameter specifies an offset into the source buffer in bytes; the default
2015 is zero. If the source buffer is not large enough a :exc:`ValueError` is
2016 raised.
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002017
Benjamin Petersone41251e2008-04-25 01:59:09 +00002018 .. method:: from_address(address)
Georg Brandl116aa622007-08-15 14:28:22 +00002019
Benjamin Petersone41251e2008-04-25 01:59:09 +00002020 This method returns a ctypes type instance using the memory specified by
Georg Brandl1d837bc2009-12-29 11:24:00 +00002021 *address* which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00002022
Benjamin Petersone41251e2008-04-25 01:59:09 +00002023 .. method:: from_param(obj)
Georg Brandl116aa622007-08-15 14:28:22 +00002024
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002025 This method adapts *obj* to a ctypes type. It is called with the actual
2026 object used in a foreign function call when the type is present in the
2027 foreign function's :attr:`argtypes` tuple; it must return an object that
2028 can be used as a function call parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00002029
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002030 All ctypes data types have a default implementation of this classmethod
Georg Brandl8d8f1972009-06-08 13:27:23 +00002031 that normally returns *obj* if that is an instance of the type. Some
Benjamin Petersone41251e2008-04-25 01:59:09 +00002032 types accept other objects as well.
Georg Brandl116aa622007-08-15 14:28:22 +00002033
Benjamin Petersone41251e2008-04-25 01:59:09 +00002034 .. method:: in_dll(library, name)
Georg Brandl116aa622007-08-15 14:28:22 +00002035
Benjamin Petersone41251e2008-04-25 01:59:09 +00002036 This method returns a ctypes type instance exported by a shared
2037 library. *name* is the name of the symbol that exports the data, *library*
2038 is the loaded shared library.
Georg Brandl116aa622007-08-15 14:28:22 +00002039
Benjamin Petersone41251e2008-04-25 01:59:09 +00002040 Common instance variables of ctypes data types:
Georg Brandl116aa622007-08-15 14:28:22 +00002041
Benjamin Petersone41251e2008-04-25 01:59:09 +00002042 .. attribute:: _b_base_
Georg Brandl116aa622007-08-15 14:28:22 +00002043
Benjamin Petersone41251e2008-04-25 01:59:09 +00002044 Sometimes ctypes data instances do not own the memory block they contain,
2045 instead they share part of the memory block of a base object. The
2046 :attr:`_b_base_` read-only member is the root ctypes object that owns the
2047 memory block.
Georg Brandl116aa622007-08-15 14:28:22 +00002048
Benjamin Petersone41251e2008-04-25 01:59:09 +00002049 .. attribute:: _b_needsfree_
Georg Brandl116aa622007-08-15 14:28:22 +00002050
Benjamin Petersone41251e2008-04-25 01:59:09 +00002051 This read-only variable is true when the ctypes data instance has
2052 allocated the memory block itself, false otherwise.
2053
Benjamin Petersone41251e2008-04-25 01:59:09 +00002054 .. attribute:: _objects
2055
2056 This member is either ``None`` or a dictionary containing Python objects
2057 that need to be kept alive so that the memory block contents is kept
2058 valid. This object is only exposed for debugging; never modify the
2059 contents of this dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002060
2061
2062.. _ctypes-fundamental-data-types-2:
2063
2064Fundamental data types
2065^^^^^^^^^^^^^^^^^^^^^^
2066
Georg Brandl116aa622007-08-15 14:28:22 +00002067.. class:: _SimpleCData
2068
Benjamin Peterson35e8c462008-04-24 02:34:53 +00002069 This non-public class is the base class of all fundamental ctypes data
2070 types. It is mentioned here because it contains the common attributes of the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002071 fundamental ctypes data types. :class:`_SimpleCData` is a subclass of
2072 :class:`_CData`, so it inherits their methods and attributes. ctypes data
2073 types that are not and do not contain pointers can now be pickled.
Thomas Heller13394e92008-02-13 20:40:44 +00002074
Benjamin Petersone41251e2008-04-25 01:59:09 +00002075 Instances have a single attribute:
Georg Brandl116aa622007-08-15 14:28:22 +00002076
Benjamin Petersone41251e2008-04-25 01:59:09 +00002077 .. attribute:: value
Georg Brandl116aa622007-08-15 14:28:22 +00002078
Benjamin Petersone41251e2008-04-25 01:59:09 +00002079 This attribute contains the actual value of the instance. For integer and
2080 pointer types, it is an integer, for character types, it is a single
Georg Brandl8d8f1972009-06-08 13:27:23 +00002081 character bytes object or string, for character pointer types it is a
2082 Python bytes object or string.
Georg Brandl116aa622007-08-15 14:28:22 +00002083
Benjamin Petersone41251e2008-04-25 01:59:09 +00002084 When the ``value`` attribute is retrieved from a ctypes instance, usually
Georg Brandl8d8f1972009-06-08 13:27:23 +00002085 a new object is returned each time. :mod:`ctypes` does *not* implement
Benjamin Petersone41251e2008-04-25 01:59:09 +00002086 original object return, always a new object is constructed. The same is
2087 true for all other ctypes object instances.
Georg Brandl116aa622007-08-15 14:28:22 +00002088
Georg Brandl8d8f1972009-06-08 13:27:23 +00002089
Georg Brandl116aa622007-08-15 14:28:22 +00002090Fundamental data types, when returned as foreign function call results, or, for
2091example, by retrieving structure field members or array items, are transparently
2092converted to native Python types. In other words, if a foreign function has a
Georg Brandl8d8f1972009-06-08 13:27:23 +00002093:attr:`restype` of :class:`c_char_p`, you will always receive a Python bytes
2094object, *not* a :class:`c_char_p` instance.
2095
2096.. XXX above is false, it actually returns a Unicode string
Georg Brandl116aa622007-08-15 14:28:22 +00002097
Thomas Woutersed03b412007-08-28 21:37:11 +00002098Subclasses of fundamental data types do *not* inherit this behavior. So, if a
Georg Brandl116aa622007-08-15 14:28:22 +00002099foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2100receive an instance of this subclass from the function call. Of course, you can
2101get the value of the pointer by accessing the ``value`` attribute.
2102
2103These are the fundamental ctypes data types:
2104
Georg Brandl116aa622007-08-15 14:28:22 +00002105.. class:: c_byte
2106
Georg Brandl60203b42010-10-06 10:11:56 +00002107 Represents the C :c:type:`signed char` datatype, and interprets the value as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002108 small integer. The constructor accepts an optional integer initializer; no
2109 overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002110
2111
2112.. class:: c_char
2113
Georg Brandl60203b42010-10-06 10:11:56 +00002114 Represents the C :c:type:`char` datatype, and interprets the value as a single
Georg Brandl1d837bc2009-12-29 11:24:00 +00002115 character. The constructor accepts an optional string initializer, the
2116 length of the string must be exactly one character.
Georg Brandl116aa622007-08-15 14:28:22 +00002117
2118
2119.. class:: c_char_p
2120
Georg Brandl60203b42010-10-06 10:11:56 +00002121 Represents the C :c:type:`char *` datatype when it points to a zero-terminated
Georg Brandl1d837bc2009-12-29 11:24:00 +00002122 string. For a general character pointer that may also point to binary data,
2123 ``POINTER(c_char)`` must be used. The constructor accepts an integer
2124 address, or a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +00002125
2126
2127.. class:: c_double
2128
Georg Brandl60203b42010-10-06 10:11:56 +00002129 Represents the C :c:type:`double` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002130 optional float initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002131
2132
Thomas Wouters89d996e2007-09-08 17:39:28 +00002133.. class:: c_longdouble
2134
Georg Brandl60203b42010-10-06 10:11:56 +00002135 Represents the C :c:type:`long double` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002136 optional float initializer. On platforms where ``sizeof(long double) ==
2137 sizeof(double)`` it is an alias to :class:`c_double`.
Thomas Wouters89d996e2007-09-08 17:39:28 +00002138
Georg Brandl116aa622007-08-15 14:28:22 +00002139.. class:: c_float
2140
Georg Brandl60203b42010-10-06 10:11:56 +00002141 Represents the C :c:type:`float` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002142 optional float initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002143
2144
2145.. class:: c_int
2146
Georg Brandl60203b42010-10-06 10:11:56 +00002147 Represents the C :c:type:`signed int` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002148 optional integer initializer; no overflow checking is done. On platforms
2149 where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
Georg Brandl116aa622007-08-15 14:28:22 +00002150
2151
2152.. class:: c_int8
2153
Georg Brandl60203b42010-10-06 10:11:56 +00002154 Represents the C 8-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002155 :class:`c_byte`.
2156
2157
2158.. class:: c_int16
2159
Georg Brandl60203b42010-10-06 10:11:56 +00002160 Represents the C 16-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002161 :class:`c_short`.
2162
2163
2164.. class:: c_int32
2165
Georg Brandl60203b42010-10-06 10:11:56 +00002166 Represents the C 32-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002167 :class:`c_int`.
2168
2169
2170.. class:: c_int64
2171
Georg Brandl60203b42010-10-06 10:11:56 +00002172 Represents the C 64-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002173 :class:`c_longlong`.
2174
2175
2176.. class:: c_long
2177
Georg Brandl60203b42010-10-06 10:11:56 +00002178 Represents the C :c:type:`signed long` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002179 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002180
2181
2182.. class:: c_longlong
2183
Georg Brandl60203b42010-10-06 10:11:56 +00002184 Represents the C :c:type:`signed long long` datatype. The constructor accepts
Georg Brandl1d837bc2009-12-29 11:24:00 +00002185 an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002186
2187
2188.. class:: c_short
2189
Georg Brandl60203b42010-10-06 10:11:56 +00002190 Represents the C :c:type:`signed short` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002191 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002192
2193
2194.. class:: c_size_t
2195
Georg Brandl60203b42010-10-06 10:11:56 +00002196 Represents the C :c:type:`size_t` datatype.
Georg Brandl116aa622007-08-15 14:28:22 +00002197
2198
Gregory P. Smith1a530912010-03-01 04:59:27 +00002199.. class:: c_ssize_t
2200
Georg Brandl60203b42010-10-06 10:11:56 +00002201 Represents the C :c:type:`ssize_t` datatype.
Gregory P. Smith1a530912010-03-01 04:59:27 +00002202
2203 .. versionadded:: 3.2
2204
2205
Georg Brandl116aa622007-08-15 14:28:22 +00002206.. class:: c_ubyte
2207
Georg Brandl60203b42010-10-06 10:11:56 +00002208 Represents the C :c:type:`unsigned char` datatype, it interprets the value as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002209 small integer. The constructor accepts an optional integer initializer; no
2210 overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002211
2212
2213.. class:: c_uint
2214
Georg Brandl60203b42010-10-06 10:11:56 +00002215 Represents the C :c:type:`unsigned int` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002216 optional integer initializer; no overflow checking is done. On platforms
2217 where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
Georg Brandl116aa622007-08-15 14:28:22 +00002218
2219
2220.. class:: c_uint8
2221
Georg Brandl60203b42010-10-06 10:11:56 +00002222 Represents the C 8-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002223 :class:`c_ubyte`.
2224
2225
2226.. class:: c_uint16
2227
Georg Brandl60203b42010-10-06 10:11:56 +00002228 Represents the C 16-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002229 :class:`c_ushort`.
2230
2231
2232.. class:: c_uint32
2233
Georg Brandl60203b42010-10-06 10:11:56 +00002234 Represents the C 32-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002235 :class:`c_uint`.
2236
2237
2238.. class:: c_uint64
2239
Georg Brandl60203b42010-10-06 10:11:56 +00002240 Represents the C 64-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002241 :class:`c_ulonglong`.
2242
2243
2244.. class:: c_ulong
2245
Georg Brandl60203b42010-10-06 10:11:56 +00002246 Represents the C :c:type:`unsigned long` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002247 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002248
2249
2250.. class:: c_ulonglong
2251
Georg Brandl60203b42010-10-06 10:11:56 +00002252 Represents the C :c:type:`unsigned long long` datatype. The constructor
Georg Brandl1d837bc2009-12-29 11:24:00 +00002253 accepts an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002254
2255
2256.. class:: c_ushort
2257
Georg Brandl60203b42010-10-06 10:11:56 +00002258 Represents the C :c:type:`unsigned short` datatype. The constructor accepts
Georg Brandl1d837bc2009-12-29 11:24:00 +00002259 an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002260
2261
2262.. class:: c_void_p
2263
Georg Brandl60203b42010-10-06 10:11:56 +00002264 Represents the C :c:type:`void *` type. The value is represented as integer.
Georg Brandl1d837bc2009-12-29 11:24:00 +00002265 The constructor accepts an optional integer initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002266
2267
2268.. class:: c_wchar
2269
Georg Brandl60203b42010-10-06 10:11:56 +00002270 Represents the C :c:type:`wchar_t` datatype, and interprets the value as a
Georg Brandl1d837bc2009-12-29 11:24:00 +00002271 single character unicode string. The constructor accepts an optional string
Georg Brandl116aa622007-08-15 14:28:22 +00002272 initializer, the length of the string must be exactly one character.
2273
2274
2275.. class:: c_wchar_p
2276
Georg Brandl60203b42010-10-06 10:11:56 +00002277 Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a
Georg Brandl1d837bc2009-12-29 11:24:00 +00002278 zero-terminated wide character string. The constructor accepts an integer
Georg Brandl116aa622007-08-15 14:28:22 +00002279 address, or a string.
2280
2281
2282.. class:: c_bool
2283
Georg Brandl60203b42010-10-06 10:11:56 +00002284 Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from
Georg Brandl1d837bc2009-12-29 11:24:00 +00002285 C99). Its value can be True or False, and the constructor accepts any object
2286 that has a truth value.
Georg Brandl116aa622007-08-15 14:28:22 +00002287
Georg Brandl116aa622007-08-15 14:28:22 +00002288
2289.. class:: HRESULT
2290
Georg Brandl60203b42010-10-06 10:11:56 +00002291 Windows only: Represents a :c:type:`HRESULT` value, which contains success or
Georg Brandl116aa622007-08-15 14:28:22 +00002292 error information for a function or method call.
2293
2294
2295.. class:: py_object
2296
Georg Brandl60203b42010-10-06 10:11:56 +00002297 Represents the C :c:type:`PyObject *` datatype. Calling this without an
2298 argument creates a ``NULL`` :c:type:`PyObject *` pointer.
Georg Brandl116aa622007-08-15 14:28:22 +00002299
Georg Brandl1d837bc2009-12-29 11:24:00 +00002300The :mod:`ctypes.wintypes` module provides quite some other Windows specific
Georg Brandl60203b42010-10-06 10:11:56 +00002301data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`. Some
2302useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined.
Georg Brandl116aa622007-08-15 14:28:22 +00002303
2304
2305.. _ctypes-structured-data-types:
2306
2307Structured data types
2308^^^^^^^^^^^^^^^^^^^^^
2309
2310
2311.. class:: Union(*args, **kw)
2312
2313 Abstract base class for unions in native byte order.
2314
2315
2316.. class:: BigEndianStructure(*args, **kw)
2317
2318 Abstract base class for structures in *big endian* byte order.
2319
2320
2321.. class:: LittleEndianStructure(*args, **kw)
2322
2323 Abstract base class for structures in *little endian* byte order.
2324
2325Structures with non-native byte order cannot contain pointer type fields, or any
2326other data types containing pointer type fields.
2327
2328
2329.. class:: Structure(*args, **kw)
2330
2331 Abstract base class for structures in *native* byte order.
2332
Benjamin Petersone41251e2008-04-25 01:59:09 +00002333 Concrete structure and union types must be created by subclassing one of these
Georg Brandl8d8f1972009-06-08 13:27:23 +00002334 types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
Benjamin Petersone41251e2008-04-25 01:59:09 +00002335 create :term:`descriptor`\s which allow reading and writing the fields by direct
2336 attribute accesses. These are the
Georg Brandl116aa622007-08-15 14:28:22 +00002337
2338
Benjamin Petersone41251e2008-04-25 01:59:09 +00002339 .. attribute:: _fields_
Georg Brandl116aa622007-08-15 14:28:22 +00002340
Benjamin Petersone41251e2008-04-25 01:59:09 +00002341 A sequence defining the structure fields. The items must be 2-tuples or
2342 3-tuples. The first item is the name of the field, the second item
2343 specifies the type of the field; it can be any ctypes data type.
Georg Brandl116aa622007-08-15 14:28:22 +00002344
Benjamin Petersone41251e2008-04-25 01:59:09 +00002345 For integer type fields like :class:`c_int`, a third optional item can be
2346 given. It must be a small positive integer defining the bit width of the
2347 field.
Georg Brandl116aa622007-08-15 14:28:22 +00002348
Benjamin Petersone41251e2008-04-25 01:59:09 +00002349 Field names must be unique within one structure or union. This is not
2350 checked, only one field can be accessed when names are repeated.
Georg Brandl116aa622007-08-15 14:28:22 +00002351
Benjamin Petersone41251e2008-04-25 01:59:09 +00002352 It is possible to define the :attr:`_fields_` class variable *after* the
2353 class statement that defines the Structure subclass, this allows to create
2354 data types that directly or indirectly reference themselves::
Georg Brandl116aa622007-08-15 14:28:22 +00002355
Benjamin Petersone41251e2008-04-25 01:59:09 +00002356 class List(Structure):
2357 pass
2358 List._fields_ = [("pnext", POINTER(List)),
2359 ...
2360 ]
Georg Brandl116aa622007-08-15 14:28:22 +00002361
Benjamin Petersone41251e2008-04-25 01:59:09 +00002362 The :attr:`_fields_` class variable must, however, be defined before the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002363 type is first used (an instance is created, :func:`sizeof` is called on it,
Benjamin Petersone41251e2008-04-25 01:59:09 +00002364 and so on). Later assignments to the :attr:`_fields_` class variable will
2365 raise an AttributeError.
Georg Brandl116aa622007-08-15 14:28:22 +00002366
Benjamin Petersone41251e2008-04-25 01:59:09 +00002367 Structure and union subclass constructors accept both positional and named
2368 arguments. Positional arguments are used to initialize the fields in the
2369 same order as they appear in the :attr:`_fields_` definition, named
2370 arguments are used to initialize the fields with the corresponding name.
Georg Brandl116aa622007-08-15 14:28:22 +00002371
Benjamin Petersone41251e2008-04-25 01:59:09 +00002372 It is possible to defined sub-subclasses of structure types, they inherit
2373 the fields of the base class plus the :attr:`_fields_` defined in the
2374 sub-subclass, if any.
Georg Brandl116aa622007-08-15 14:28:22 +00002375
2376
Benjamin Petersone41251e2008-04-25 01:59:09 +00002377 .. attribute:: _pack_
Georg Brandl116aa622007-08-15 14:28:22 +00002378
Benjamin Petersone41251e2008-04-25 01:59:09 +00002379 An optional small integer that allows to override the alignment of
2380 structure fields in the instance. :attr:`_pack_` must already be defined
2381 when :attr:`_fields_` is assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002382
2383
Benjamin Petersone41251e2008-04-25 01:59:09 +00002384 .. attribute:: _anonymous_
Georg Brandl116aa622007-08-15 14:28:22 +00002385
Benjamin Petersone41251e2008-04-25 01:59:09 +00002386 An optional sequence that lists the names of unnamed (anonymous) fields.
Georg Brandl1d837bc2009-12-29 11:24:00 +00002387 :attr:`_anonymous_` must be already defined when :attr:`_fields_` is
2388 assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002389
Benjamin Petersone41251e2008-04-25 01:59:09 +00002390 The fields listed in this variable must be structure or union type fields.
Georg Brandl8d8f1972009-06-08 13:27:23 +00002391 :mod:`ctypes` will create descriptors in the structure type that allows to
Benjamin Petersone41251e2008-04-25 01:59:09 +00002392 access the nested fields directly, without the need to create the
2393 structure or union field.
Georg Brandl116aa622007-08-15 14:28:22 +00002394
Benjamin Petersone41251e2008-04-25 01:59:09 +00002395 Here is an example type (Windows)::
Georg Brandl116aa622007-08-15 14:28:22 +00002396
Benjamin Petersone41251e2008-04-25 01:59:09 +00002397 class _U(Union):
2398 _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2399 ("lpadesc", POINTER(ARRAYDESC)),
2400 ("hreftype", HREFTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002401
Benjamin Petersone41251e2008-04-25 01:59:09 +00002402 class TYPEDESC(Structure):
Benjamin Petersonb58dda72009-01-18 22:27:04 +00002403 _anonymous_ = ("u",)
Benjamin Petersone41251e2008-04-25 01:59:09 +00002404 _fields_ = [("u", _U),
2405 ("vt", VARTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002406
Georg Brandl116aa622007-08-15 14:28:22 +00002407
Benjamin Petersone41251e2008-04-25 01:59:09 +00002408 The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2409 specifies which one of the union fields is valid. Since the ``u`` field
2410 is defined as anonymous field, it is now possible to access the members
2411 directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2412 are equivalent, but the former is faster since it does not need to create
2413 a temporary union instance::
Georg Brandl116aa622007-08-15 14:28:22 +00002414
Benjamin Petersone41251e2008-04-25 01:59:09 +00002415 td = TYPEDESC()
2416 td.vt = VT_PTR
2417 td.lptdesc = POINTER(some_type)
2418 td.u.lptdesc = POINTER(some_type)
Georg Brandl116aa622007-08-15 14:28:22 +00002419
Georg Brandl1d837bc2009-12-29 11:24:00 +00002420 It is possible to defined sub-subclasses of structures, they inherit the
2421 fields of the base class. If the subclass definition has a separate
2422 :attr:`_fields_` variable, the fields specified in this are appended to the
2423 fields of the base class.
Georg Brandl116aa622007-08-15 14:28:22 +00002424
Georg Brandl1d837bc2009-12-29 11:24:00 +00002425 Structure and union constructors accept both positional and keyword
2426 arguments. Positional arguments are used to initialize member fields in the
2427 same order as they are appear in :attr:`_fields_`. Keyword arguments in the
2428 constructor are interpreted as attribute assignments, so they will initialize
2429 :attr:`_fields_` with the same name, or create new attributes for names not
2430 present in :attr:`_fields_`.
Georg Brandl116aa622007-08-15 14:28:22 +00002431
2432
2433.. _ctypes-arrays-pointers:
2434
2435Arrays and pointers
2436^^^^^^^^^^^^^^^^^^^
2437
Georg Brandl1d837bc2009-12-29 11:24:00 +00002438Not yet written - please see the sections :ref:`ctypes-pointers` and section
2439:ref:`ctypes-arrays` in the tutorial.
Georg Brandl116aa622007-08-15 14:28:22 +00002440