blob: 8a22e948234e10180e027863d03cd84f6c2c69d6 [file] [log] [blame]
Georg Brandl71515ca2009-05-17 12:29:12 +00001:mod:`ctypes` --- A foreign function library for Python
2=======================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: ctypes
5 :synopsis: A foreign function library for Python.
6.. moduleauthor:: Thomas Heller <theller@python.net>
7
8
Georg Brandl1d837bc2009-12-29 11:24:00 +00009:mod:`ctypes` is a foreign function library for Python. It provides C compatible
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000010data types, and allows calling functions in DLLs or shared libraries. It can be
Georg Brandl116aa622007-08-15 14:28:22 +000011used to wrap these libraries in pure Python.
12
13
14.. _ctypes-ctypes-tutorial:
15
16ctypes tutorial
17---------------
18
Georg Brandl1d837bc2009-12-29 11:24:00 +000019Note: The code samples in this tutorial use :mod:`doctest` to make sure that
20they actually work. Since some code samples behave differently under Linux,
21Windows, or Mac OS X, they contain doctest directives in comments.
Georg Brandl116aa622007-08-15 14:28:22 +000022
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000023Note: Some code samples reference the ctypes :class:`c_int` type. This type is
24an alias for the :class:`c_long` type on 32-bit systems. So, you should not be
Georg Brandl116aa622007-08-15 14:28:22 +000025confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
26they are actually the same type.
27
28
29.. _ctypes-loading-dynamic-link-libraries:
30
31Loading dynamic link libraries
32^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
33
Georg Brandl8d8f1972009-06-08 13:27:23 +000034:mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll*
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000035objects, for loading dynamic link libraries.
Georg Brandl116aa622007-08-15 14:28:22 +000036
37You load libraries by accessing them as attributes of these objects. *cdll*
38loads libraries which export functions using the standard ``cdecl`` calling
39convention, while *windll* libraries call functions using the ``stdcall``
40calling convention. *oledll* also uses the ``stdcall`` calling convention, and
Georg Brandl60203b42010-10-06 10:11:56 +000041assumes the functions return a Windows :c:type:`HRESULT` error code. The error
Antoine Pitrou442ee032011-10-12 18:53:23 +020042code is used to automatically raise a :class:`OSError` exception when the
Georg Brandl1d837bc2009-12-29 11:24:00 +000043function call fails.
Georg Brandl116aa622007-08-15 14:28:22 +000044
Antoine Pitrou442ee032011-10-12 18:53:23 +020045.. versionchanged:: 3.3
46 Windows errors used to raise :exc:`WindowsError`, which is now an alias
47 of :exc:`OSError`.
48
49
Georg Brandl116aa622007-08-15 14:28:22 +000050Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
51library containing most standard C functions, and uses the cdecl calling
52convention::
53
54 >>> from ctypes import *
Georg Brandl6911e3c2007-09-04 07:15:32 +000055 >>> print(windll.kernel32) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000056 <WinDLL 'kernel32', handle ... at ...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000057 >>> print(cdll.msvcrt) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000058 <CDLL 'msvcrt', handle ... at ...>
59 >>> libc = cdll.msvcrt # doctest: +WINDOWS
60 >>>
61
Thomas Heller2fadaa22008-06-16 19:56:33 +000062Windows appends the usual ``.dll`` file suffix automatically.
Georg Brandl116aa622007-08-15 14:28:22 +000063
64On Linux, it is required to specify the filename *including* the extension to
Thomas Heller2fadaa22008-06-16 19:56:33 +000065load a library, so attribute access can not be used to load libraries. Either the
Georg Brandl116aa622007-08-15 14:28:22 +000066:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
67the library by creating an instance of CDLL by calling the constructor::
68
69 >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
70 <CDLL 'libc.so.6', handle ... at ...>
71 >>> libc = CDLL("libc.so.6") # doctest: +LINUX
72 >>> libc # doctest: +LINUX
73 <CDLL 'libc.so.6', handle ... at ...>
74 >>>
75
Christian Heimes5b5e81c2007-12-31 16:14:33 +000076.. XXX Add section for Mac OS X.
Georg Brandl116aa622007-08-15 14:28:22 +000077
78
79.. _ctypes-accessing-functions-from-loaded-dlls:
80
81Accessing functions from loaded dlls
82^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
83
84Functions are accessed as attributes of dll objects::
85
86 >>> from ctypes import *
87 >>> libc.printf
88 <_FuncPtr object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000089 >>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000090 <_FuncPtr object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000091 >>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000092 Traceback (most recent call last):
93 File "<stdin>", line 1, in ?
94 File "ctypes.py", line 239, in __getattr__
95 func = _StdcallFuncPtr(name, self)
96 AttributeError: function 'MyOwnFunction' not found
97 >>>
98
99Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
100as well as UNICODE versions of a function. The UNICODE version is exported with
101an ``W`` appended to the name, while the ANSI version is exported with an ``A``
102appended to the name. The win32 ``GetModuleHandle`` function, which returns a
103*module handle* for a given module name, has the following C prototype, and a
104macro is used to expose one of them as ``GetModuleHandle`` depending on whether
105UNICODE is defined or not::
106
107 /* ANSI version */
108 HMODULE GetModuleHandleA(LPCSTR lpModuleName);
109 /* UNICODE version */
110 HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
111
112*windll* does not try to select one of them by magic, you must access the
113version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
Georg Brandl8d8f1972009-06-08 13:27:23 +0000114explicitly, and then call it with bytes or string objects respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116Sometimes, dlls export functions with names which aren't valid Python
Georg Brandl1d837bc2009-12-29 11:24:00 +0000117identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
118:func:`getattr` to retrieve the function::
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120 >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
121 <_FuncPtr object at 0x...>
122 >>>
123
124On Windows, some dlls export functions not by name but by ordinal. These
125functions can be accessed by indexing the dll object with the ordinal number::
126
127 >>> cdll.kernel32[1] # doctest: +WINDOWS
128 <_FuncPtr object at 0x...>
129 >>> cdll.kernel32[0] # doctest: +WINDOWS
130 Traceback (most recent call last):
131 File "<stdin>", line 1, in ?
132 File "ctypes.py", line 310, in __getitem__
133 func = _StdcallFuncPtr(name, self)
134 AttributeError: function ordinal 0 not found
135 >>>
136
137
138.. _ctypes-calling-functions:
139
140Calling functions
141^^^^^^^^^^^^^^^^^
142
143You can call these functions like any other Python callable. This example uses
144the ``time()`` function, which returns system time in seconds since the Unix
145epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
146handle.
147
148This example calls both functions with a NULL pointer (``None`` should be used
149as the NULL pointer)::
150
Georg Brandl6911e3c2007-09-04 07:15:32 +0000151 >>> print(libc.time(None)) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000152 1150640792
Georg Brandl6911e3c2007-09-04 07:15:32 +0000153 >>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000154 0x1d000000
155 >>>
156
Georg Brandl1d837bc2009-12-29 11:24:00 +0000157:mod:`ctypes` tries to protect you from calling functions with the wrong number
158of arguments or the wrong calling convention. Unfortunately this only works on
Georg Brandl116aa622007-08-15 14:28:22 +0000159Windows. It does this by examining the stack after the function returns, so
160although an error is raised the function *has* been called::
161
162 >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
163 Traceback (most recent call last):
164 File "<stdin>", line 1, in ?
165 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
166 >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
167 Traceback (most recent call last):
168 File "<stdin>", line 1, in ?
169 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
170 >>>
171
172The same exception is raised when you call an ``stdcall`` function with the
173``cdecl`` calling convention, or vice versa::
174
175 >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
176 Traceback (most recent call last):
177 File "<stdin>", line 1, in ?
178 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
179 >>>
180
Georg Brandl8d8f1972009-06-08 13:27:23 +0000181 >>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000182 Traceback (most recent call last):
183 File "<stdin>", line 1, in ?
184 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
185 >>>
186
187To find out the correct calling convention you have to look into the C header
188file or the documentation for the function you want to call.
189
Georg Brandl8d8f1972009-06-08 13:27:23 +0000190On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
Georg Brandl116aa622007-08-15 14:28:22 +0000191crashes from general protection faults when functions are called with invalid
192argument values::
193
194 >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
195 Traceback (most recent call last):
196 File "<stdin>", line 1, in ?
Antoine Pitrou442ee032011-10-12 18:53:23 +0200197 OSError: exception: access violation reading 0x00000020
Georg Brandl116aa622007-08-15 14:28:22 +0000198 >>>
199
Georg Brandl1d837bc2009-12-29 11:24:00 +0000200There are, however, enough ways to crash Python with :mod:`ctypes`, so you
201should be careful anyway.
Georg Brandl116aa622007-08-15 14:28:22 +0000202
Georg Brandl8d8f1972009-06-08 13:27:23 +0000203``None``, integers, bytes objects and (unicode) strings are the only native
Georg Brandl116aa622007-08-15 14:28:22 +0000204Python objects that can directly be used as parameters in these function calls.
Georg Brandl1d837bc2009-12-29 11:24:00 +0000205``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are passed
Georg Brandl60203b42010-10-06 10:11:56 +0000206as pointer to the memory block that contains their data (:c:type:`char *` or
207:c:type:`wchar_t *`). Python integers are passed as the platforms default C
208:c:type:`int` type, their value is masked to fit into the C type.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210Before we move on calling functions with other parameter types, we have to learn
Georg Brandl8d8f1972009-06-08 13:27:23 +0000211more about :mod:`ctypes` data types.
Georg Brandl116aa622007-08-15 14:28:22 +0000212
213
214.. _ctypes-fundamental-data-types:
215
216Fundamental data types
217^^^^^^^^^^^^^^^^^^^^^^
218
Georg Brandl8d8f1972009-06-08 13:27:23 +0000219:mod:`ctypes` defines a number of primitive C compatible data types :
Georg Brandl116aa622007-08-15 14:28:22 +0000220
Georg Brandl60203b42010-10-06 10:11:56 +0000221+----------------------+------------------------------------------+----------------------------+
222| ctypes type | C type | Python type |
223+======================+==========================================+============================+
Georg Brandlecdd63f2011-01-19 20:05:49 +0000224| :class:`c_bool` | :c:type:`_Bool` | bool (1) |
225+----------------------+------------------------------------------+----------------------------+
Georg Brandl60203b42010-10-06 10:11:56 +0000226| :class:`c_char` | :c:type:`char` | 1-character bytes object |
227+----------------------+------------------------------------------+----------------------------+
228| :class:`c_wchar` | :c:type:`wchar_t` | 1-character string |
229+----------------------+------------------------------------------+----------------------------+
230| :class:`c_byte` | :c:type:`char` | int |
231+----------------------+------------------------------------------+----------------------------+
232| :class:`c_ubyte` | :c:type:`unsigned char` | int |
233+----------------------+------------------------------------------+----------------------------+
234| :class:`c_short` | :c:type:`short` | int |
235+----------------------+------------------------------------------+----------------------------+
236| :class:`c_ushort` | :c:type:`unsigned short` | int |
237+----------------------+------------------------------------------+----------------------------+
238| :class:`c_int` | :c:type:`int` | int |
239+----------------------+------------------------------------------+----------------------------+
240| :class:`c_uint` | :c:type:`unsigned int` | int |
241+----------------------+------------------------------------------+----------------------------+
242| :class:`c_long` | :c:type:`long` | int |
243+----------------------+------------------------------------------+----------------------------+
244| :class:`c_ulong` | :c:type:`unsigned long` | int |
245+----------------------+------------------------------------------+----------------------------+
246| :class:`c_longlong` | :c:type:`__int64` or :c:type:`long long` | int |
247+----------------------+------------------------------------------+----------------------------+
248| :class:`c_ulonglong` | :c:type:`unsigned __int64` or | int |
249| | :c:type:`unsigned long long` | |
250+----------------------+------------------------------------------+----------------------------+
251| :class:`c_float` | :c:type:`float` | float |
252+----------------------+------------------------------------------+----------------------------+
253| :class:`c_double` | :c:type:`double` | float |
254+----------------------+------------------------------------------+----------------------------+
255| :class:`c_longdouble`| :c:type:`long double` | float |
256+----------------------+------------------------------------------+----------------------------+
257| :class:`c_char_p` | :c:type:`char *` (NUL terminated) | bytes object or ``None`` |
258+----------------------+------------------------------------------+----------------------------+
259| :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | string or ``None`` |
260+----------------------+------------------------------------------+----------------------------+
261| :class:`c_void_p` | :c:type:`void *` | int or ``None`` |
262+----------------------+------------------------------------------+----------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000263
Georg Brandlecdd63f2011-01-19 20:05:49 +0000264(1)
265 The constructor accepts any object with a truth value.
266
Georg Brandl116aa622007-08-15 14:28:22 +0000267All these types can be created by calling them with an optional initializer of
268the correct type and value::
269
270 >>> c_int()
271 c_long(0)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000272 >>> c_wchar_p("Hello, World")
273 c_wchar_p('Hello, World')
Georg Brandl116aa622007-08-15 14:28:22 +0000274 >>> c_ushort(-3)
275 c_ushort(65533)
276 >>>
277
278Since these types are mutable, their value can also be changed afterwards::
279
280 >>> i = c_int(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000281 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000282 c_long(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000283 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000284 42
285 >>> i.value = -99
Georg Brandl6911e3c2007-09-04 07:15:32 +0000286 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000287 -99
288 >>>
289
290Assigning a new value to instances of the pointer types :class:`c_char_p`,
291:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
292point to, *not the contents* of the memory block (of course not, because Python
Georg Brandl8d8f1972009-06-08 13:27:23 +0000293bytes objects are immutable)::
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295 >>> s = "Hello, World"
Georg Brandl8d8f1972009-06-08 13:27:23 +0000296 >>> c_s = c_wchar_p(s)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000297 >>> print(c_s)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000298 c_wchar_p('Hello, World')
Georg Brandl116aa622007-08-15 14:28:22 +0000299 >>> c_s.value = "Hi, there"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000300 >>> print(c_s)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000301 c_wchar_p('Hi, there')
302 >>> print(s) # first object is unchanged
Georg Brandl116aa622007-08-15 14:28:22 +0000303 Hello, World
304 >>>
305
306You should be careful, however, not to pass them to functions expecting pointers
307to mutable memory. If you need mutable memory blocks, ctypes has a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000308:func:`create_string_buffer` function which creates these in various ways. The
Georg Brandl116aa622007-08-15 14:28:22 +0000309current memory block contents can be accessed (or changed) with the ``raw``
310property; if you want to access it as NUL terminated string, use the ``value``
311property::
312
313 >>> from ctypes import *
Georg Brandl8d8f1972009-06-08 13:27:23 +0000314 >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
Georg Brandl6911e3c2007-09-04 07:15:32 +0000315 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000316 3 b'\x00\x00\x00'
317 >>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string
Georg Brandl6911e3c2007-09-04 07:15:32 +0000318 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000319 6 b'Hello\x00'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000320 >>> print(repr(p.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000321 b'Hello'
322 >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000323 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000324 10 b'Hello\x00\x00\x00\x00\x00'
325 >>> p.value = b"Hi"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000326 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000327 10 b'Hi\x00lo\x00\x00\x00\x00\x00'
Georg Brandl116aa622007-08-15 14:28:22 +0000328 >>>
329
Georg Brandl1d837bc2009-12-29 11:24:00 +0000330The :func:`create_string_buffer` function replaces the :func:`c_buffer` function
331(which is still available as an alias), as well as the :func:`c_string` function
Georg Brandl8d8f1972009-06-08 13:27:23 +0000332from earlier ctypes releases. To create a mutable memory block containing
Georg Brandl60203b42010-10-06 10:11:56 +0000333unicode characters of the C type :c:type:`wchar_t` use the
Georg Brandl8d8f1972009-06-08 13:27:23 +0000334:func:`create_unicode_buffer` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336
337.. _ctypes-calling-functions-continued:
338
339Calling functions, continued
340^^^^^^^^^^^^^^^^^^^^^^^^^^^^
341
342Note that printf prints to the real standard output channel, *not* to
Georg Brandl8d8f1972009-06-08 13:27:23 +0000343:data:`sys.stdout`, so these examples will only work at the console prompt, not
344from within *IDLE* or *PythonWin*::
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346 >>> printf = libc.printf
Georg Brandl8d8f1972009-06-08 13:27:23 +0000347 >>> printf(b"Hello, %s\n", b"World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000348 Hello, World!
349 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000350 >>> printf(b"Hello, %S\n", "World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000351 Hello, World!
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000352 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000353 >>> printf(b"%d bottles of beer\n", 42)
Georg Brandl116aa622007-08-15 14:28:22 +0000354 42 bottles of beer
355 19
Georg Brandl8d8f1972009-06-08 13:27:23 +0000356 >>> printf(b"%f bottles of beer\n", 42.5)
Georg Brandl116aa622007-08-15 14:28:22 +0000357 Traceback (most recent call last):
358 File "<stdin>", line 1, in ?
359 ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
360 >>>
361
362As has been mentioned before, all Python types except integers, strings, and
Georg Brandl8d8f1972009-06-08 13:27:23 +0000363bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so
Georg Brandl116aa622007-08-15 14:28:22 +0000364that they can be converted to the required C data type::
365
Georg Brandl8d8f1972009-06-08 13:27:23 +0000366 >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000367 An int 1234, a double 3.140000
Georg Brandl116aa622007-08-15 14:28:22 +0000368 31
369 >>>
370
371
372.. _ctypes-calling-functions-with-own-custom-data-types:
373
374Calling functions with your own custom data types
375^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
376
Georg Brandl1d837bc2009-12-29 11:24:00 +0000377You can also customize :mod:`ctypes` argument conversion to allow instances of
378your own classes be used as function arguments. :mod:`ctypes` looks for an
379:attr:`_as_parameter_` attribute and uses this as the function argument. Of
Georg Brandl8d8f1972009-06-08 13:27:23 +0000380course, it must be one of integer, string, or bytes::
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Éric Araujo28053fb2010-11-22 03:09:19 +0000382 >>> class Bottles:
Georg Brandl116aa622007-08-15 14:28:22 +0000383 ... def __init__(self, number):
384 ... self._as_parameter_ = number
385 ...
386 >>> bottles = Bottles(42)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000387 >>> printf(b"%d bottles of beer\n", bottles)
Georg Brandl116aa622007-08-15 14:28:22 +0000388 42 bottles of beer
389 19
390 >>>
391
392If you don't want to store the instance's data in the :attr:`_as_parameter_`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000393instance variable, you could define a :class:`property` which makes the
394attribute available on request.
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396
397.. _ctypes-specifying-required-argument-types:
398
399Specifying the required argument types (function prototypes)
400^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
401
402It is possible to specify the required argument types of functions exported from
403DLLs by setting the :attr:`argtypes` attribute.
404
405:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
406probably not a good example here, because it takes a variable number and
407different types of parameters depending on the format string, on the other hand
408this is quite handy to experiment with this feature)::
409
410 >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000411 >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
Georg Brandl116aa622007-08-15 14:28:22 +0000412 String 'Hi', Int 10, Double 2.200000
413 37
414 >>>
415
416Specifying a format protects against incompatible argument types (just as a
417prototype for a C function), and tries to convert the arguments to valid types::
418
Georg Brandl8d8f1972009-06-08 13:27:23 +0000419 >>> printf(b"%d %d %d", 1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000420 Traceback (most recent call last):
421 File "<stdin>", line 1, in ?
422 ArgumentError: argument 2: exceptions.TypeError: wrong type
Georg Brandl8d8f1972009-06-08 13:27:23 +0000423 >>> printf(b"%s %d %f\n", b"X", 2, 3)
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000424 X 2 3.000000
425 13
Georg Brandl116aa622007-08-15 14:28:22 +0000426 >>>
427
428If you have defined your own classes which you pass to function calls, you have
429to implement a :meth:`from_param` class method for them to be able to use them
430in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
431the Python object passed to the function call, it should do a typecheck or
432whatever is needed to make sure this object is acceptable, and then return the
Thomas Heller2fadaa22008-06-16 19:56:33 +0000433object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
Georg Brandl116aa622007-08-15 14:28:22 +0000434pass as the C function argument in this case. Again, the result should be an
Georg Brandl8d8f1972009-06-08 13:27:23 +0000435integer, string, bytes, a :mod:`ctypes` instance, or an object with an
Georg Brandl116aa622007-08-15 14:28:22 +0000436:attr:`_as_parameter_` attribute.
437
438
439.. _ctypes-return-types:
440
441Return types
442^^^^^^^^^^^^
443
Georg Brandl60203b42010-10-06 10:11:56 +0000444By default functions are assumed to return the C :c:type:`int` type. Other
Georg Brandl1d837bc2009-12-29 11:24:00 +0000445return types can be specified by setting the :attr:`restype` attribute of the
446function object.
Georg Brandl116aa622007-08-15 14:28:22 +0000447
448Here is a more advanced example, it uses the ``strchr`` function, which expects
449a string pointer and a char, and returns a pointer to a string::
450
451 >>> strchr = libc.strchr
Georg Brandl8d8f1972009-06-08 13:27:23 +0000452 >>> strchr(b"abcdef", ord("d")) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000453 8059983
Georg Brandl8d8f1972009-06-08 13:27:23 +0000454 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
455 >>> strchr(b"abcdef", ord("d"))
456 b'def'
457 >>> print(strchr(b"abcdef", ord("x")))
Georg Brandl116aa622007-08-15 14:28:22 +0000458 None
459 >>>
460
461If you want to avoid the ``ord("x")`` calls above, you can set the
462:attr:`argtypes` attribute, and the second argument will be converted from a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000463single character Python bytes object into a C char::
Georg Brandl116aa622007-08-15 14:28:22 +0000464
465 >>> strchr.restype = c_char_p
466 >>> strchr.argtypes = [c_char_p, c_char]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000467 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000468 'def'
Georg Brandl8d8f1972009-06-08 13:27:23 +0000469 >>> strchr(b"abcdef", b"def")
Georg Brandl116aa622007-08-15 14:28:22 +0000470 Traceback (most recent call last):
471 File "<stdin>", line 1, in ?
472 ArgumentError: argument 2: exceptions.TypeError: one character string expected
Georg Brandl8d8f1972009-06-08 13:27:23 +0000473 >>> print(strchr(b"abcdef", b"x"))
Georg Brandl116aa622007-08-15 14:28:22 +0000474 None
Georg Brandl8d8f1972009-06-08 13:27:23 +0000475 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000476 'def'
477 >>>
478
479You can also use a callable Python object (a function or a class for example) as
480the :attr:`restype` attribute, if the foreign function returns an integer. The
Georg Brandl1d837bc2009-12-29 11:24:00 +0000481callable will be called with the *integer* the C function returns, and the
Georg Brandl116aa622007-08-15 14:28:22 +0000482result of this call will be used as the result of your function call. This is
483useful to check for error return values and automatically raise an exception::
484
485 >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
486 >>> def ValidHandle(value):
487 ... if value == 0:
488 ... raise WinError()
489 ... return value
490 ...
491 >>>
492 >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
493 >>> GetModuleHandle(None) # doctest: +WINDOWS
494 486539264
495 >>> GetModuleHandle("something silly") # doctest: +WINDOWS
496 Traceback (most recent call last):
497 File "<stdin>", line 1, in ?
498 File "<stdin>", line 3, in ValidHandle
Antoine Pitrou442ee032011-10-12 18:53:23 +0200499 OSError: [Errno 126] The specified module could not be found.
Georg Brandl116aa622007-08-15 14:28:22 +0000500 >>>
501
502``WinError`` is a function which will call Windows ``FormatMessage()`` api to
503get the string representation of an error code, and *returns* an exception.
504``WinError`` takes an optional error code parameter, if no one is used, it calls
505:func:`GetLastError` to retrieve it.
506
507Please note that a much more powerful error checking mechanism is available
508through the :attr:`errcheck` attribute; see the reference manual for details.
509
510
511.. _ctypes-passing-pointers:
512
513Passing pointers (or: passing parameters by reference)
514^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
515
516Sometimes a C api function expects a *pointer* to a data type as parameter,
517probably to write into the corresponding location, or if the data is too large
518to be passed by value. This is also known as *passing parameters by reference*.
519
Georg Brandl8d8f1972009-06-08 13:27:23 +0000520:mod:`ctypes` exports the :func:`byref` function which is used to pass parameters
521by reference. The same effect can be achieved with the :func:`pointer` function,
522although :func:`pointer` does a lot more work since it constructs a real pointer
Georg Brandl116aa622007-08-15 14:28:22 +0000523object, so it is faster to use :func:`byref` if you don't need the pointer
524object in Python itself::
525
526 >>> i = c_int()
527 >>> f = c_float()
Georg Brandl8d8f1972009-06-08 13:27:23 +0000528 >>> s = create_string_buffer(b'\000' * 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000529 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000530 0 0.0 b''
531 >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
Georg Brandl116aa622007-08-15 14:28:22 +0000532 ... byref(i), byref(f), s)
533 3
Georg Brandl6911e3c2007-09-04 07:15:32 +0000534 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000535 1 3.1400001049 b'Hello'
Georg Brandl116aa622007-08-15 14:28:22 +0000536 >>>
537
538
539.. _ctypes-structures-unions:
540
541Structures and unions
542^^^^^^^^^^^^^^^^^^^^^
543
544Structures and unions must derive from the :class:`Structure` and :class:`Union`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000545base classes which are defined in the :mod:`ctypes` module. Each subclass must
Georg Brandl116aa622007-08-15 14:28:22 +0000546define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
547*2-tuples*, containing a *field name* and a *field type*.
548
Georg Brandl8d8f1972009-06-08 13:27:23 +0000549The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
550derived :mod:`ctypes` type: structure, union, array, pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552Here is a simple example of a POINT structure, which contains two integers named
Georg Brandl8d8f1972009-06-08 13:27:23 +0000553*x* and *y*, and also shows how to initialize a structure in the constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000554
555 >>> from ctypes import *
556 >>> class POINT(Structure):
557 ... _fields_ = [("x", c_int),
558 ... ("y", c_int)]
559 ...
560 >>> point = POINT(10, 20)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000561 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000562 10 20
563 >>> point = POINT(y=5)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000564 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000565 0 5
566 >>> POINT(1, 2, 3)
567 Traceback (most recent call last):
568 File "<stdin>", line 1, in ?
569 ValueError: too many initializers
570 >>>
571
572You can, however, build much more complicated structures. Structures can itself
573contain other structures by using a structure as a field type.
574
Georg Brandl1d837bc2009-12-29 11:24:00 +0000575Here is a RECT structure which contains two POINTs named *upperleft* and
576*lowerright*::
Georg Brandl116aa622007-08-15 14:28:22 +0000577
578 >>> class RECT(Structure):
579 ... _fields_ = [("upperleft", POINT),
580 ... ("lowerright", POINT)]
581 ...
582 >>> rc = RECT(point)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000583 >>> print(rc.upperleft.x, rc.upperleft.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000584 0 5
Georg Brandl6911e3c2007-09-04 07:15:32 +0000585 >>> print(rc.lowerright.x, rc.lowerright.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000586 0 0
587 >>>
588
589Nested structures can also be initialized in the constructor in several ways::
590
591 >>> r = RECT(POINT(1, 2), POINT(3, 4))
592 >>> r = RECT((1, 2), (3, 4))
593
Georg Brandl9afde1c2007-11-01 20:32:30 +0000594Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
595for debugging because they can provide useful information::
Georg Brandl116aa622007-08-15 14:28:22 +0000596
Georg Brandl6911e3c2007-09-04 07:15:32 +0000597 >>> print(POINT.x)
Georg Brandl116aa622007-08-15 14:28:22 +0000598 <Field type=c_long, ofs=0, size=4>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000599 >>> print(POINT.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000600 <Field type=c_long, ofs=4, size=4>
601 >>>
602
603
604.. _ctypes-structureunion-alignment-byte-order:
605
606Structure/union alignment and byte order
607^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
608
609By default, Structure and Union fields are aligned in the same way the C
Thomas Woutersed03b412007-08-28 21:37:11 +0000610compiler does it. It is possible to override this behavior be specifying a
Georg Brandl116aa622007-08-15 14:28:22 +0000611:attr:`_pack_` class attribute in the subclass definition. This must be set to a
612positive integer and specifies the maximum alignment for the fields. This is
613what ``#pragma pack(n)`` also does in MSVC.
614
Georg Brandl8d8f1972009-06-08 13:27:23 +0000615:mod:`ctypes` uses the native byte order for Structures and Unions. To build
Georg Brandl116aa622007-08-15 14:28:22 +0000616structures with non-native byte order, you can use one of the
Georg Brandl1d837bc2009-12-29 11:24:00 +0000617:class:`BigEndianStructure`, :class:`LittleEndianStructure`,
618:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These
619classes cannot contain pointer fields.
Georg Brandl116aa622007-08-15 14:28:22 +0000620
621
622.. _ctypes-bit-fields-in-structures-unions:
623
624Bit fields in structures and unions
625^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
626
627It is possible to create structures and unions containing bit fields. Bit fields
628are only possible for integer fields, the bit width is specified as the third
629item in the :attr:`_fields_` tuples::
630
631 >>> class Int(Structure):
632 ... _fields_ = [("first_16", c_int, 16),
633 ... ("second_16", c_int, 16)]
634 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000635 >>> print(Int.first_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000636 <Field type=c_long, ofs=0:0, bits=16>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000637 >>> print(Int.second_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000638 <Field type=c_long, ofs=0:16, bits=16>
639 >>>
640
641
642.. _ctypes-arrays:
643
644Arrays
645^^^^^^
646
647Arrays are sequences, containing a fixed number of instances of the same type.
648
649The recommended way to create array types is by multiplying a data type with a
650positive integer::
651
652 TenPointsArrayType = POINT * 10
653
Thomas Woutersed03b412007-08-28 21:37:11 +0000654Here is an example of an somewhat artificial data type, a structure containing 4
Georg Brandl116aa622007-08-15 14:28:22 +0000655POINTs among other stuff::
656
657 >>> from ctypes import *
658 >>> class POINT(Structure):
659 ... _fields_ = ("x", c_int), ("y", c_int)
660 ...
661 >>> class MyStruct(Structure):
662 ... _fields_ = [("a", c_int),
663 ... ("b", c_float),
664 ... ("point_array", POINT * 4)]
665 >>>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000666 >>> print(len(MyStruct().point_array))
Georg Brandl116aa622007-08-15 14:28:22 +0000667 4
668 >>>
669
670Instances are created in the usual way, by calling the class::
671
672 arr = TenPointsArrayType()
673 for pt in arr:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000674 print(pt.x, pt.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000675
676The above code print a series of ``0 0`` lines, because the array contents is
677initialized to zeros.
678
679Initializers of the correct type can also be specified::
680
681 >>> from ctypes import *
682 >>> TenIntegers = c_int * 10
683 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000684 >>> print(ii)
Georg Brandl116aa622007-08-15 14:28:22 +0000685 <c_long_Array_10 object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000686 >>> for i in ii: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000687 ...
688 1 2 3 4 5 6 7 8 9 10
689 >>>
690
691
692.. _ctypes-pointers:
693
694Pointers
695^^^^^^^^
696
Georg Brandl8d8f1972009-06-08 13:27:23 +0000697Pointer instances are created by calling the :func:`pointer` function on a
698:mod:`ctypes` type::
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700 >>> from ctypes import *
701 >>> i = c_int(42)
702 >>> pi = pointer(i)
703 >>>
704
Georg Brandl1d837bc2009-12-29 11:24:00 +0000705Pointer instances have a :attr:`contents` attribute which returns the object to
Georg Brandl116aa622007-08-15 14:28:22 +0000706which the pointer points, the ``i`` object above::
707
708 >>> pi.contents
709 c_long(42)
710 >>>
711
Georg Brandl8d8f1972009-06-08 13:27:23 +0000712Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
Georg Brandl116aa622007-08-15 14:28:22 +0000713new, equivalent object each time you retrieve an attribute::
714
715 >>> pi.contents is i
716 False
717 >>> pi.contents is pi.contents
718 False
719 >>>
720
721Assigning another :class:`c_int` instance to the pointer's contents attribute
722would cause the pointer to point to the memory location where this is stored::
723
724 >>> i = c_int(99)
725 >>> pi.contents = i
726 >>> pi.contents
727 c_long(99)
728 >>>
729
Georg Brandl1d837bc2009-12-29 11:24:00 +0000730.. XXX Document dereferencing pointers, and that it is preferred over the
731 .contents attribute.
Thomas Heller2fadaa22008-06-16 19:56:33 +0000732
Georg Brandl116aa622007-08-15 14:28:22 +0000733Pointer instances can also be indexed with integers::
734
735 >>> pi[0]
736 99
737 >>>
738
739Assigning to an integer index changes the pointed to value::
740
Georg Brandl6911e3c2007-09-04 07:15:32 +0000741 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000742 c_long(99)
743 >>> pi[0] = 22
Georg Brandl6911e3c2007-09-04 07:15:32 +0000744 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000745 c_long(22)
746 >>>
747
748It is also possible to use indexes different from 0, but you must know what
749you're doing, just as in C: You can access or change arbitrary memory locations.
750Generally you only use this feature if you receive a pointer from a C function,
751and you *know* that the pointer actually points to an array instead of a single
752item.
753
Georg Brandl8d8f1972009-06-08 13:27:23 +0000754Behind the scenes, the :func:`pointer` function does more than simply create
755pointer instances, it has to create pointer *types* first. This is done with the
756:func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a
757new type::
Georg Brandl116aa622007-08-15 14:28:22 +0000758
759 >>> PI = POINTER(c_int)
760 >>> PI
761 <class 'ctypes.LP_c_long'>
762 >>> PI(42)
763 Traceback (most recent call last):
764 File "<stdin>", line 1, in ?
765 TypeError: expected c_long instead of int
766 >>> PI(c_int(42))
767 <ctypes.LP_c_long object at 0x...>
768 >>>
769
770Calling the pointer type without an argument creates a ``NULL`` pointer.
771``NULL`` pointers have a ``False`` boolean value::
772
773 >>> null_ptr = POINTER(c_int)()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000774 >>> print(bool(null_ptr))
Georg Brandl116aa622007-08-15 14:28:22 +0000775 False
776 >>>
777
Georg Brandl8d8f1972009-06-08 13:27:23 +0000778:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
Thomas Heller2fadaa22008-06-16 19:56:33 +0000779invalid non-\ ``NULL`` pointers would crash Python)::
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781 >>> null_ptr[0]
782 Traceback (most recent call last):
783 ....
784 ValueError: NULL pointer access
785 >>>
786
787 >>> null_ptr[0] = 1234
788 Traceback (most recent call last):
789 ....
790 ValueError: NULL pointer access
791 >>>
792
793
794.. _ctypes-type-conversions:
795
796Type conversions
797^^^^^^^^^^^^^^^^
798
799Usually, ctypes does strict type checking. This means, if you have
800``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
801a member field in a structure definition, only instances of exactly the same
802type are accepted. There are some exceptions to this rule, where ctypes accepts
803other objects. For example, you can pass compatible array instances instead of
804pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
805
806 >>> class Bar(Structure):
807 ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
808 ...
809 >>> bar = Bar()
810 >>> bar.values = (c_int * 3)(1, 2, 3)
811 >>> bar.count = 3
812 >>> for i in range(bar.count):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000813 ... print(bar.values[i])
Georg Brandl116aa622007-08-15 14:28:22 +0000814 ...
815 1
816 2
817 3
818 >>>
819
820To set a POINTER type field to ``NULL``, you can assign ``None``::
821
822 >>> bar.values = None
823 >>>
824
Thomas Heller2fadaa22008-06-16 19:56:33 +0000825.. XXX list other conversions...
Georg Brandl116aa622007-08-15 14:28:22 +0000826
Georg Brandl8d8f1972009-06-08 13:27:23 +0000827Sometimes you have instances of incompatible types. In C, you can cast one type
828into another type. :mod:`ctypes` provides a :func:`cast` function which can be
Georg Brandl116aa622007-08-15 14:28:22 +0000829used in the same way. The ``Bar`` structure defined above accepts
830``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
831but not instances of other types::
832
833 >>> bar.values = (c_byte * 4)()
834 Traceback (most recent call last):
835 File "<stdin>", line 1, in ?
836 TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
837 >>>
838
Georg Brandl8d8f1972009-06-08 13:27:23 +0000839For these cases, the :func:`cast` function is handy.
Georg Brandl116aa622007-08-15 14:28:22 +0000840
Georg Brandl8d8f1972009-06-08 13:27:23 +0000841The :func:`cast` function can be used to cast a ctypes instance into a pointer
842to a different ctypes data type. :func:`cast` takes two parameters, a ctypes
843object that is or can be converted to a pointer of some kind, and a ctypes
844pointer type. It returns an instance of the second argument, which references
845the same memory block as the first argument::
Georg Brandl116aa622007-08-15 14:28:22 +0000846
847 >>> a = (c_byte * 4)()
848 >>> cast(a, POINTER(c_int))
849 <ctypes.LP_c_long object at ...>
850 >>>
851
Georg Brandl8d8f1972009-06-08 13:27:23 +0000852So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the
Georg Brandl116aa622007-08-15 14:28:22 +0000853structure::
854
855 >>> bar = Bar()
856 >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
Georg Brandl6911e3c2007-09-04 07:15:32 +0000857 >>> print(bar.values[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000858 0
859 >>>
860
861
862.. _ctypes-incomplete-types:
863
864Incomplete Types
865^^^^^^^^^^^^^^^^
866
867*Incomplete Types* are structures, unions or arrays whose members are not yet
868specified. In C, they are specified by forward declarations, which are defined
869later::
870
871 struct cell; /* forward declaration */
872
Sandro Tosi692dba22011-08-02 16:17:14 +0200873 struct cell {
Georg Brandl116aa622007-08-15 14:28:22 +0000874 char *name;
875 struct cell *next;
Sandro Tosi692dba22011-08-02 16:17:14 +0200876 };
Georg Brandl116aa622007-08-15 14:28:22 +0000877
878The straightforward translation into ctypes code would be this, but it does not
879work::
880
881 >>> class cell(Structure):
882 ... _fields_ = [("name", c_char_p),
883 ... ("next", POINTER(cell))]
884 ...
885 Traceback (most recent call last):
886 File "<stdin>", line 1, in ?
887 File "<stdin>", line 2, in cell
888 NameError: name 'cell' is not defined
889 >>>
890
891because the new ``class cell`` is not available in the class statement itself.
Georg Brandl8d8f1972009-06-08 13:27:23 +0000892In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_`
Georg Brandl116aa622007-08-15 14:28:22 +0000893attribute later, after the class statement::
894
895 >>> from ctypes import *
896 >>> class cell(Structure):
897 ... pass
898 ...
899 >>> cell._fields_ = [("name", c_char_p),
900 ... ("next", POINTER(cell))]
901 >>>
902
903Lets try it. We create two instances of ``cell``, and let them point to each
904other, and finally follow the pointer chain a few times::
905
906 >>> c1 = cell()
907 >>> c1.name = "foo"
908 >>> c2 = cell()
909 >>> c2.name = "bar"
910 >>> c1.next = pointer(c2)
911 >>> c2.next = pointer(c1)
912 >>> p = c1
913 >>> for i in range(8):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000914 ... print(p.name, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000915 ... p = p.next[0]
916 ...
917 foo bar foo bar foo bar foo bar
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000918 >>>
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920
921.. _ctypes-callback-functions:
922
923Callback functions
924^^^^^^^^^^^^^^^^^^
925
Georg Brandl8d8f1972009-06-08 13:27:23 +0000926:mod:`ctypes` allows to create C callable function pointers from Python callables.
Georg Brandl116aa622007-08-15 14:28:22 +0000927These are sometimes called *callback functions*.
928
929First, you must create a class for the callback function, the class knows the
930calling convention, the return type, and the number and types of arguments this
931function will receive.
932
933The CFUNCTYPE factory function creates types for callback functions using the
934normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
935function creates types for callback functions using the stdcall calling
936convention.
937
938Both of these factory functions are called with the result type as first
939argument, and the callback functions expected argument types as the remaining
940arguments.
941
Georg Brandl8d8f1972009-06-08 13:27:23 +0000942I will present an example here which uses the standard C library's
Georg Brandl60203b42010-10-06 10:11:56 +0000943:c:func:`qsort` function, this is used to sort items with the help of a callback
944function. :c:func:`qsort` will be used to sort an array of integers::
Georg Brandl116aa622007-08-15 14:28:22 +0000945
946 >>> IntArray5 = c_int * 5
947 >>> ia = IntArray5(5, 1, 7, 33, 99)
948 >>> qsort = libc.qsort
949 >>> qsort.restype = None
950 >>>
951
952:func:`qsort` must be called with a pointer to the data to sort, the number of
953items in the data array, the size of one item, and a pointer to the comparison
954function, the callback. The callback will then be called with two pointers to
955items, and it must return a negative integer if the first item is smaller than
956the second, a zero if they are equal, and a positive integer else.
957
958So our callback function receives pointers to integers, and must return an
959integer. First we create the ``type`` for the callback function::
960
961 >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
962 >>>
963
964For the first implementation of the callback function, we simply print the
965arguments we get, and return 0 (incremental development ;-)::
966
967 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000968 ... print("py_cmp_func", a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000969 ... return 0
970 ...
971 >>>
972
973Create the C callable callback::
974
975 >>> cmp_func = CMPFUNC(py_cmp_func)
976 >>>
977
978And we're ready to go::
979
980 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
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 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
987 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
988 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
989 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
990 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
991 >>>
992
993We know how to access the contents of a pointer, so lets redefine our callback::
994
995 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000996 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000997 ... return 0
998 ...
999 >>> cmp_func = CMPFUNC(py_cmp_func)
1000 >>>
1001
1002Here is what we get on Windows::
1003
1004 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
1005 py_cmp_func 7 1
1006 py_cmp_func 33 1
1007 py_cmp_func 99 1
1008 py_cmp_func 5 1
1009 py_cmp_func 7 5
1010 py_cmp_func 33 5
1011 py_cmp_func 99 5
1012 py_cmp_func 7 99
1013 py_cmp_func 33 99
1014 py_cmp_func 7 33
1015 >>>
1016
1017It is funny to see that on linux the sort function seems to work much more
Benjamin Peterson1baf4652009-12-31 03:11:23 +00001018efficiently, it is doing less comparisons::
Georg Brandl116aa622007-08-15 14:28:22 +00001019
1020 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
1021 py_cmp_func 5 1
1022 py_cmp_func 33 99
1023 py_cmp_func 7 33
1024 py_cmp_func 5 7
1025 py_cmp_func 1 7
1026 >>>
1027
1028Ah, we're nearly done! The last step is to actually compare the two items and
1029return a useful result::
1030
1031 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001032 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +00001033 ... return a[0] - b[0]
1034 ...
1035 >>>
1036
1037Final run on Windows::
1038
1039 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
1040 py_cmp_func 33 7
1041 py_cmp_func 99 33
1042 py_cmp_func 5 99
1043 py_cmp_func 1 99
1044 py_cmp_func 33 7
1045 py_cmp_func 1 33
1046 py_cmp_func 5 33
1047 py_cmp_func 5 7
1048 py_cmp_func 1 7
1049 py_cmp_func 5 1
1050 >>>
1051
1052and on Linux::
1053
1054 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1055 py_cmp_func 5 1
1056 py_cmp_func 33 99
1057 py_cmp_func 7 33
1058 py_cmp_func 1 7
1059 py_cmp_func 5 7
1060 >>>
1061
1062It is quite interesting to see that the Windows :func:`qsort` function needs
1063more comparisons than the linux version!
1064
1065As we can easily check, our array is sorted now::
1066
Georg Brandl6911e3c2007-09-04 07:15:32 +00001067 >>> for i in ia: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +00001068 ...
1069 1 5 7 33 99
1070 >>>
1071
1072**Important note for callback functions:**
1073
1074Make sure you keep references to CFUNCTYPE objects as long as they are used from
Georg Brandl8d8f1972009-06-08 13:27:23 +00001075C code. :mod:`ctypes` doesn't, and if you don't, they may be garbage collected,
Georg Brandl116aa622007-08-15 14:28:22 +00001076crashing your program when a callback is made.
1077
1078
1079.. _ctypes-accessing-values-exported-from-dlls:
1080
1081Accessing values exported from dlls
1082^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1083
Thomas Heller2fadaa22008-06-16 19:56:33 +00001084Some shared libraries not only export functions, they also export variables. An
Georg Brandl60203b42010-10-06 10:11:56 +00001085example in the Python library itself is the :c:data:`Py_OptimizeFlag`, an integer
Georg Brandl8d8f1972009-06-08 13:27:23 +00001086set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
Georg Brandl116aa622007-08-15 14:28:22 +00001087startup.
1088
Georg Brandl8d8f1972009-06-08 13:27:23 +00001089:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of
Georg Brandl116aa622007-08-15 14:28:22 +00001090the type. *pythonapi* is a predefined symbol giving access to the Python C
1091api::
1092
1093 >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
Georg Brandl6911e3c2007-09-04 07:15:32 +00001094 >>> print(opt_flag)
Georg Brandl116aa622007-08-15 14:28:22 +00001095 c_long(0)
1096 >>>
1097
1098If the interpreter would have been started with :option:`-O`, the sample would
1099have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1100specified.
1101
1102An extended example which also demonstrates the use of pointers accesses the
Georg Brandl60203b42010-10-06 10:11:56 +00001103:c:data:`PyImport_FrozenModules` pointer exported by Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001104
Georg Brandl8d8f1972009-06-08 13:27:23 +00001105Quoting the docs for that value:
1106
Georg Brandl60203b42010-10-06 10:11:56 +00001107 This pointer is initialized to point to an array of :c:type:`struct _frozen`
Georg Brandl8d8f1972009-06-08 13:27:23 +00001108 records, terminated by one whose members are all *NULL* or zero. When a frozen
1109 module is imported, it is searched in this table. Third-party code could play
1110 tricks with this to provide a dynamically created collection of frozen modules.
Georg Brandl116aa622007-08-15 14:28:22 +00001111
1112So manipulating this pointer could even prove useful. To restrict the example
Georg Brandl8d8f1972009-06-08 13:27:23 +00001113size, we show only how this table can be read with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001114
1115 >>> from ctypes import *
1116 >>>
1117 >>> class struct_frozen(Structure):
1118 ... _fields_ = [("name", c_char_p),
1119 ... ("code", POINTER(c_ubyte)),
1120 ... ("size", c_int)]
1121 ...
1122 >>>
1123
Georg Brandl60203b42010-10-06 10:11:56 +00001124We have defined the :c:type:`struct _frozen` data type, so we can get the pointer
Georg Brandl8d8f1972009-06-08 13:27:23 +00001125to the table::
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127 >>> FrozenTable = POINTER(struct_frozen)
1128 >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1129 >>>
1130
1131Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1132can iterate over it, but we just have to make sure that our loop terminates,
1133because pointers have no size. Sooner or later it would probably crash with an
1134access violation or whatever, so it's better to break out of the loop when we
1135hit the NULL entry::
1136
1137 >>> for item in table:
Georg Brandl6911e3c2007-09-04 07:15:32 +00001138 ... print(item.name, item.size)
Georg Brandl116aa622007-08-15 14:28:22 +00001139 ... if item.name is None:
1140 ... break
1141 ...
1142 __hello__ 104
1143 __phello__ -104
1144 __phello__.spam 104
1145 None 0
1146 >>>
1147
1148The fact that standard Python has a frozen module and a frozen package
Thomas Woutersed03b412007-08-28 21:37:11 +00001149(indicated by the negative size member) is not well known, it is only used for
Georg Brandl116aa622007-08-15 14:28:22 +00001150testing. Try it out with ``import __hello__`` for example.
1151
1152
1153.. _ctypes-surprises:
1154
1155Surprises
1156^^^^^^^^^
1157
Georg Brandl8d8f1972009-06-08 13:27:23 +00001158There are some edges in :mod:`ctypes` where you may be expect something else than
Georg Brandl116aa622007-08-15 14:28:22 +00001159what actually happens.
1160
1161Consider the following example::
1162
1163 >>> from ctypes import *
1164 >>> class POINT(Structure):
1165 ... _fields_ = ("x", c_int), ("y", c_int)
1166 ...
1167 >>> class RECT(Structure):
1168 ... _fields_ = ("a", POINT), ("b", POINT)
1169 ...
1170 >>> p1 = POINT(1, 2)
1171 >>> p2 = POINT(3, 4)
1172 >>> rc = RECT(p1, p2)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001173 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001174 1 2 3 4
1175 >>> # now swap the two points
1176 >>> rc.a, rc.b = rc.b, rc.a
Georg Brandl6911e3c2007-09-04 07:15:32 +00001177 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001178 3 4 3 4
1179 >>>
1180
1181Hm. We certainly expected the last statement to print ``3 4 1 2``. What
Thomas Woutersed03b412007-08-28 21:37:11 +00001182happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
Georg Brandl116aa622007-08-15 14:28:22 +00001183
1184 >>> temp0, temp1 = rc.b, rc.a
1185 >>> rc.a = temp0
1186 >>> rc.b = temp1
1187 >>>
1188
1189Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1190the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1191contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1192contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1193the expected effect.
1194
Thomas Woutersed03b412007-08-28 21:37:11 +00001195Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1196doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
Georg Brandl116aa622007-08-15 14:28:22 +00001197the root-object's underlying buffer.
1198
1199Another example that may behave different from what one would expect is this::
1200
1201 >>> s = c_char_p()
1202 >>> s.value = "abc def ghi"
1203 >>> s.value
1204 'abc def ghi'
1205 >>> s.value is s.value
1206 False
1207 >>>
1208
1209Why is it printing ``False``? ctypes instances are objects containing a memory
Georg Brandl9afde1c2007-11-01 20:32:30 +00001210block plus some :term:`descriptor`\s accessing the contents of the memory.
1211Storing a Python object in the memory block does not store the object itself,
1212instead the ``contents`` of the object is stored. Accessing the contents again
1213constructs a new Python object each time!
Georg Brandl116aa622007-08-15 14:28:22 +00001214
1215
1216.. _ctypes-variable-sized-data-types:
1217
1218Variable-sized data types
1219^^^^^^^^^^^^^^^^^^^^^^^^^
1220
Georg Brandl8d8f1972009-06-08 13:27:23 +00001221:mod:`ctypes` provides some support for variable-sized arrays and structures.
Georg Brandl116aa622007-08-15 14:28:22 +00001222
Georg Brandl8d8f1972009-06-08 13:27:23 +00001223The :func:`resize` function can be used to resize the memory buffer of an
1224existing ctypes object. The function takes the object as first argument, and
1225the requested size in bytes as the second argument. The memory block cannot be
1226made smaller than the natural memory block specified by the objects type, a
1227:exc:`ValueError` is raised if this is tried::
Georg Brandl116aa622007-08-15 14:28:22 +00001228
1229 >>> short_array = (c_short * 4)()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001230 >>> print(sizeof(short_array))
Georg Brandl116aa622007-08-15 14:28:22 +00001231 8
1232 >>> resize(short_array, 4)
1233 Traceback (most recent call last):
1234 ...
1235 ValueError: minimum size is 8
1236 >>> resize(short_array, 32)
1237 >>> sizeof(short_array)
1238 32
1239 >>> sizeof(type(short_array))
1240 8
1241 >>>
1242
1243This is nice and fine, but how would one access the additional elements
1244contained in this array? Since the type still only knows about 4 elements, we
1245get errors accessing other elements::
1246
1247 >>> short_array[:]
1248 [0, 0, 0, 0]
1249 >>> short_array[7]
1250 Traceback (most recent call last):
1251 ...
1252 IndexError: invalid index
1253 >>>
1254
Georg Brandl8d8f1972009-06-08 13:27:23 +00001255Another way to use variable-sized data types with :mod:`ctypes` is to use the
Georg Brandl116aa622007-08-15 14:28:22 +00001256dynamic nature of Python, and (re-)define the data type after the required size
1257is already known, on a case by case basis.
1258
1259
Georg Brandl116aa622007-08-15 14:28:22 +00001260.. _ctypes-ctypes-reference:
1261
1262ctypes reference
1263----------------
1264
1265
1266.. _ctypes-finding-shared-libraries:
1267
1268Finding shared libraries
1269^^^^^^^^^^^^^^^^^^^^^^^^
1270
1271When programming in a compiled language, shared libraries are accessed when
1272compiling/linking a program, and when the program is run.
1273
Georg Brandl8d8f1972009-06-08 13:27:23 +00001274The purpose of the :func:`find_library` function is to locate a library in a way
Georg Brandl116aa622007-08-15 14:28:22 +00001275similar to what the compiler does (on platforms with several versions of a
1276shared library the most recent should be loaded), while the ctypes library
1277loaders act like when a program is run, and call the runtime loader directly.
1278
Georg Brandl8d8f1972009-06-08 13:27:23 +00001279The :mod:`ctypes.util` module provides a function which can help to determine
1280the library to load.
Georg Brandl116aa622007-08-15 14:28:22 +00001281
1282
1283.. data:: find_library(name)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001284 :module: ctypes.util
Georg Brandl116aa622007-08-15 14:28:22 +00001285 :noindex:
1286
1287 Try to find a library and return a pathname. *name* is the library name without
1288 any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1289 is the form used for the posix linker option :option:`-l`). If no library can
1290 be found, returns ``None``.
1291
Thomas Woutersed03b412007-08-28 21:37:11 +00001292The exact functionality is system dependent.
Georg Brandl116aa622007-08-15 14:28:22 +00001293
Georg Brandl1d837bc2009-12-29 11:24:00 +00001294On Linux, :func:`find_library` tries to run external programs
1295(``/sbin/ldconfig``, ``gcc``, and ``objdump``) to find the library file. It
1296returns the filename of the library file. Here are some examples::
Georg Brandl116aa622007-08-15 14:28:22 +00001297
1298 >>> from ctypes.util import find_library
1299 >>> find_library("m")
1300 'libm.so.6'
1301 >>> find_library("c")
1302 'libc.so.6'
1303 >>> find_library("bz2")
1304 'libbz2.so.1.0'
1305 >>>
1306
Georg Brandl8d8f1972009-06-08 13:27:23 +00001307On OS X, :func:`find_library` tries several predefined naming schemes and paths
1308to locate the library, and returns a full pathname if successful::
Georg Brandl116aa622007-08-15 14:28:22 +00001309
1310 >>> from ctypes.util import find_library
1311 >>> find_library("c")
1312 '/usr/lib/libc.dylib'
1313 >>> find_library("m")
1314 '/usr/lib/libm.dylib'
1315 >>> find_library("bz2")
1316 '/usr/lib/libbz2.dylib'
1317 >>> find_library("AGL")
1318 '/System/Library/Frameworks/AGL.framework/AGL'
1319 >>>
1320
Georg Brandl8d8f1972009-06-08 13:27:23 +00001321On Windows, :func:`find_library` searches along the system search path, and
1322returns the full pathname, but since there is no predefined naming scheme a call
1323like ``find_library("c")`` will fail and return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001324
Georg Brandl8d8f1972009-06-08 13:27:23 +00001325If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
Georg Brandl116aa622007-08-15 14:28:22 +00001326the shared library name at development type, and hardcode that into the wrapper
Georg Brandl8d8f1972009-06-08 13:27:23 +00001327module instead of using :func:`find_library` to locate the library at runtime.
Georg Brandl116aa622007-08-15 14:28:22 +00001328
1329
1330.. _ctypes-loading-shared-libraries:
1331
1332Loading shared libraries
1333^^^^^^^^^^^^^^^^^^^^^^^^
1334
1335There are several ways to loaded shared libraries into the Python process. One
1336way is to instantiate one of the following classes:
1337
1338
Thomas Hellerb795f5282008-06-10 15:26:58 +00001339.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001340
1341 Instances of this class represent loaded shared libraries. Functions in these
1342 libraries use the standard C calling convention, and are assumed to return
Georg Brandl60203b42010-10-06 10:11:56 +00001343 :c:type:`int`.
Georg Brandl116aa622007-08-15 14:28:22 +00001344
1345
Thomas Hellerb795f5282008-06-10 15:26:58 +00001346.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001347
1348 Windows only: Instances of this class represent loaded shared libraries,
1349 functions in these libraries use the ``stdcall`` calling convention, and are
1350 assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1351 values contain information specifying whether the function call failed or
1352 succeeded, together with additional error code. If the return value signals a
Antoine Pitrou442ee032011-10-12 18:53:23 +02001353 failure, an :class:`OSError` is automatically raised.
1354
1355 .. versionchanged:: 3.3
1356 :exc:`WindowsError` used to be raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001357
1358
Thomas Hellerb795f5282008-06-10 15:26:58 +00001359.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001360
1361 Windows only: Instances of this class represent loaded shared libraries,
1362 functions in these libraries use the ``stdcall`` calling convention, and are
Georg Brandl60203b42010-10-06 10:11:56 +00001363 assumed to return :c:type:`int` by default.
Georg Brandl116aa622007-08-15 14:28:22 +00001364
1365 On Windows CE only the standard calling convention is used, for convenience the
1366 :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1367 platform.
1368
Georg Brandl9afde1c2007-11-01 20:32:30 +00001369The Python :term:`global interpreter lock` is released before calling any
1370function exported by these libraries, and reacquired afterwards.
Georg Brandl116aa622007-08-15 14:28:22 +00001371
1372
1373.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1374
1375 Instances of this class behave like :class:`CDLL` instances, except that the
1376 Python GIL is *not* released during the function call, and after the function
1377 execution the Python error flag is checked. If the error flag is set, a Python
1378 exception is raised.
1379
1380 Thus, this is only useful to call Python C api functions directly.
1381
1382All these classes can be instantiated by calling them with at least one
1383argument, the pathname of the shared library. If you have an existing handle to
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001384an already loaded shared library, it can be passed as the ``handle`` named
Georg Brandl1d837bc2009-12-29 11:24:00 +00001385parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary``
Georg Brandl116aa622007-08-15 14:28:22 +00001386function is used to load the library into the process, and to get a handle to
1387it.
1388
1389The *mode* parameter can be used to specify how the library is loaded. For
Georg Brandl1d837bc2009-12-29 11:24:00 +00001390details, consult the :manpage:`dlopen(3)` manpage, on Windows, *mode* is
1391ignored.
Georg Brandl116aa622007-08-15 14:28:22 +00001392
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001393The *use_errno* parameter, when set to True, enables a ctypes mechanism that
1394allows to access the system :data:`errno` error number in a safe way.
1395:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1396variable; if you call foreign functions created with ``use_errno=True`` then the
1397:data:`errno` value before the function call is swapped with the ctypes private
1398copy, the same happens immediately after the function call.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001399
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001400The function :func:`ctypes.get_errno` returns the value of the ctypes private
1401copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1402to a new value and returns the former value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001403
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001404The *use_last_error* parameter, when set to True, enables the same mechanism for
1405the Windows error code which is managed by the :func:`GetLastError` and
1406:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1407:func:`ctypes.set_last_error` are used to request and change the ctypes private
1408copy of the windows error code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001409
Georg Brandl116aa622007-08-15 14:28:22 +00001410.. data:: RTLD_GLOBAL
1411 :noindex:
1412
1413 Flag to use as *mode* parameter. On platforms where this flag is not available,
1414 it is defined as the integer zero.
1415
1416
1417.. data:: RTLD_LOCAL
1418 :noindex:
1419
1420 Flag to use as *mode* parameter. On platforms where this is not available, it
1421 is the same as *RTLD_GLOBAL*.
1422
1423
1424.. data:: DEFAULT_MODE
1425 :noindex:
1426
1427 The default mode which is used to load shared libraries. On OSX 10.3, this is
1428 *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1429
1430Instances of these classes have no public methods, however :meth:`__getattr__`
Thomas Woutersed03b412007-08-28 21:37:11 +00001431and :meth:`__getitem__` have special behavior: functions exported by the shared
Georg Brandl116aa622007-08-15 14:28:22 +00001432library can be accessed as attributes of by index. Please note that both
1433:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1434repeatedly returns the same object each time.
1435
1436The following public attributes are available, their name starts with an
1437underscore to not clash with exported function names:
1438
1439
1440.. attribute:: PyDLL._handle
1441
1442 The system handle used to access the library.
1443
1444
1445.. attribute:: PyDLL._name
1446
Thomas Woutersed03b412007-08-28 21:37:11 +00001447 The name of the library passed in the constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001448
1449Shared libraries can also be loaded by using one of the prefabricated objects,
1450which are instances of the :class:`LibraryLoader` class, either by calling the
1451:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1452loader instance.
1453
1454
1455.. class:: LibraryLoader(dlltype)
1456
Georg Brandl1d837bc2009-12-29 11:24:00 +00001457 Class which loads shared libraries. *dlltype* should be one of the
Georg Brandl116aa622007-08-15 14:28:22 +00001458 :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1459
Thomas Woutersed03b412007-08-28 21:37:11 +00001460 :meth:`__getattr__` has special behavior: It allows to load a shared library by
Georg Brandl116aa622007-08-15 14:28:22 +00001461 accessing it as attribute of a library loader instance. The result is cached,
1462 so repeated attribute accesses return the same library each time.
1463
Benjamin Petersone41251e2008-04-25 01:59:09 +00001464 .. method:: LoadLibrary(name)
Georg Brandl116aa622007-08-15 14:28:22 +00001465
Benjamin Petersone41251e2008-04-25 01:59:09 +00001466 Load a shared library into the process and return it. This method always
1467 returns a new instance of the library.
Georg Brandl116aa622007-08-15 14:28:22 +00001468
Georg Brandl116aa622007-08-15 14:28:22 +00001469
Georg Brandl8d8f1972009-06-08 13:27:23 +00001470These prefabricated library loaders are available:
Georg Brandl116aa622007-08-15 14:28:22 +00001471
1472.. data:: cdll
1473 :noindex:
1474
1475 Creates :class:`CDLL` instances.
1476
1477
1478.. data:: windll
1479 :noindex:
1480
1481 Windows only: Creates :class:`WinDLL` instances.
1482
1483
1484.. data:: oledll
1485 :noindex:
1486
1487 Windows only: Creates :class:`OleDLL` instances.
1488
1489
1490.. data:: pydll
1491 :noindex:
1492
1493 Creates :class:`PyDLL` instances.
1494
Georg Brandl8d8f1972009-06-08 13:27:23 +00001495
Georg Brandl116aa622007-08-15 14:28:22 +00001496For accessing the C Python api directly, a ready-to-use Python shared library
1497object is available:
1498
Georg Brandl116aa622007-08-15 14:28:22 +00001499.. data:: pythonapi
1500 :noindex:
1501
Georg Brandl1d837bc2009-12-29 11:24:00 +00001502 An instance of :class:`PyDLL` that exposes Python C API functions as
1503 attributes. Note that all these functions are assumed to return C
Georg Brandl60203b42010-10-06 10:11:56 +00001504 :c:type:`int`, which is of course not always the truth, so you have to assign
Georg Brandl1d837bc2009-12-29 11:24:00 +00001505 the correct :attr:`restype` attribute to use these functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001506
1507
1508.. _ctypes-foreign-functions:
1509
1510Foreign functions
1511^^^^^^^^^^^^^^^^^
1512
1513As explained in the previous section, foreign functions can be accessed as
1514attributes of loaded shared libraries. The function objects created in this way
1515by default accept any number of arguments, accept any ctypes data instances as
1516arguments, and return the default result type specified by the library loader.
1517They are instances of a private class:
1518
1519
1520.. class:: _FuncPtr
1521
1522 Base class for C callable foreign functions.
1523
Benjamin Petersone41251e2008-04-25 01:59:09 +00001524 Instances of foreign functions are also C compatible data types; they
1525 represent C function pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001526
Benjamin Petersone41251e2008-04-25 01:59:09 +00001527 This behavior can be customized by assigning to special attributes of the
1528 foreign function object.
Georg Brandl116aa622007-08-15 14:28:22 +00001529
Benjamin Petersone41251e2008-04-25 01:59:09 +00001530 .. attribute:: restype
Georg Brandl116aa622007-08-15 14:28:22 +00001531
Benjamin Petersone41251e2008-04-25 01:59:09 +00001532 Assign a ctypes type to specify the result type of the foreign function.
Georg Brandl60203b42010-10-06 10:11:56 +00001533 Use ``None`` for :c:type:`void`, a function not returning anything.
Georg Brandl116aa622007-08-15 14:28:22 +00001534
Benjamin Petersone41251e2008-04-25 01:59:09 +00001535 It is possible to assign a callable Python object that is not a ctypes
Georg Brandl60203b42010-10-06 10:11:56 +00001536 type, in this case the function is assumed to return a C :c:type:`int`, and
Georg Brandl1d837bc2009-12-29 11:24:00 +00001537 the callable will be called with this integer, allowing to do further
Benjamin Petersone41251e2008-04-25 01:59:09 +00001538 processing or error checking. Using this is deprecated, for more flexible
1539 post processing or error checking use a ctypes data type as
1540 :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001541
Benjamin Petersone41251e2008-04-25 01:59:09 +00001542 .. attribute:: argtypes
Georg Brandl116aa622007-08-15 14:28:22 +00001543
Benjamin Petersone41251e2008-04-25 01:59:09 +00001544 Assign a tuple of ctypes types to specify the argument types that the
1545 function accepts. Functions using the ``stdcall`` calling convention can
1546 only be called with the same number of arguments as the length of this
1547 tuple; functions using the C calling convention accept additional,
1548 unspecified arguments as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001549
Benjamin Petersone41251e2008-04-25 01:59:09 +00001550 When a foreign function is called, each actual argument is passed to the
1551 :meth:`from_param` class method of the items in the :attr:`argtypes`
1552 tuple, this method allows to adapt the actual argument to an object that
1553 the foreign function accepts. For example, a :class:`c_char_p` item in
Georg Brandl8d8f1972009-06-08 13:27:23 +00001554 the :attr:`argtypes` tuple will convert a string passed as argument into
1555 a bytes object using ctypes conversion rules.
Georg Brandl116aa622007-08-15 14:28:22 +00001556
Benjamin Petersone41251e2008-04-25 01:59:09 +00001557 New: It is now possible to put items in argtypes which are not ctypes
1558 types, but each item must have a :meth:`from_param` method which returns a
1559 value usable as argument (integer, string, ctypes instance). This allows
1560 to define adapters that can adapt custom objects as function parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001561
Benjamin Petersone41251e2008-04-25 01:59:09 +00001562 .. attribute:: errcheck
Georg Brandl116aa622007-08-15 14:28:22 +00001563
Benjamin Petersone41251e2008-04-25 01:59:09 +00001564 Assign a Python function or another callable to this attribute. The
1565 callable will be called with three or more arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001566
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001567 .. function:: callable(result, func, arguments)
1568 :noindex:
Georg Brandl8d8f1972009-06-08 13:27:23 +00001569 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001570
Georg Brandl1d837bc2009-12-29 11:24:00 +00001571 *result* is what the foreign function returns, as specified by the
1572 :attr:`restype` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001573
Georg Brandl1d837bc2009-12-29 11:24:00 +00001574 *func* is the foreign function object itself, this allows to reuse the
1575 same callable object to check or post process the results of several
1576 functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001577
Georg Brandl1d837bc2009-12-29 11:24:00 +00001578 *arguments* is a tuple containing the parameters originally passed to
1579 the function call, this allows to specialize the behavior on the
1580 arguments used.
Georg Brandl116aa622007-08-15 14:28:22 +00001581
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001582 The object that this function returns will be returned from the
1583 foreign function call, but it can also check the result value
1584 and raise an exception if the foreign function call failed.
Georg Brandl116aa622007-08-15 14:28:22 +00001585
1586
Georg Brandl8d8f1972009-06-08 13:27:23 +00001587.. exception:: ArgumentError
Georg Brandl116aa622007-08-15 14:28:22 +00001588
1589 This exception is raised when a foreign function call cannot convert one of the
1590 passed arguments.
1591
1592
1593.. _ctypes-function-prototypes:
1594
1595Function prototypes
1596^^^^^^^^^^^^^^^^^^^
1597
1598Foreign functions can also be created by instantiating function prototypes.
1599Function prototypes are similar to function prototypes in C; they describe a
1600function (return type, argument types, calling convention) without defining an
1601implementation. The factory functions must be called with the desired result
1602type and the argument types of the function.
1603
1604
Thomas Hellerb795f5282008-06-10 15:26:58 +00001605.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001606
1607 The returned function prototype creates functions that use the standard C
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001608 calling convention. The function will release the GIL during the call. If
1609 *use_errno* is set to True, the ctypes private copy of the system
Georg Brandla6053b42009-09-01 08:11:14 +00001610 :data:`errno` variable is exchanged with the real :data:`errno` value before
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001611 and after the call; *use_last_error* does the same for the Windows error
1612 code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001613
Georg Brandl116aa622007-08-15 14:28:22 +00001614
Thomas Hellerb795f5282008-06-10 15:26:58 +00001615.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001616
1617 Windows only: The returned function prototype creates functions that use the
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001618 ``stdcall`` calling convention, except on Windows CE where
1619 :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
1620 release the GIL during the call. *use_errno* and *use_last_error* have the
1621 same meaning as above.
Georg Brandl116aa622007-08-15 14:28:22 +00001622
1623
1624.. function:: PYFUNCTYPE(restype, *argtypes)
1625
1626 The returned function prototype creates functions that use the Python calling
1627 convention. The function will *not* release the GIL during the call.
1628
Thomas Heller2fadaa22008-06-16 19:56:33 +00001629Function prototypes created by these factory functions can be instantiated in
1630different ways, depending on the type and number of the parameters in the call:
Georg Brandl116aa622007-08-15 14:28:22 +00001631
1632
Thomas Heller2fadaa22008-06-16 19:56:33 +00001633 .. function:: prototype(address)
1634 :noindex:
1635 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001636
Thomas Heller2fadaa22008-06-16 19:56:33 +00001637 Returns a foreign function at the specified address which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00001638
1639
Thomas Heller2fadaa22008-06-16 19:56:33 +00001640 .. function:: prototype(callable)
1641 :noindex:
1642 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001643
Georg Brandl8d8f1972009-06-08 13:27:23 +00001644 Create a C callable function (a callback function) from a Python *callable*.
Georg Brandl116aa622007-08-15 14:28:22 +00001645
1646
Thomas Heller2fadaa22008-06-16 19:56:33 +00001647 .. function:: prototype(func_spec[, paramflags])
1648 :noindex:
1649 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001650
Georg Brandl1d837bc2009-12-29 11:24:00 +00001651 Returns a foreign function exported by a shared library. *func_spec* must
1652 be a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of
1653 the exported function as string, or the ordinal of the exported function
1654 as small integer. The second item is the shared library instance.
Georg Brandl116aa622007-08-15 14:28:22 +00001655
1656
Thomas Heller2fadaa22008-06-16 19:56:33 +00001657 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1658 :noindex:
1659 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001660
Georg Brandl8d8f1972009-06-08 13:27:23 +00001661 Returns a foreign function that will call a COM method. *vtbl_index* is
1662 the index into the virtual function table, a small non-negative
1663 integer. *name* is name of the COM method. *iid* is an optional pointer to
1664 the interface identifier which is used in extended error reporting.
Georg Brandl116aa622007-08-15 14:28:22 +00001665
Georg Brandl8d8f1972009-06-08 13:27:23 +00001666 COM methods use a special calling convention: They require a pointer to
1667 the COM interface as first argument, in addition to those parameters that
1668 are specified in the :attr:`argtypes` tuple.
Georg Brandl116aa622007-08-15 14:28:22 +00001669
Thomas Heller2fadaa22008-06-16 19:56:33 +00001670 The optional *paramflags* parameter creates foreign function wrappers with much
1671 more functionality than the features described above.
Georg Brandl116aa622007-08-15 14:28:22 +00001672
Thomas Heller2fadaa22008-06-16 19:56:33 +00001673 *paramflags* must be a tuple of the same length as :attr:`argtypes`.
Georg Brandl116aa622007-08-15 14:28:22 +00001674
Thomas Heller2fadaa22008-06-16 19:56:33 +00001675 Each item in this tuple contains further information about a parameter, it must
1676 be a tuple containing one, two, or three items.
Georg Brandl116aa622007-08-15 14:28:22 +00001677
Thomas Heller2fadaa22008-06-16 19:56:33 +00001678 The first item is an integer containing a combination of direction
1679 flags for the parameter:
Georg Brandl116aa622007-08-15 14:28:22 +00001680
Thomas Heller2fadaa22008-06-16 19:56:33 +00001681 1
1682 Specifies an input parameter to the function.
Georg Brandl116aa622007-08-15 14:28:22 +00001683
Thomas Heller2fadaa22008-06-16 19:56:33 +00001684 2
1685 Output parameter. The foreign function fills in a value.
Georg Brandl116aa622007-08-15 14:28:22 +00001686
Thomas Heller2fadaa22008-06-16 19:56:33 +00001687 4
1688 Input parameter which defaults to the integer zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001689
Thomas Heller2fadaa22008-06-16 19:56:33 +00001690 The optional second item is the parameter name as string. If this is specified,
1691 the foreign function can be called with named parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001692
Thomas Heller2fadaa22008-06-16 19:56:33 +00001693 The optional third item is the default value for this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001694
1695This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
1696that it supports default parameters and named arguments. The C declaration from
1697the windows header file is this::
1698
1699 WINUSERAPI int WINAPI
1700 MessageBoxA(
1701 HWND hWnd ,
1702 LPCSTR lpText,
1703 LPCSTR lpCaption,
1704 UINT uType);
1705
Georg Brandl8d8f1972009-06-08 13:27:23 +00001706Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001707
Thomas Heller2fadaa22008-06-16 19:56:33 +00001708 >>> from ctypes import c_int, WINFUNCTYPE, windll
1709 >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1710 >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
1711 >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1712 >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1713 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001714
1715The MessageBox foreign function can now be called in these ways::
1716
1717 >>> MessageBox()
1718 >>> MessageBox(text="Spam, spam, spam")
1719 >>> MessageBox(flags=2, text="foo bar")
1720 >>>
1721
1722A second example demonstrates output parameters. The win32 ``GetWindowRect``
1723function retrieves the dimensions of a specified window by copying them into
1724``RECT`` structure that the caller has to supply. Here is the C declaration::
1725
1726 WINUSERAPI BOOL WINAPI
1727 GetWindowRect(
1728 HWND hWnd,
1729 LPRECT lpRect);
1730
Georg Brandl8d8f1972009-06-08 13:27:23 +00001731Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001732
Thomas Heller2fadaa22008-06-16 19:56:33 +00001733 >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1734 >>> from ctypes.wintypes import BOOL, HWND, RECT
1735 >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1736 >>> paramflags = (1, "hwnd"), (2, "lprect")
1737 >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1738 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001739
1740Functions with output parameters will automatically return the output parameter
1741value if there is a single one, or a tuple containing the output parameter
1742values when there are more than one, so the GetWindowRect function now returns a
1743RECT instance, when called.
1744
1745Output parameters can be combined with the :attr:`errcheck` protocol to do
1746further output processing and error checking. The win32 ``GetWindowRect`` api
1747function returns a ``BOOL`` to signal success or failure, so this function could
1748do the error checking, and raises an exception when the api call failed::
1749
1750 >>> def errcheck(result, func, args):
1751 ... if not result:
1752 ... raise WinError()
1753 ... return args
Thomas Heller2fadaa22008-06-16 19:56:33 +00001754 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001755 >>> GetWindowRect.errcheck = errcheck
1756 >>>
1757
1758If the :attr:`errcheck` function returns the argument tuple it receives
Georg Brandl8d8f1972009-06-08 13:27:23 +00001759unchanged, :mod:`ctypes` continues the normal processing it does on the output
Georg Brandl116aa622007-08-15 14:28:22 +00001760parameters. If you want to return a tuple of window coordinates instead of a
1761``RECT`` instance, you can retrieve the fields in the function and return them
1762instead, the normal processing will no longer take place::
1763
1764 >>> def errcheck(result, func, args):
1765 ... if not result:
1766 ... raise WinError()
1767 ... rc = args[1]
1768 ... return rc.left, rc.top, rc.bottom, rc.right
Thomas Heller2fadaa22008-06-16 19:56:33 +00001769 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001770 >>> GetWindowRect.errcheck = errcheck
1771 >>>
1772
1773
1774.. _ctypes-utility-functions:
1775
1776Utility functions
1777^^^^^^^^^^^^^^^^^
1778
Georg Brandl116aa622007-08-15 14:28:22 +00001779.. function:: addressof(obj)
1780
Georg Brandl8d8f1972009-06-08 13:27:23 +00001781 Returns the address of the memory buffer as integer. *obj* must be an
Georg Brandl116aa622007-08-15 14:28:22 +00001782 instance of a ctypes type.
1783
1784
1785.. function:: alignment(obj_or_type)
1786
Georg Brandl8d8f1972009-06-08 13:27:23 +00001787 Returns the alignment requirements of a ctypes type. *obj_or_type* must be a
Georg Brandl116aa622007-08-15 14:28:22 +00001788 ctypes type or instance.
1789
1790
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001791.. function:: byref(obj[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +00001792
Georg Brandl1d837bc2009-12-29 11:24:00 +00001793 Returns a light-weight pointer to *obj*, which must be an instance of a
1794 ctypes type. *offset* defaults to zero, and must be an integer that will be
1795 added to the internal pointer value.
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001796
1797 ``byref(obj, offset)`` corresponds to this C code::
1798
1799 (((char *)&obj) + offset)
1800
Georg Brandl1d837bc2009-12-29 11:24:00 +00001801 The returned object can only be used as a foreign function call parameter.
1802 It behaves similar to ``pointer(obj)``, but the construction is a lot faster.
Georg Brandl116aa622007-08-15 14:28:22 +00001803
1804
1805.. function:: cast(obj, type)
1806
Georg Brandl8d8f1972009-06-08 13:27:23 +00001807 This function is similar to the cast operator in C. It returns a new instance
Georg Brandl1d837bc2009-12-29 11:24:00 +00001808 of *type* which points to the same memory block as *obj*. *type* must be a
Georg Brandl8d8f1972009-06-08 13:27:23 +00001809 pointer type, and *obj* must be an object that can be interpreted as a
Georg Brandl116aa622007-08-15 14:28:22 +00001810 pointer.
1811
1812
Georg Brandl8d8f1972009-06-08 13:27:23 +00001813.. function:: create_string_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001814
1815 This function creates a mutable character buffer. The returned object is a
1816 ctypes array of :class:`c_char`.
1817
Georg Brandl8d8f1972009-06-08 13:27:23 +00001818 *init_or_size* must be an integer which specifies the size of the array, or a
1819 bytes object which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001820
Georg Brandl8d8f1972009-06-08 13:27:23 +00001821 If a bytes object is specified as first argument, the buffer is made one item
1822 larger than its length so that the last element in the array is a NUL
Georg Brandl116aa622007-08-15 14:28:22 +00001823 termination character. An integer can be passed as second argument which allows
Georg Brandl8d8f1972009-06-08 13:27:23 +00001824 to specify the size of the array if the length of the bytes should not be used.
Georg Brandl116aa622007-08-15 14:28:22 +00001825
Georg Brandl8d8f1972009-06-08 13:27:23 +00001826 If the first parameter is a string, it is converted into a bytes object
Georg Brandl116aa622007-08-15 14:28:22 +00001827 according to ctypes conversion rules.
1828
1829
Georg Brandl8d8f1972009-06-08 13:27:23 +00001830.. function:: create_unicode_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001831
1832 This function creates a mutable unicode character buffer. The returned object is
1833 a ctypes array of :class:`c_wchar`.
1834
Georg Brandl8d8f1972009-06-08 13:27:23 +00001835 *init_or_size* must be an integer which specifies the size of the array, or a
1836 string which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001837
Georg Brandl8d8f1972009-06-08 13:27:23 +00001838 If a string is specified as first argument, the buffer is made one item
Georg Brandl116aa622007-08-15 14:28:22 +00001839 larger than the length of the string so that the last element in the array is a
1840 NUL termination character. An integer can be passed as second argument which
1841 allows to specify the size of the array if the length of the string should not
1842 be used.
1843
Georg Brandl8d8f1972009-06-08 13:27:23 +00001844 If the first parameter is a bytes object, it is converted into an unicode string
Georg Brandl116aa622007-08-15 14:28:22 +00001845 according to ctypes conversion rules.
1846
1847
1848.. function:: DllCanUnloadNow()
1849
Georg Brandl1d837bc2009-12-29 11:24:00 +00001850 Windows only: This function is a hook which allows to implement in-process
1851 COM servers with ctypes. It is called from the DllCanUnloadNow function that
1852 the _ctypes extension dll exports.
Georg Brandl116aa622007-08-15 14:28:22 +00001853
1854
1855.. function:: DllGetClassObject()
1856
Georg Brandl1d837bc2009-12-29 11:24:00 +00001857 Windows only: This function is a hook which allows to implement in-process
1858 COM servers with ctypes. It is called from the DllGetClassObject function
1859 that the ``_ctypes`` extension dll exports.
1860
Georg Brandl116aa622007-08-15 14:28:22 +00001861
Thomas Heller2fadaa22008-06-16 19:56:33 +00001862.. function:: find_library(name)
1863 :module: ctypes.util
1864
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001865 Try to find a library and return a pathname. *name* is the library name
Benjamin Peterson28d88b42009-01-09 03:03:23 +00001866 without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001867 number (this is the form used for the posix linker option :option:`-l`). If
1868 no library can be found, returns ``None``.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001869
1870 The exact functionality is system dependent.
1871
Thomas Heller2fadaa22008-06-16 19:56:33 +00001872
1873.. function:: find_msvcrt()
1874 :module: ctypes.util
1875
Georg Brandl1d837bc2009-12-29 11:24:00 +00001876 Windows only: return the filename of the VC runtype library used by Python,
1877 and by the extension modules. If the name of the library cannot be
1878 determined, ``None`` is returned.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001879
Georg Brandl1d837bc2009-12-29 11:24:00 +00001880 If you need to free memory, for example, allocated by an extension module
1881 with a call to the ``free(void *)``, it is important that you use the
1882 function in the same library that allocated the memory.
1883
Thomas Heller2fadaa22008-06-16 19:56:33 +00001884
Georg Brandl116aa622007-08-15 14:28:22 +00001885.. function:: FormatError([code])
1886
Georg Brandl1d837bc2009-12-29 11:24:00 +00001887 Windows only: Returns a textual description of the error code *code*. If no
1888 error code is specified, the last error code is used by calling the Windows
1889 api function GetLastError.
Georg Brandl116aa622007-08-15 14:28:22 +00001890
1891
1892.. function:: GetLastError()
1893
1894 Windows only: Returns the last error code set by Windows in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001895 This function calls the Windows `GetLastError()` function directly,
1896 it does not return the ctypes-private copy of the error code.
Georg Brandl116aa622007-08-15 14:28:22 +00001897
Thomas Hellerb795f5282008-06-10 15:26:58 +00001898.. function:: get_errno()
1899
1900 Returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001901 :data:`errno` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001902
Thomas Hellerb795f5282008-06-10 15:26:58 +00001903.. function:: get_last_error()
1904
1905 Windows only: returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001906 :data:`LastError` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001907
Georg Brandl116aa622007-08-15 14:28:22 +00001908.. function:: memmove(dst, src, count)
1909
1910 Same as the standard C memmove library function: copies *count* bytes from
Georg Brandl1d837bc2009-12-29 11:24:00 +00001911 *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can
1912 be converted to pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001913
1914
1915.. function:: memset(dst, c, count)
1916
1917 Same as the standard C memset library function: fills the memory block at
1918 address *dst* with *count* bytes of value *c*. *dst* must be an integer
1919 specifying an address, or a ctypes instance.
1920
1921
1922.. function:: POINTER(type)
1923
1924 This factory function creates and returns a new ctypes pointer type. Pointer
1925 types are cached an reused internally, so calling this function repeatedly is
Georg Brandl1d837bc2009-12-29 11:24:00 +00001926 cheap. *type* must be a ctypes type.
Georg Brandl116aa622007-08-15 14:28:22 +00001927
1928
1929.. function:: pointer(obj)
1930
Georg Brandl8d8f1972009-06-08 13:27:23 +00001931 This function creates a new pointer instance, pointing to *obj*. The returned
Georg Brandl1d837bc2009-12-29 11:24:00 +00001932 object is of the type ``POINTER(type(obj))``.
Georg Brandl116aa622007-08-15 14:28:22 +00001933
1934 Note: If you just want to pass a pointer to an object to a foreign function
1935 call, you should use ``byref(obj)`` which is much faster.
1936
1937
1938.. function:: resize(obj, size)
1939
Georg Brandl1d837bc2009-12-29 11:24:00 +00001940 This function resizes the internal memory buffer of *obj*, which must be an
1941 instance of a ctypes type. It is not possible to make the buffer smaller
1942 than the native size of the objects type, as given by ``sizeof(type(obj))``,
1943 but it is possible to enlarge the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00001944
1945
Thomas Hellerb795f5282008-06-10 15:26:58 +00001946.. function:: set_errno(value)
1947
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001948 Set the current value of the ctypes-private copy of the system :data:`errno`
1949 variable in the calling thread to *value* and return the 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
Thomas Hellerb795f5282008-06-10 15:26:58 +00001953.. function:: set_last_error(value)
1954
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001955 Windows only: set the current value of the ctypes-private copy of the system
1956 :data:`LastError` variable in the calling thread to *value* and return the
1957 previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001958
Georg Brandl8d8f1972009-06-08 13:27:23 +00001959
Georg Brandl1d837bc2009-12-29 11:24:00 +00001960
Georg Brandl116aa622007-08-15 14:28:22 +00001961.. function:: sizeof(obj_or_type)
1962
1963 Returns the size in bytes of a ctypes type or instance memory buffer. Does the
1964 same as the C ``sizeof()`` function.
1965
1966
Georg Brandl8d8f1972009-06-08 13:27:23 +00001967.. function:: string_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001968
Ezio Melottie130a522011-10-19 10:58:56 +03001969 This function returns the C string starting at memory address *address* as a bytes
Georg Brandl8d8f1972009-06-08 13:27:23 +00001970 object. If size is specified, it is used as size, otherwise the string is assumed
1971 to be zero-terminated.
Georg Brandl116aa622007-08-15 14:28:22 +00001972
1973
1974.. function:: WinError(code=None, descr=None)
1975
1976 Windows only: this function is probably the worst-named thing in ctypes. It
Antoine Pitrou442ee032011-10-12 18:53:23 +02001977 creates an instance of OSError. If *code* is not specified,
Georg Brandl1d837bc2009-12-29 11:24:00 +00001978 ``GetLastError`` is called to determine the error code. If *descr* is not
Thomas Woutersed03b412007-08-28 21:37:11 +00001979 specified, :func:`FormatError` is called to get a textual description of the
Georg Brandl116aa622007-08-15 14:28:22 +00001980 error.
1981
Antoine Pitrou442ee032011-10-12 18:53:23 +02001982 .. versionchanged:: 3.3
1983 An instance of :exc:`WindowsError` used to be created.
1984
Georg Brandl116aa622007-08-15 14:28:22 +00001985
Georg Brandl8d8f1972009-06-08 13:27:23 +00001986.. function:: wstring_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001987
1988 This function returns the wide character string starting at memory address
Georg Brandl1d837bc2009-12-29 11:24:00 +00001989 *address* as a string. If *size* is specified, it is used as the number of
1990 characters of the string, otherwise the string is assumed to be
Georg Brandl116aa622007-08-15 14:28:22 +00001991 zero-terminated.
1992
1993
1994.. _ctypes-data-types:
1995
1996Data types
1997^^^^^^^^^^
1998
1999
2000.. class:: _CData
2001
Georg Brandl1d837bc2009-12-29 11:24:00 +00002002 This non-public class is the common base class of all ctypes data types.
2003 Among other things, all ctypes type instances contain a memory block that
2004 hold C compatible data; the address of the memory block is returned by the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002005 :func:`addressof` helper function. Another instance variable is exposed as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002006 :attr:`_objects`; this contains other Python objects that need to be kept
2007 alive in case the memory block contains pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00002008
Benjamin Petersone41251e2008-04-25 01:59:09 +00002009 Common methods of ctypes data types, these are all class methods (to be
2010 exact, they are methods of the :term:`metaclass`):
Georg Brandl116aa622007-08-15 14:28:22 +00002011
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002012 .. method:: _CData.from_buffer(source[, offset])
2013
Georg Brandl1d837bc2009-12-29 11:24:00 +00002014 This method returns a ctypes instance that shares the buffer of the
2015 *source* object. The *source* object must support the writeable buffer
2016 interface. The optional *offset* parameter specifies an offset into the
2017 source buffer in bytes; the default is zero. If the source buffer is not
2018 large enough a :exc:`ValueError` is raised.
2019
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002020
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002021 .. method:: _CData.from_buffer_copy(source[, offset])
2022
Georg Brandl1d837bc2009-12-29 11:24:00 +00002023 This method creates a ctypes instance, copying the buffer from the
2024 *source* object buffer which must be readable. The optional *offset*
2025 parameter specifies an offset into the source buffer in bytes; the default
2026 is zero. If the source buffer is not large enough a :exc:`ValueError` is
2027 raised.
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002028
Benjamin Petersone41251e2008-04-25 01:59:09 +00002029 .. method:: from_address(address)
Georg Brandl116aa622007-08-15 14:28:22 +00002030
Benjamin Petersone41251e2008-04-25 01:59:09 +00002031 This method returns a ctypes type instance using the memory specified by
Georg Brandl1d837bc2009-12-29 11:24:00 +00002032 *address* which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00002033
Benjamin Petersone41251e2008-04-25 01:59:09 +00002034 .. method:: from_param(obj)
Georg Brandl116aa622007-08-15 14:28:22 +00002035
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002036 This method adapts *obj* to a ctypes type. It is called with the actual
2037 object used in a foreign function call when the type is present in the
2038 foreign function's :attr:`argtypes` tuple; it must return an object that
2039 can be used as a function call parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00002040
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002041 All ctypes data types have a default implementation of this classmethod
Georg Brandl8d8f1972009-06-08 13:27:23 +00002042 that normally returns *obj* if that is an instance of the type. Some
Benjamin Petersone41251e2008-04-25 01:59:09 +00002043 types accept other objects as well.
Georg Brandl116aa622007-08-15 14:28:22 +00002044
Benjamin Petersone41251e2008-04-25 01:59:09 +00002045 .. method:: in_dll(library, name)
Georg Brandl116aa622007-08-15 14:28:22 +00002046
Benjamin Petersone41251e2008-04-25 01:59:09 +00002047 This method returns a ctypes type instance exported by a shared
2048 library. *name* is the name of the symbol that exports the data, *library*
2049 is the loaded shared library.
Georg Brandl116aa622007-08-15 14:28:22 +00002050
Benjamin Petersone41251e2008-04-25 01:59:09 +00002051 Common instance variables of ctypes data types:
Georg Brandl116aa622007-08-15 14:28:22 +00002052
Benjamin Petersone41251e2008-04-25 01:59:09 +00002053 .. attribute:: _b_base_
Georg Brandl116aa622007-08-15 14:28:22 +00002054
Benjamin Petersone41251e2008-04-25 01:59:09 +00002055 Sometimes ctypes data instances do not own the memory block they contain,
2056 instead they share part of the memory block of a base object. The
2057 :attr:`_b_base_` read-only member is the root ctypes object that owns the
2058 memory block.
Georg Brandl116aa622007-08-15 14:28:22 +00002059
Benjamin Petersone41251e2008-04-25 01:59:09 +00002060 .. attribute:: _b_needsfree_
Georg Brandl116aa622007-08-15 14:28:22 +00002061
Benjamin Petersone41251e2008-04-25 01:59:09 +00002062 This read-only variable is true when the ctypes data instance has
2063 allocated the memory block itself, false otherwise.
2064
Benjamin Petersone41251e2008-04-25 01:59:09 +00002065 .. attribute:: _objects
2066
2067 This member is either ``None`` or a dictionary containing Python objects
2068 that need to be kept alive so that the memory block contents is kept
2069 valid. This object is only exposed for debugging; never modify the
2070 contents of this dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002071
2072
2073.. _ctypes-fundamental-data-types-2:
2074
2075Fundamental data types
2076^^^^^^^^^^^^^^^^^^^^^^
2077
Georg Brandl116aa622007-08-15 14:28:22 +00002078.. class:: _SimpleCData
2079
Benjamin Peterson35e8c462008-04-24 02:34:53 +00002080 This non-public class is the base class of all fundamental ctypes data
2081 types. It is mentioned here because it contains the common attributes of the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002082 fundamental ctypes data types. :class:`_SimpleCData` is a subclass of
2083 :class:`_CData`, so it inherits their methods and attributes. ctypes data
2084 types that are not and do not contain pointers can now be pickled.
Thomas Heller13394e92008-02-13 20:40:44 +00002085
Benjamin Petersone41251e2008-04-25 01:59:09 +00002086 Instances have a single attribute:
Georg Brandl116aa622007-08-15 14:28:22 +00002087
Benjamin Petersone41251e2008-04-25 01:59:09 +00002088 .. attribute:: value
Georg Brandl116aa622007-08-15 14:28:22 +00002089
Benjamin Petersone41251e2008-04-25 01:59:09 +00002090 This attribute contains the actual value of the instance. For integer and
2091 pointer types, it is an integer, for character types, it is a single
Georg Brandl8d8f1972009-06-08 13:27:23 +00002092 character bytes object or string, for character pointer types it is a
2093 Python bytes object or string.
Georg Brandl116aa622007-08-15 14:28:22 +00002094
Benjamin Petersone41251e2008-04-25 01:59:09 +00002095 When the ``value`` attribute is retrieved from a ctypes instance, usually
Georg Brandl8d8f1972009-06-08 13:27:23 +00002096 a new object is returned each time. :mod:`ctypes` does *not* implement
Benjamin Petersone41251e2008-04-25 01:59:09 +00002097 original object return, always a new object is constructed. The same is
2098 true for all other ctypes object instances.
Georg Brandl116aa622007-08-15 14:28:22 +00002099
Georg Brandl8d8f1972009-06-08 13:27:23 +00002100
Georg Brandl116aa622007-08-15 14:28:22 +00002101Fundamental data types, when returned as foreign function call results, or, for
2102example, by retrieving structure field members or array items, are transparently
2103converted to native Python types. In other words, if a foreign function has a
Georg Brandl8d8f1972009-06-08 13:27:23 +00002104:attr:`restype` of :class:`c_char_p`, you will always receive a Python bytes
2105object, *not* a :class:`c_char_p` instance.
2106
2107.. XXX above is false, it actually returns a Unicode string
Georg Brandl116aa622007-08-15 14:28:22 +00002108
Thomas Woutersed03b412007-08-28 21:37:11 +00002109Subclasses of fundamental data types do *not* inherit this behavior. So, if a
Georg Brandl116aa622007-08-15 14:28:22 +00002110foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2111receive an instance of this subclass from the function call. Of course, you can
2112get the value of the pointer by accessing the ``value`` attribute.
2113
2114These are the fundamental ctypes data types:
2115
Georg Brandl116aa622007-08-15 14:28:22 +00002116.. class:: c_byte
2117
Georg Brandl60203b42010-10-06 10:11:56 +00002118 Represents the C :c:type:`signed char` datatype, and interprets the value as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002119 small integer. The constructor accepts an optional integer initializer; no
2120 overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002121
2122
2123.. class:: c_char
2124
Georg Brandl60203b42010-10-06 10:11:56 +00002125 Represents the C :c:type:`char` datatype, and interprets the value as a single
Georg Brandl1d837bc2009-12-29 11:24:00 +00002126 character. The constructor accepts an optional string initializer, the
2127 length of the string must be exactly one character.
Georg Brandl116aa622007-08-15 14:28:22 +00002128
2129
2130.. class:: c_char_p
2131
Georg Brandl60203b42010-10-06 10:11:56 +00002132 Represents the C :c:type:`char *` datatype when it points to a zero-terminated
Georg Brandl1d837bc2009-12-29 11:24:00 +00002133 string. For a general character pointer that may also point to binary data,
2134 ``POINTER(c_char)`` must be used. The constructor accepts an integer
2135 address, or a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +00002136
2137
2138.. class:: c_double
2139
Georg Brandl60203b42010-10-06 10:11:56 +00002140 Represents the C :c:type:`double` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002141 optional float initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002142
2143
Thomas Wouters89d996e2007-09-08 17:39:28 +00002144.. class:: c_longdouble
2145
Georg Brandl60203b42010-10-06 10:11:56 +00002146 Represents the C :c:type:`long double` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002147 optional float initializer. On platforms where ``sizeof(long double) ==
2148 sizeof(double)`` it is an alias to :class:`c_double`.
Thomas Wouters89d996e2007-09-08 17:39:28 +00002149
Georg Brandl116aa622007-08-15 14:28:22 +00002150.. class:: c_float
2151
Georg Brandl60203b42010-10-06 10:11:56 +00002152 Represents the C :c:type:`float` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002153 optional float initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002154
2155
2156.. class:: c_int
2157
Georg Brandl60203b42010-10-06 10:11:56 +00002158 Represents the C :c:type:`signed int` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002159 optional integer initializer; no overflow checking is done. On platforms
2160 where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
Georg Brandl116aa622007-08-15 14:28:22 +00002161
2162
2163.. class:: c_int8
2164
Georg Brandl60203b42010-10-06 10:11:56 +00002165 Represents the C 8-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002166 :class:`c_byte`.
2167
2168
2169.. class:: c_int16
2170
Georg Brandl60203b42010-10-06 10:11:56 +00002171 Represents the C 16-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002172 :class:`c_short`.
2173
2174
2175.. class:: c_int32
2176
Georg Brandl60203b42010-10-06 10:11:56 +00002177 Represents the C 32-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002178 :class:`c_int`.
2179
2180
2181.. class:: c_int64
2182
Georg Brandl60203b42010-10-06 10:11:56 +00002183 Represents the C 64-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002184 :class:`c_longlong`.
2185
2186
2187.. class:: c_long
2188
Georg Brandl60203b42010-10-06 10:11:56 +00002189 Represents the C :c:type:`signed long` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002190 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002191
2192
2193.. class:: c_longlong
2194
Georg Brandl60203b42010-10-06 10:11:56 +00002195 Represents the C :c:type:`signed long long` datatype. The constructor accepts
Georg Brandl1d837bc2009-12-29 11:24:00 +00002196 an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002197
2198
2199.. class:: c_short
2200
Georg Brandl60203b42010-10-06 10:11:56 +00002201 Represents the C :c:type:`signed short` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002202 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002203
2204
2205.. class:: c_size_t
2206
Georg Brandl60203b42010-10-06 10:11:56 +00002207 Represents the C :c:type:`size_t` datatype.
Georg Brandl116aa622007-08-15 14:28:22 +00002208
2209
Gregory P. Smith1a530912010-03-01 04:59:27 +00002210.. class:: c_ssize_t
2211
Georg Brandl60203b42010-10-06 10:11:56 +00002212 Represents the C :c:type:`ssize_t` datatype.
Gregory P. Smith1a530912010-03-01 04:59:27 +00002213
2214 .. versionadded:: 3.2
2215
2216
Georg Brandl116aa622007-08-15 14:28:22 +00002217.. class:: c_ubyte
2218
Georg Brandl60203b42010-10-06 10:11:56 +00002219 Represents the C :c:type:`unsigned char` datatype, it interprets the value as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002220 small integer. The constructor accepts an optional integer initializer; no
2221 overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002222
2223
2224.. class:: c_uint
2225
Georg Brandl60203b42010-10-06 10:11:56 +00002226 Represents the C :c:type:`unsigned int` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002227 optional integer initializer; no overflow checking is done. On platforms
2228 where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
Georg Brandl116aa622007-08-15 14:28:22 +00002229
2230
2231.. class:: c_uint8
2232
Georg Brandl60203b42010-10-06 10:11:56 +00002233 Represents the C 8-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002234 :class:`c_ubyte`.
2235
2236
2237.. class:: c_uint16
2238
Georg Brandl60203b42010-10-06 10:11:56 +00002239 Represents the C 16-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002240 :class:`c_ushort`.
2241
2242
2243.. class:: c_uint32
2244
Georg Brandl60203b42010-10-06 10:11:56 +00002245 Represents the C 32-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002246 :class:`c_uint`.
2247
2248
2249.. class:: c_uint64
2250
Georg Brandl60203b42010-10-06 10:11:56 +00002251 Represents the C 64-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002252 :class:`c_ulonglong`.
2253
2254
2255.. class:: c_ulong
2256
Georg Brandl60203b42010-10-06 10:11:56 +00002257 Represents the C :c:type:`unsigned long` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002258 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002259
2260
2261.. class:: c_ulonglong
2262
Georg Brandl60203b42010-10-06 10:11:56 +00002263 Represents the C :c:type:`unsigned long long` datatype. The constructor
Georg Brandl1d837bc2009-12-29 11:24:00 +00002264 accepts an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002265
2266
2267.. class:: c_ushort
2268
Georg Brandl60203b42010-10-06 10:11:56 +00002269 Represents the C :c:type:`unsigned short` datatype. The constructor accepts
Georg Brandl1d837bc2009-12-29 11:24:00 +00002270 an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002271
2272
2273.. class:: c_void_p
2274
Georg Brandl60203b42010-10-06 10:11:56 +00002275 Represents the C :c:type:`void *` type. The value is represented as integer.
Georg Brandl1d837bc2009-12-29 11:24:00 +00002276 The constructor accepts an optional integer initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002277
2278
2279.. class:: c_wchar
2280
Georg Brandl60203b42010-10-06 10:11:56 +00002281 Represents the C :c:type:`wchar_t` datatype, and interprets the value as a
Georg Brandl1d837bc2009-12-29 11:24:00 +00002282 single character unicode string. The constructor accepts an optional string
Georg Brandl116aa622007-08-15 14:28:22 +00002283 initializer, the length of the string must be exactly one character.
2284
2285
2286.. class:: c_wchar_p
2287
Georg Brandl60203b42010-10-06 10:11:56 +00002288 Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a
Georg Brandl1d837bc2009-12-29 11:24:00 +00002289 zero-terminated wide character string. The constructor accepts an integer
Georg Brandl116aa622007-08-15 14:28:22 +00002290 address, or a string.
2291
2292
2293.. class:: c_bool
2294
Georg Brandl60203b42010-10-06 10:11:56 +00002295 Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from
Georg Brandl1d837bc2009-12-29 11:24:00 +00002296 C99). Its value can be True or False, and the constructor accepts any object
2297 that has a truth value.
Georg Brandl116aa622007-08-15 14:28:22 +00002298
Georg Brandl116aa622007-08-15 14:28:22 +00002299
2300.. class:: HRESULT
2301
Georg Brandl60203b42010-10-06 10:11:56 +00002302 Windows only: Represents a :c:type:`HRESULT` value, which contains success or
Georg Brandl116aa622007-08-15 14:28:22 +00002303 error information for a function or method call.
2304
2305
2306.. class:: py_object
2307
Georg Brandl60203b42010-10-06 10:11:56 +00002308 Represents the C :c:type:`PyObject *` datatype. Calling this without an
2309 argument creates a ``NULL`` :c:type:`PyObject *` pointer.
Georg Brandl116aa622007-08-15 14:28:22 +00002310
Georg Brandl1d837bc2009-12-29 11:24:00 +00002311The :mod:`ctypes.wintypes` module provides quite some other Windows specific
Georg Brandl60203b42010-10-06 10:11:56 +00002312data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`. Some
2313useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined.
Georg Brandl116aa622007-08-15 14:28:22 +00002314
2315
2316.. _ctypes-structured-data-types:
2317
2318Structured data types
2319^^^^^^^^^^^^^^^^^^^^^
2320
2321
2322.. class:: Union(*args, **kw)
2323
2324 Abstract base class for unions in native byte order.
2325
2326
2327.. class:: BigEndianStructure(*args, **kw)
2328
2329 Abstract base class for structures in *big endian* byte order.
2330
2331
2332.. class:: LittleEndianStructure(*args, **kw)
2333
2334 Abstract base class for structures in *little endian* byte order.
2335
2336Structures with non-native byte order cannot contain pointer type fields, or any
2337other data types containing pointer type fields.
2338
2339
2340.. class:: Structure(*args, **kw)
2341
2342 Abstract base class for structures in *native* byte order.
2343
Benjamin Petersone41251e2008-04-25 01:59:09 +00002344 Concrete structure and union types must be created by subclassing one of these
Georg Brandl8d8f1972009-06-08 13:27:23 +00002345 types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
Benjamin Petersone41251e2008-04-25 01:59:09 +00002346 create :term:`descriptor`\s which allow reading and writing the fields by direct
2347 attribute accesses. These are the
Georg Brandl116aa622007-08-15 14:28:22 +00002348
2349
Benjamin Petersone41251e2008-04-25 01:59:09 +00002350 .. attribute:: _fields_
Georg Brandl116aa622007-08-15 14:28:22 +00002351
Benjamin Petersone41251e2008-04-25 01:59:09 +00002352 A sequence defining the structure fields. The items must be 2-tuples or
2353 3-tuples. The first item is the name of the field, the second item
2354 specifies the type of the field; it can be any ctypes data type.
Georg Brandl116aa622007-08-15 14:28:22 +00002355
Benjamin Petersone41251e2008-04-25 01:59:09 +00002356 For integer type fields like :class:`c_int`, a third optional item can be
2357 given. It must be a small positive integer defining the bit width of the
2358 field.
Georg Brandl116aa622007-08-15 14:28:22 +00002359
Benjamin Petersone41251e2008-04-25 01:59:09 +00002360 Field names must be unique within one structure or union. This is not
2361 checked, only one field can be accessed when names are repeated.
Georg Brandl116aa622007-08-15 14:28:22 +00002362
Benjamin Petersone41251e2008-04-25 01:59:09 +00002363 It is possible to define the :attr:`_fields_` class variable *after* the
2364 class statement that defines the Structure subclass, this allows to create
2365 data types that directly or indirectly reference themselves::
Georg Brandl116aa622007-08-15 14:28:22 +00002366
Benjamin Petersone41251e2008-04-25 01:59:09 +00002367 class List(Structure):
2368 pass
2369 List._fields_ = [("pnext", POINTER(List)),
2370 ...
2371 ]
Georg Brandl116aa622007-08-15 14:28:22 +00002372
Benjamin Petersone41251e2008-04-25 01:59:09 +00002373 The :attr:`_fields_` class variable must, however, be defined before the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002374 type is first used (an instance is created, :func:`sizeof` is called on it,
Benjamin Petersone41251e2008-04-25 01:59:09 +00002375 and so on). Later assignments to the :attr:`_fields_` class variable will
2376 raise an AttributeError.
Georg Brandl116aa622007-08-15 14:28:22 +00002377
Benjamin Petersone41251e2008-04-25 01:59:09 +00002378 Structure and union subclass constructors accept both positional and named
2379 arguments. Positional arguments are used to initialize the fields in the
2380 same order as they appear in the :attr:`_fields_` definition, named
2381 arguments are used to initialize the fields with the corresponding name.
Georg Brandl116aa622007-08-15 14:28:22 +00002382
Benjamin Petersone41251e2008-04-25 01:59:09 +00002383 It is possible to defined sub-subclasses of structure types, they inherit
2384 the fields of the base class plus the :attr:`_fields_` defined in the
2385 sub-subclass, if any.
Georg Brandl116aa622007-08-15 14:28:22 +00002386
2387
Benjamin Petersone41251e2008-04-25 01:59:09 +00002388 .. attribute:: _pack_
Georg Brandl116aa622007-08-15 14:28:22 +00002389
Benjamin Petersone41251e2008-04-25 01:59:09 +00002390 An optional small integer that allows to override the alignment of
2391 structure fields in the instance. :attr:`_pack_` must already be defined
2392 when :attr:`_fields_` is assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002393
2394
Benjamin Petersone41251e2008-04-25 01:59:09 +00002395 .. attribute:: _anonymous_
Georg Brandl116aa622007-08-15 14:28:22 +00002396
Benjamin Petersone41251e2008-04-25 01:59:09 +00002397 An optional sequence that lists the names of unnamed (anonymous) fields.
Georg Brandl1d837bc2009-12-29 11:24:00 +00002398 :attr:`_anonymous_` must be already defined when :attr:`_fields_` is
2399 assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002400
Benjamin Petersone41251e2008-04-25 01:59:09 +00002401 The fields listed in this variable must be structure or union type fields.
Georg Brandl8d8f1972009-06-08 13:27:23 +00002402 :mod:`ctypes` will create descriptors in the structure type that allows to
Benjamin Petersone41251e2008-04-25 01:59:09 +00002403 access the nested fields directly, without the need to create the
2404 structure or union field.
Georg Brandl116aa622007-08-15 14:28:22 +00002405
Benjamin Petersone41251e2008-04-25 01:59:09 +00002406 Here is an example type (Windows)::
Georg Brandl116aa622007-08-15 14:28:22 +00002407
Benjamin Petersone41251e2008-04-25 01:59:09 +00002408 class _U(Union):
2409 _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2410 ("lpadesc", POINTER(ARRAYDESC)),
2411 ("hreftype", HREFTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002412
Benjamin Petersone41251e2008-04-25 01:59:09 +00002413 class TYPEDESC(Structure):
Benjamin Petersonb58dda72009-01-18 22:27:04 +00002414 _anonymous_ = ("u",)
Benjamin Petersone41251e2008-04-25 01:59:09 +00002415 _fields_ = [("u", _U),
2416 ("vt", VARTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002417
Georg Brandl116aa622007-08-15 14:28:22 +00002418
Benjamin Petersone41251e2008-04-25 01:59:09 +00002419 The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2420 specifies which one of the union fields is valid. Since the ``u`` field
2421 is defined as anonymous field, it is now possible to access the members
2422 directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2423 are equivalent, but the former is faster since it does not need to create
2424 a temporary union instance::
Georg Brandl116aa622007-08-15 14:28:22 +00002425
Benjamin Petersone41251e2008-04-25 01:59:09 +00002426 td = TYPEDESC()
2427 td.vt = VT_PTR
2428 td.lptdesc = POINTER(some_type)
2429 td.u.lptdesc = POINTER(some_type)
Georg Brandl116aa622007-08-15 14:28:22 +00002430
Georg Brandl1d837bc2009-12-29 11:24:00 +00002431 It is possible to defined sub-subclasses of structures, they inherit the
2432 fields of the base class. If the subclass definition has a separate
2433 :attr:`_fields_` variable, the fields specified in this are appended to the
2434 fields of the base class.
Georg Brandl116aa622007-08-15 14:28:22 +00002435
Georg Brandl1d837bc2009-12-29 11:24:00 +00002436 Structure and union constructors accept both positional and keyword
2437 arguments. Positional arguments are used to initialize member fields in the
2438 same order as they are appear in :attr:`_fields_`. Keyword arguments in the
2439 constructor are interpreted as attribute assignments, so they will initialize
2440 :attr:`_fields_` with the same name, or create new attributes for names not
2441 present in :attr:`_fields_`.
Georg Brandl116aa622007-08-15 14:28:22 +00002442
2443
2444.. _ctypes-arrays-pointers:
2445
2446Arrays and pointers
2447^^^^^^^^^^^^^^^^^^^
2448
Georg Brandl1d837bc2009-12-29 11:24:00 +00002449Not yet written - please see the sections :ref:`ctypes-pointers` and section
2450:ref:`ctypes-arrays` in the tutorial.
Georg Brandl116aa622007-08-15 14:28:22 +00002451