blob: 5f5a5125963dc9dafbfd102b2aef7721c07472c6 [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+----------------------+------------------------------------------+----------------------------+
Antoine Pitrou52cc7222012-07-12 20:31:50 +0200251| :class:`c_size_t` | :c:type:`size_t` | int |
252+----------------------+------------------------------------------+----------------------------+
253| :class:`c_ssize_t` | :c:type:`ssize_t` or | int |
254| | :c:type:`Py_ssize_t` | |
255+----------------------+------------------------------------------+----------------------------+
Georg Brandl60203b42010-10-06 10:11:56 +0000256| :class:`c_float` | :c:type:`float` | float |
257+----------------------+------------------------------------------+----------------------------+
258| :class:`c_double` | :c:type:`double` | float |
259+----------------------+------------------------------------------+----------------------------+
260| :class:`c_longdouble`| :c:type:`long double` | float |
261+----------------------+------------------------------------------+----------------------------+
262| :class:`c_char_p` | :c:type:`char *` (NUL terminated) | bytes object or ``None`` |
263+----------------------+------------------------------------------+----------------------------+
264| :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | string or ``None`` |
265+----------------------+------------------------------------------+----------------------------+
266| :class:`c_void_p` | :c:type:`void *` | int or ``None`` |
267+----------------------+------------------------------------------+----------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000268
Georg Brandlecdd63f2011-01-19 20:05:49 +0000269(1)
270 The constructor accepts any object with a truth value.
271
Georg Brandl116aa622007-08-15 14:28:22 +0000272All these types can be created by calling them with an optional initializer of
273the correct type and value::
274
275 >>> c_int()
276 c_long(0)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000277 >>> c_wchar_p("Hello, World")
278 c_wchar_p('Hello, World')
Georg Brandl116aa622007-08-15 14:28:22 +0000279 >>> c_ushort(-3)
280 c_ushort(65533)
281 >>>
282
283Since these types are mutable, their value can also be changed afterwards::
284
285 >>> i = c_int(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000286 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000287 c_long(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000288 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000289 42
290 >>> i.value = -99
Georg Brandl6911e3c2007-09-04 07:15:32 +0000291 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000292 -99
293 >>>
294
295Assigning a new value to instances of the pointer types :class:`c_char_p`,
296:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
297point to, *not the contents* of the memory block (of course not, because Python
Georg Brandl8d8f1972009-06-08 13:27:23 +0000298bytes objects are immutable)::
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300 >>> s = "Hello, World"
Georg Brandl8d8f1972009-06-08 13:27:23 +0000301 >>> c_s = c_wchar_p(s)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000302 >>> print(c_s)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000303 c_wchar_p('Hello, World')
Georg Brandl116aa622007-08-15 14:28:22 +0000304 >>> c_s.value = "Hi, there"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000305 >>> print(c_s)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000306 c_wchar_p('Hi, there')
307 >>> print(s) # first object is unchanged
Georg Brandl116aa622007-08-15 14:28:22 +0000308 Hello, World
309 >>>
310
311You should be careful, however, not to pass them to functions expecting pointers
312to mutable memory. If you need mutable memory blocks, ctypes has a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000313:func:`create_string_buffer` function which creates these in various ways. The
Georg Brandl116aa622007-08-15 14:28:22 +0000314current memory block contents can be accessed (or changed) with the ``raw``
315property; if you want to access it as NUL terminated string, use the ``value``
316property::
317
318 >>> from ctypes import *
Georg Brandl8d8f1972009-06-08 13:27:23 +0000319 >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
Georg Brandl6911e3c2007-09-04 07:15:32 +0000320 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000321 3 b'\x00\x00\x00'
322 >>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string
Georg Brandl6911e3c2007-09-04 07:15:32 +0000323 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000324 6 b'Hello\x00'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000325 >>> print(repr(p.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000326 b'Hello'
327 >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000328 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000329 10 b'Hello\x00\x00\x00\x00\x00'
330 >>> p.value = b"Hi"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000331 >>> print(sizeof(p), repr(p.raw))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000332 10 b'Hi\x00lo\x00\x00\x00\x00\x00'
Georg Brandl116aa622007-08-15 14:28:22 +0000333 >>>
334
Georg Brandl1d837bc2009-12-29 11:24:00 +0000335The :func:`create_string_buffer` function replaces the :func:`c_buffer` function
336(which is still available as an alias), as well as the :func:`c_string` function
Georg Brandl8d8f1972009-06-08 13:27:23 +0000337from earlier ctypes releases. To create a mutable memory block containing
Georg Brandl60203b42010-10-06 10:11:56 +0000338unicode characters of the C type :c:type:`wchar_t` use the
Georg Brandl8d8f1972009-06-08 13:27:23 +0000339:func:`create_unicode_buffer` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000340
341
342.. _ctypes-calling-functions-continued:
343
344Calling functions, continued
345^^^^^^^^^^^^^^^^^^^^^^^^^^^^
346
347Note that printf prints to the real standard output channel, *not* to
Georg Brandl8d8f1972009-06-08 13:27:23 +0000348:data:`sys.stdout`, so these examples will only work at the console prompt, not
349from within *IDLE* or *PythonWin*::
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351 >>> printf = libc.printf
Georg Brandl8d8f1972009-06-08 13:27:23 +0000352 >>> printf(b"Hello, %s\n", b"World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000353 Hello, World!
354 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000355 >>> printf(b"Hello, %S\n", "World!")
Georg Brandl116aa622007-08-15 14:28:22 +0000356 Hello, World!
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000357 14
Georg Brandl8d8f1972009-06-08 13:27:23 +0000358 >>> printf(b"%d bottles of beer\n", 42)
Georg Brandl116aa622007-08-15 14:28:22 +0000359 42 bottles of beer
360 19
Georg Brandl8d8f1972009-06-08 13:27:23 +0000361 >>> printf(b"%f bottles of beer\n", 42.5)
Georg Brandl116aa622007-08-15 14:28:22 +0000362 Traceback (most recent call last):
363 File "<stdin>", line 1, in ?
364 ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
365 >>>
366
367As has been mentioned before, all Python types except integers, strings, and
Georg Brandl8d8f1972009-06-08 13:27:23 +0000368bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so
Georg Brandl116aa622007-08-15 14:28:22 +0000369that they can be converted to the required C data type::
370
Georg Brandl8d8f1972009-06-08 13:27:23 +0000371 >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000372 An int 1234, a double 3.140000
Georg Brandl116aa622007-08-15 14:28:22 +0000373 31
374 >>>
375
376
377.. _ctypes-calling-functions-with-own-custom-data-types:
378
379Calling functions with your own custom data types
380^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
381
Georg Brandl1d837bc2009-12-29 11:24:00 +0000382You can also customize :mod:`ctypes` argument conversion to allow instances of
383your own classes be used as function arguments. :mod:`ctypes` looks for an
384:attr:`_as_parameter_` attribute and uses this as the function argument. Of
Georg Brandl8d8f1972009-06-08 13:27:23 +0000385course, it must be one of integer, string, or bytes::
Georg Brandl116aa622007-08-15 14:28:22 +0000386
Éric Araujo28053fb2010-11-22 03:09:19 +0000387 >>> class Bottles:
Georg Brandl116aa622007-08-15 14:28:22 +0000388 ... def __init__(self, number):
389 ... self._as_parameter_ = number
390 ...
391 >>> bottles = Bottles(42)
Georg Brandl8d8f1972009-06-08 13:27:23 +0000392 >>> printf(b"%d bottles of beer\n", bottles)
Georg Brandl116aa622007-08-15 14:28:22 +0000393 42 bottles of beer
394 19
395 >>>
396
397If you don't want to store the instance's data in the :attr:`_as_parameter_`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000398instance variable, you could define a :class:`property` which makes the
399attribute available on request.
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401
402.. _ctypes-specifying-required-argument-types:
403
404Specifying the required argument types (function prototypes)
405^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
406
407It is possible to specify the required argument types of functions exported from
408DLLs by setting the :attr:`argtypes` attribute.
409
410:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
411probably not a good example here, because it takes a variable number and
412different types of parameters depending on the format string, on the other hand
413this is quite handy to experiment with this feature)::
414
415 >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000416 >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
Georg Brandl116aa622007-08-15 14:28:22 +0000417 String 'Hi', Int 10, Double 2.200000
418 37
419 >>>
420
421Specifying a format protects against incompatible argument types (just as a
422prototype for a C function), and tries to convert the arguments to valid types::
423
Georg Brandl8d8f1972009-06-08 13:27:23 +0000424 >>> printf(b"%d %d %d", 1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000425 Traceback (most recent call last):
426 File "<stdin>", line 1, in ?
427 ArgumentError: argument 2: exceptions.TypeError: wrong type
Georg Brandl8d8f1972009-06-08 13:27:23 +0000428 >>> printf(b"%s %d %f\n", b"X", 2, 3)
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000429 X 2 3.000000
430 13
Georg Brandl116aa622007-08-15 14:28:22 +0000431 >>>
432
433If you have defined your own classes which you pass to function calls, you have
434to implement a :meth:`from_param` class method for them to be able to use them
435in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
436the Python object passed to the function call, it should do a typecheck or
437whatever is needed to make sure this object is acceptable, and then return the
Thomas Heller2fadaa22008-06-16 19:56:33 +0000438object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
Georg Brandl116aa622007-08-15 14:28:22 +0000439pass as the C function argument in this case. Again, the result should be an
Georg Brandl8d8f1972009-06-08 13:27:23 +0000440integer, string, bytes, a :mod:`ctypes` instance, or an object with an
Georg Brandl116aa622007-08-15 14:28:22 +0000441:attr:`_as_parameter_` attribute.
442
443
444.. _ctypes-return-types:
445
446Return types
447^^^^^^^^^^^^
448
Georg Brandl60203b42010-10-06 10:11:56 +0000449By default functions are assumed to return the C :c:type:`int` type. Other
Georg Brandl1d837bc2009-12-29 11:24:00 +0000450return types can be specified by setting the :attr:`restype` attribute of the
451function object.
Georg Brandl116aa622007-08-15 14:28:22 +0000452
453Here is a more advanced example, it uses the ``strchr`` function, which expects
454a string pointer and a char, and returns a pointer to a string::
455
456 >>> strchr = libc.strchr
Georg Brandl8d8f1972009-06-08 13:27:23 +0000457 >>> strchr(b"abcdef", ord("d")) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000458 8059983
Georg Brandl8d8f1972009-06-08 13:27:23 +0000459 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
460 >>> strchr(b"abcdef", ord("d"))
461 b'def'
462 >>> print(strchr(b"abcdef", ord("x")))
Georg Brandl116aa622007-08-15 14:28:22 +0000463 None
464 >>>
465
466If you want to avoid the ``ord("x")`` calls above, you can set the
467:attr:`argtypes` attribute, and the second argument will be converted from a
Georg Brandl8d8f1972009-06-08 13:27:23 +0000468single character Python bytes object into a C char::
Georg Brandl116aa622007-08-15 14:28:22 +0000469
470 >>> strchr.restype = c_char_p
471 >>> strchr.argtypes = [c_char_p, c_char]
Georg Brandl8d8f1972009-06-08 13:27:23 +0000472 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000473 'def'
Georg Brandl8d8f1972009-06-08 13:27:23 +0000474 >>> strchr(b"abcdef", b"def")
Georg Brandl116aa622007-08-15 14:28:22 +0000475 Traceback (most recent call last):
476 File "<stdin>", line 1, in ?
477 ArgumentError: argument 2: exceptions.TypeError: one character string expected
Georg Brandl8d8f1972009-06-08 13:27:23 +0000478 >>> print(strchr(b"abcdef", b"x"))
Georg Brandl116aa622007-08-15 14:28:22 +0000479 None
Georg Brandl8d8f1972009-06-08 13:27:23 +0000480 >>> strchr(b"abcdef", b"d")
Georg Brandl116aa622007-08-15 14:28:22 +0000481 'def'
482 >>>
483
484You can also use a callable Python object (a function or a class for example) as
485the :attr:`restype` attribute, if the foreign function returns an integer. The
Georg Brandl1d837bc2009-12-29 11:24:00 +0000486callable will be called with the *integer* the C function returns, and the
Georg Brandl116aa622007-08-15 14:28:22 +0000487result of this call will be used as the result of your function call. This is
488useful to check for error return values and automatically raise an exception::
489
490 >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
491 >>> def ValidHandle(value):
492 ... if value == 0:
493 ... raise WinError()
494 ... return value
495 ...
496 >>>
497 >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
498 >>> GetModuleHandle(None) # doctest: +WINDOWS
499 486539264
500 >>> GetModuleHandle("something silly") # doctest: +WINDOWS
501 Traceback (most recent call last):
502 File "<stdin>", line 1, in ?
503 File "<stdin>", line 3, in ValidHandle
Antoine Pitrou442ee032011-10-12 18:53:23 +0200504 OSError: [Errno 126] The specified module could not be found.
Georg Brandl116aa622007-08-15 14:28:22 +0000505 >>>
506
507``WinError`` is a function which will call Windows ``FormatMessage()`` api to
508get the string representation of an error code, and *returns* an exception.
509``WinError`` takes an optional error code parameter, if no one is used, it calls
510:func:`GetLastError` to retrieve it.
511
512Please note that a much more powerful error checking mechanism is available
513through the :attr:`errcheck` attribute; see the reference manual for details.
514
515
516.. _ctypes-passing-pointers:
517
518Passing pointers (or: passing parameters by reference)
519^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
520
521Sometimes a C api function expects a *pointer* to a data type as parameter,
522probably to write into the corresponding location, or if the data is too large
523to be passed by value. This is also known as *passing parameters by reference*.
524
Georg Brandl8d8f1972009-06-08 13:27:23 +0000525:mod:`ctypes` exports the :func:`byref` function which is used to pass parameters
526by reference. The same effect can be achieved with the :func:`pointer` function,
527although :func:`pointer` does a lot more work since it constructs a real pointer
Georg Brandl116aa622007-08-15 14:28:22 +0000528object, so it is faster to use :func:`byref` if you don't need the pointer
529object in Python itself::
530
531 >>> i = c_int()
532 >>> f = c_float()
Georg Brandl8d8f1972009-06-08 13:27:23 +0000533 >>> s = create_string_buffer(b'\000' * 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000534 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000535 0 0.0 b''
536 >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
Georg Brandl116aa622007-08-15 14:28:22 +0000537 ... byref(i), byref(f), s)
538 3
Georg Brandl6911e3c2007-09-04 07:15:32 +0000539 >>> print(i.value, f.value, repr(s.value))
Georg Brandl8d8f1972009-06-08 13:27:23 +0000540 1 3.1400001049 b'Hello'
Georg Brandl116aa622007-08-15 14:28:22 +0000541 >>>
542
543
544.. _ctypes-structures-unions:
545
546Structures and unions
547^^^^^^^^^^^^^^^^^^^^^
548
549Structures and unions must derive from the :class:`Structure` and :class:`Union`
Georg Brandl8d8f1972009-06-08 13:27:23 +0000550base classes which are defined in the :mod:`ctypes` module. Each subclass must
Georg Brandl116aa622007-08-15 14:28:22 +0000551define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
552*2-tuples*, containing a *field name* and a *field type*.
553
Georg Brandl8d8f1972009-06-08 13:27:23 +0000554The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
555derived :mod:`ctypes` type: structure, union, array, pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557Here is a simple example of a POINT structure, which contains two integers named
Georg Brandl8d8f1972009-06-08 13:27:23 +0000558*x* and *y*, and also shows how to initialize a structure in the constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000559
560 >>> from ctypes import *
561 >>> class POINT(Structure):
562 ... _fields_ = [("x", c_int),
563 ... ("y", c_int)]
564 ...
565 >>> point = POINT(10, 20)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000566 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000567 10 20
568 >>> point = POINT(y=5)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000569 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000570 0 5
571 >>> POINT(1, 2, 3)
572 Traceback (most recent call last):
573 File "<stdin>", line 1, in ?
574 ValueError: too many initializers
575 >>>
576
Eli Benderskyf9164e12013-03-06 06:48:57 -0800577You can, however, build much more complicated structures. A structure can
578itself contain other structures by using a structure as a field type.
Georg Brandl116aa622007-08-15 14:28:22 +0000579
Georg Brandl1d837bc2009-12-29 11:24:00 +0000580Here is a RECT structure which contains two POINTs named *upperleft* and
581*lowerright*::
Georg Brandl116aa622007-08-15 14:28:22 +0000582
583 >>> class RECT(Structure):
584 ... _fields_ = [("upperleft", POINT),
585 ... ("lowerright", POINT)]
586 ...
587 >>> rc = RECT(point)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000588 >>> print(rc.upperleft.x, rc.upperleft.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000589 0 5
Georg Brandl6911e3c2007-09-04 07:15:32 +0000590 >>> print(rc.lowerright.x, rc.lowerright.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000591 0 0
592 >>>
593
594Nested structures can also be initialized in the constructor in several ways::
595
596 >>> r = RECT(POINT(1, 2), POINT(3, 4))
597 >>> r = RECT((1, 2), (3, 4))
598
Georg Brandl9afde1c2007-11-01 20:32:30 +0000599Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
600for debugging because they can provide useful information::
Georg Brandl116aa622007-08-15 14:28:22 +0000601
Georg Brandl6911e3c2007-09-04 07:15:32 +0000602 >>> print(POINT.x)
Georg Brandl116aa622007-08-15 14:28:22 +0000603 <Field type=c_long, ofs=0, size=4>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000604 >>> print(POINT.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000605 <Field type=c_long, ofs=4, size=4>
606 >>>
607
608
609.. _ctypes-structureunion-alignment-byte-order:
610
Eli Bendersky490cf442013-03-09 05:54:00 -0800611.. warning::
612
613 :mod:`ctypes` does not support passing unions or structures with bit-fields
614 to functions by value. While this may work on 32-bit x86, it's not
615 guaranteed by the library to work in the general case. Unions and
616 structures with bit-fields should always be passed to functions by pointer.
617
Georg Brandl116aa622007-08-15 14:28:22 +0000618Structure/union alignment and byte order
619^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
620
621By default, Structure and Union fields are aligned in the same way the C
Thomas Woutersed03b412007-08-28 21:37:11 +0000622compiler does it. It is possible to override this behavior be specifying a
Georg Brandl116aa622007-08-15 14:28:22 +0000623:attr:`_pack_` class attribute in the subclass definition. This must be set to a
624positive integer and specifies the maximum alignment for the fields. This is
625what ``#pragma pack(n)`` also does in MSVC.
626
Georg Brandl8d8f1972009-06-08 13:27:23 +0000627:mod:`ctypes` uses the native byte order for Structures and Unions. To build
Georg Brandl116aa622007-08-15 14:28:22 +0000628structures with non-native byte order, you can use one of the
Georg Brandl1d837bc2009-12-29 11:24:00 +0000629:class:`BigEndianStructure`, :class:`LittleEndianStructure`,
630:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These
631classes cannot contain pointer fields.
Georg Brandl116aa622007-08-15 14:28:22 +0000632
633
634.. _ctypes-bit-fields-in-structures-unions:
635
636Bit fields in structures and unions
637^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
638
639It is possible to create structures and unions containing bit fields. Bit fields
640are only possible for integer fields, the bit width is specified as the third
641item in the :attr:`_fields_` tuples::
642
643 >>> class Int(Structure):
644 ... _fields_ = [("first_16", c_int, 16),
645 ... ("second_16", c_int, 16)]
646 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000647 >>> print(Int.first_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000648 <Field type=c_long, ofs=0:0, bits=16>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000649 >>> print(Int.second_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000650 <Field type=c_long, ofs=0:16, bits=16>
651 >>>
652
653
654.. _ctypes-arrays:
655
656Arrays
657^^^^^^
658
659Arrays are sequences, containing a fixed number of instances of the same type.
660
661The recommended way to create array types is by multiplying a data type with a
662positive integer::
663
664 TenPointsArrayType = POINT * 10
665
Thomas Woutersed03b412007-08-28 21:37:11 +0000666Here is an example of an somewhat artificial data type, a structure containing 4
Georg Brandl116aa622007-08-15 14:28:22 +0000667POINTs among other stuff::
668
669 >>> from ctypes import *
670 >>> class POINT(Structure):
671 ... _fields_ = ("x", c_int), ("y", c_int)
672 ...
673 >>> class MyStruct(Structure):
674 ... _fields_ = [("a", c_int),
675 ... ("b", c_float),
676 ... ("point_array", POINT * 4)]
677 >>>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000678 >>> print(len(MyStruct().point_array))
Georg Brandl116aa622007-08-15 14:28:22 +0000679 4
680 >>>
681
682Instances are created in the usual way, by calling the class::
683
684 arr = TenPointsArrayType()
685 for pt in arr:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000686 print(pt.x, pt.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000687
688The above code print a series of ``0 0`` lines, because the array contents is
689initialized to zeros.
690
691Initializers of the correct type can also be specified::
692
693 >>> from ctypes import *
694 >>> TenIntegers = c_int * 10
695 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000696 >>> print(ii)
Georg Brandl116aa622007-08-15 14:28:22 +0000697 <c_long_Array_10 object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000698 >>> for i in ii: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000699 ...
700 1 2 3 4 5 6 7 8 9 10
701 >>>
702
703
704.. _ctypes-pointers:
705
706Pointers
707^^^^^^^^
708
Georg Brandl8d8f1972009-06-08 13:27:23 +0000709Pointer instances are created by calling the :func:`pointer` function on a
710:mod:`ctypes` type::
Georg Brandl116aa622007-08-15 14:28:22 +0000711
712 >>> from ctypes import *
713 >>> i = c_int(42)
714 >>> pi = pointer(i)
715 >>>
716
Georg Brandl1d837bc2009-12-29 11:24:00 +0000717Pointer instances have a :attr:`contents` attribute which returns the object to
Georg Brandl116aa622007-08-15 14:28:22 +0000718which the pointer points, the ``i`` object above::
719
720 >>> pi.contents
721 c_long(42)
722 >>>
723
Georg Brandl8d8f1972009-06-08 13:27:23 +0000724Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
Georg Brandl116aa622007-08-15 14:28:22 +0000725new, equivalent object each time you retrieve an attribute::
726
727 >>> pi.contents is i
728 False
729 >>> pi.contents is pi.contents
730 False
731 >>>
732
733Assigning another :class:`c_int` instance to the pointer's contents attribute
734would cause the pointer to point to the memory location where this is stored::
735
736 >>> i = c_int(99)
737 >>> pi.contents = i
738 >>> pi.contents
739 c_long(99)
740 >>>
741
Georg Brandl1d837bc2009-12-29 11:24:00 +0000742.. XXX Document dereferencing pointers, and that it is preferred over the
743 .contents attribute.
Thomas Heller2fadaa22008-06-16 19:56:33 +0000744
Georg Brandl116aa622007-08-15 14:28:22 +0000745Pointer instances can also be indexed with integers::
746
747 >>> pi[0]
748 99
749 >>>
750
751Assigning to an integer index changes the pointed to value::
752
Georg Brandl6911e3c2007-09-04 07:15:32 +0000753 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000754 c_long(99)
755 >>> pi[0] = 22
Georg Brandl6911e3c2007-09-04 07:15:32 +0000756 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000757 c_long(22)
758 >>>
759
760It is also possible to use indexes different from 0, but you must know what
761you're doing, just as in C: You can access or change arbitrary memory locations.
762Generally you only use this feature if you receive a pointer from a C function,
763and you *know* that the pointer actually points to an array instead of a single
764item.
765
Georg Brandl8d8f1972009-06-08 13:27:23 +0000766Behind the scenes, the :func:`pointer` function does more than simply create
767pointer instances, it has to create pointer *types* first. This is done with the
768:func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a
769new type::
Georg Brandl116aa622007-08-15 14:28:22 +0000770
771 >>> PI = POINTER(c_int)
772 >>> PI
773 <class 'ctypes.LP_c_long'>
774 >>> PI(42)
775 Traceback (most recent call last):
776 File "<stdin>", line 1, in ?
777 TypeError: expected c_long instead of int
778 >>> PI(c_int(42))
779 <ctypes.LP_c_long object at 0x...>
780 >>>
781
782Calling the pointer type without an argument creates a ``NULL`` pointer.
783``NULL`` pointers have a ``False`` boolean value::
784
785 >>> null_ptr = POINTER(c_int)()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000786 >>> print(bool(null_ptr))
Georg Brandl116aa622007-08-15 14:28:22 +0000787 False
788 >>>
789
Georg Brandl8d8f1972009-06-08 13:27:23 +0000790:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
Thomas Heller2fadaa22008-06-16 19:56:33 +0000791invalid non-\ ``NULL`` pointers would crash Python)::
Georg Brandl116aa622007-08-15 14:28:22 +0000792
793 >>> null_ptr[0]
794 Traceback (most recent call last):
795 ....
796 ValueError: NULL pointer access
797 >>>
798
799 >>> null_ptr[0] = 1234
800 Traceback (most recent call last):
801 ....
802 ValueError: NULL pointer access
803 >>>
804
805
806.. _ctypes-type-conversions:
807
808Type conversions
809^^^^^^^^^^^^^^^^
810
811Usually, ctypes does strict type checking. This means, if you have
812``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
813a member field in a structure definition, only instances of exactly the same
814type are accepted. There are some exceptions to this rule, where ctypes accepts
815other objects. For example, you can pass compatible array instances instead of
816pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
817
818 >>> class Bar(Structure):
819 ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
820 ...
821 >>> bar = Bar()
822 >>> bar.values = (c_int * 3)(1, 2, 3)
823 >>> bar.count = 3
824 >>> for i in range(bar.count):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000825 ... print(bar.values[i])
Georg Brandl116aa622007-08-15 14:28:22 +0000826 ...
827 1
828 2
829 3
830 >>>
831
Eli Benderskyf81de8d2013-03-08 05:31:54 -0800832In addition, if a function argument is explicitly declared to be a pointer type
833(such as ``POINTER(c_int)``) in :attr:`argtypes`, an object of the pointed
834type (``c_int`` in this case) can be passed to the function. ctypes will apply
835the required :func:`byref` conversion in this case automatically.
836
Georg Brandl116aa622007-08-15 14:28:22 +0000837To set a POINTER type field to ``NULL``, you can assign ``None``::
838
839 >>> bar.values = None
840 >>>
841
Thomas Heller2fadaa22008-06-16 19:56:33 +0000842.. XXX list other conversions...
Georg Brandl116aa622007-08-15 14:28:22 +0000843
Georg Brandl8d8f1972009-06-08 13:27:23 +0000844Sometimes you have instances of incompatible types. In C, you can cast one type
845into another type. :mod:`ctypes` provides a :func:`cast` function which can be
Georg Brandl116aa622007-08-15 14:28:22 +0000846used in the same way. The ``Bar`` structure defined above accepts
847``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
848but not instances of other types::
849
850 >>> bar.values = (c_byte * 4)()
851 Traceback (most recent call last):
852 File "<stdin>", line 1, in ?
853 TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
854 >>>
855
Georg Brandl8d8f1972009-06-08 13:27:23 +0000856For these cases, the :func:`cast` function is handy.
Georg Brandl116aa622007-08-15 14:28:22 +0000857
Georg Brandl8d8f1972009-06-08 13:27:23 +0000858The :func:`cast` function can be used to cast a ctypes instance into a pointer
859to a different ctypes data type. :func:`cast` takes two parameters, a ctypes
860object that is or can be converted to a pointer of some kind, and a ctypes
861pointer type. It returns an instance of the second argument, which references
862the same memory block as the first argument::
Georg Brandl116aa622007-08-15 14:28:22 +0000863
864 >>> a = (c_byte * 4)()
865 >>> cast(a, POINTER(c_int))
866 <ctypes.LP_c_long object at ...>
867 >>>
868
Georg Brandl8d8f1972009-06-08 13:27:23 +0000869So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the
Georg Brandl116aa622007-08-15 14:28:22 +0000870structure::
871
872 >>> bar = Bar()
873 >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
Georg Brandl6911e3c2007-09-04 07:15:32 +0000874 >>> print(bar.values[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000875 0
876 >>>
877
878
879.. _ctypes-incomplete-types:
880
881Incomplete Types
882^^^^^^^^^^^^^^^^
883
884*Incomplete Types* are structures, unions or arrays whose members are not yet
885specified. In C, they are specified by forward declarations, which are defined
886later::
887
888 struct cell; /* forward declaration */
889
Sandro Tosi692dba22011-08-02 16:17:14 +0200890 struct cell {
Georg Brandl116aa622007-08-15 14:28:22 +0000891 char *name;
892 struct cell *next;
Sandro Tosi692dba22011-08-02 16:17:14 +0200893 };
Georg Brandl116aa622007-08-15 14:28:22 +0000894
895The straightforward translation into ctypes code would be this, but it does not
896work::
897
898 >>> class cell(Structure):
899 ... _fields_ = [("name", c_char_p),
900 ... ("next", POINTER(cell))]
901 ...
902 Traceback (most recent call last):
903 File "<stdin>", line 1, in ?
904 File "<stdin>", line 2, in cell
905 NameError: name 'cell' is not defined
906 >>>
907
908because the new ``class cell`` is not available in the class statement itself.
Georg Brandl8d8f1972009-06-08 13:27:23 +0000909In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_`
Georg Brandl116aa622007-08-15 14:28:22 +0000910attribute later, after the class statement::
911
912 >>> from ctypes import *
913 >>> class cell(Structure):
914 ... pass
915 ...
916 >>> cell._fields_ = [("name", c_char_p),
917 ... ("next", POINTER(cell))]
918 >>>
919
920Lets try it. We create two instances of ``cell``, and let them point to each
921other, and finally follow the pointer chain a few times::
922
923 >>> c1 = cell()
924 >>> c1.name = "foo"
925 >>> c2 = cell()
926 >>> c2.name = "bar"
927 >>> c1.next = pointer(c2)
928 >>> c2.next = pointer(c1)
929 >>> p = c1
930 >>> for i in range(8):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000931 ... print(p.name, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000932 ... p = p.next[0]
933 ...
934 foo bar foo bar foo bar foo bar
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000935 >>>
Georg Brandl116aa622007-08-15 14:28:22 +0000936
937
938.. _ctypes-callback-functions:
939
940Callback functions
941^^^^^^^^^^^^^^^^^^
942
Georg Brandl8d8f1972009-06-08 13:27:23 +0000943:mod:`ctypes` allows to create C callable function pointers from Python callables.
Georg Brandl116aa622007-08-15 14:28:22 +0000944These are sometimes called *callback functions*.
945
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200946First, you must create a class for the callback function. The class knows the
Georg Brandl116aa622007-08-15 14:28:22 +0000947calling convention, the return type, and the number and types of arguments this
948function will receive.
949
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200950The :func:`CFUNCTYPE` factory function creates types for callback functions
951using the ``cdecl`` calling convention. On Windows, the :func:`WINFUNCTYPE`
952factory function creates types for callback functions using the ``stdcall``
953calling convention.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955Both of these factory functions are called with the result type as first
956argument, and the callback functions expected argument types as the remaining
957arguments.
958
Georg Brandl8d8f1972009-06-08 13:27:23 +0000959I will present an example here which uses the standard C library's
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200960:c:func:`qsort` function, that is used to sort items with the help of a callback
Georg Brandl60203b42010-10-06 10:11:56 +0000961function. :c:func:`qsort` will be used to sort an array of integers::
Georg Brandl116aa622007-08-15 14:28:22 +0000962
963 >>> IntArray5 = c_int * 5
964 >>> ia = IntArray5(5, 1, 7, 33, 99)
965 >>> qsort = libc.qsort
966 >>> qsort.restype = None
967 >>>
968
969:func:`qsort` must be called with a pointer to the data to sort, the number of
970items in the data array, the size of one item, and a pointer to the comparison
971function, the callback. The callback will then be called with two pointers to
972items, and it must return a negative integer if the first item is smaller than
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200973the second, a zero if they are equal, and a positive integer otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +0000974
975So our callback function receives pointers to integers, and must return an
976integer. First we create the ``type`` for the callback function::
977
978 >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
979 >>>
980
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200981To get started, here is a simple callback that shows the values it gets
982passed::
Georg Brandl116aa622007-08-15 14:28:22 +0000983
984 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000985 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000986 ... return 0
987 ...
988 >>> cmp_func = CMPFUNC(py_cmp_func)
989 >>>
990
Eli Bendersky2a1e74a2012-03-16 09:17:43 +0200991The result::
Georg Brandl116aa622007-08-15 14:28:22 +0000992
993 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
994 py_cmp_func 5 1
995 py_cmp_func 33 99
996 py_cmp_func 7 33
997 py_cmp_func 5 7
998 py_cmp_func 1 7
999 >>>
1000
Eli Bendersky2a1e74a2012-03-16 09:17:43 +02001001Now we can actually compare the two items and return a useful result::
Georg Brandl116aa622007-08-15 14:28:22 +00001002
1003 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001004 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +00001005 ... return a[0] - b[0]
1006 ...
1007 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001008 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1009 py_cmp_func 5 1
1010 py_cmp_func 33 99
1011 py_cmp_func 7 33
1012 py_cmp_func 1 7
1013 py_cmp_func 5 7
1014 >>>
1015
Georg Brandl116aa622007-08-15 14:28:22 +00001016As we can easily check, our array is sorted now::
1017
Georg Brandl6911e3c2007-09-04 07:15:32 +00001018 >>> for i in ia: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +00001019 ...
1020 1 5 7 33 99
1021 >>>
1022
1023**Important note for callback functions:**
1024
Eli Bendersky2a1e74a2012-03-16 09:17:43 +02001025Make sure you keep references to :func:`CFUNCTYPE` objects as long as they are
1026used from C code. :mod:`ctypes` doesn't, and if you don't, they may be garbage
1027collected, crashing your program when a callback is made.
Georg Brandl116aa622007-08-15 14:28:22 +00001028
1029
1030.. _ctypes-accessing-values-exported-from-dlls:
1031
1032Accessing values exported from dlls
1033^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1034
Thomas Heller2fadaa22008-06-16 19:56:33 +00001035Some shared libraries not only export functions, they also export variables. An
Georg Brandl60203b42010-10-06 10:11:56 +00001036example in the Python library itself is the :c:data:`Py_OptimizeFlag`, an integer
Georg Brandl8d8f1972009-06-08 13:27:23 +00001037set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
Georg Brandl116aa622007-08-15 14:28:22 +00001038startup.
1039
Georg Brandl8d8f1972009-06-08 13:27:23 +00001040:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of
Georg Brandl116aa622007-08-15 14:28:22 +00001041the type. *pythonapi* is a predefined symbol giving access to the Python C
1042api::
1043
1044 >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
Georg Brandl6911e3c2007-09-04 07:15:32 +00001045 >>> print(opt_flag)
Georg Brandl116aa622007-08-15 14:28:22 +00001046 c_long(0)
1047 >>>
1048
1049If the interpreter would have been started with :option:`-O`, the sample would
1050have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1051specified.
1052
1053An extended example which also demonstrates the use of pointers accesses the
Georg Brandl60203b42010-10-06 10:11:56 +00001054:c:data:`PyImport_FrozenModules` pointer exported by Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001055
Georg Brandl8d8f1972009-06-08 13:27:23 +00001056Quoting the docs for that value:
1057
Georg Brandl60203b42010-10-06 10:11:56 +00001058 This pointer is initialized to point to an array of :c:type:`struct _frozen`
Georg Brandl8d8f1972009-06-08 13:27:23 +00001059 records, terminated by one whose members are all *NULL* or zero. When a frozen
1060 module is imported, it is searched in this table. Third-party code could play
1061 tricks with this to provide a dynamically created collection of frozen modules.
Georg Brandl116aa622007-08-15 14:28:22 +00001062
1063So manipulating this pointer could even prove useful. To restrict the example
Georg Brandl8d8f1972009-06-08 13:27:23 +00001064size, we show only how this table can be read with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001065
1066 >>> from ctypes import *
1067 >>>
1068 >>> class struct_frozen(Structure):
1069 ... _fields_ = [("name", c_char_p),
1070 ... ("code", POINTER(c_ubyte)),
1071 ... ("size", c_int)]
1072 ...
1073 >>>
1074
Georg Brandl60203b42010-10-06 10:11:56 +00001075We have defined the :c:type:`struct _frozen` data type, so we can get the pointer
Georg Brandl8d8f1972009-06-08 13:27:23 +00001076to the table::
Georg Brandl116aa622007-08-15 14:28:22 +00001077
1078 >>> FrozenTable = POINTER(struct_frozen)
1079 >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1080 >>>
1081
1082Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1083can iterate over it, but we just have to make sure that our loop terminates,
1084because pointers have no size. Sooner or later it would probably crash with an
1085access violation or whatever, so it's better to break out of the loop when we
1086hit the NULL entry::
1087
1088 >>> for item in table:
Georg Brandl6911e3c2007-09-04 07:15:32 +00001089 ... print(item.name, item.size)
Georg Brandl116aa622007-08-15 14:28:22 +00001090 ... if item.name is None:
1091 ... break
1092 ...
1093 __hello__ 104
1094 __phello__ -104
1095 __phello__.spam 104
1096 None 0
1097 >>>
1098
1099The fact that standard Python has a frozen module and a frozen package
Thomas Woutersed03b412007-08-28 21:37:11 +00001100(indicated by the negative size member) is not well known, it is only used for
Georg Brandl116aa622007-08-15 14:28:22 +00001101testing. Try it out with ``import __hello__`` for example.
1102
1103
1104.. _ctypes-surprises:
1105
1106Surprises
1107^^^^^^^^^
1108
R David Murraya2959ce2012-10-31 10:50:27 -04001109There are some edges in :mod:`ctypes` where you might expect something other
1110than what actually happens.
Georg Brandl116aa622007-08-15 14:28:22 +00001111
1112Consider the following example::
1113
1114 >>> from ctypes import *
1115 >>> class POINT(Structure):
1116 ... _fields_ = ("x", c_int), ("y", c_int)
1117 ...
1118 >>> class RECT(Structure):
1119 ... _fields_ = ("a", POINT), ("b", POINT)
1120 ...
1121 >>> p1 = POINT(1, 2)
1122 >>> p2 = POINT(3, 4)
1123 >>> rc = RECT(p1, p2)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001124 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001125 1 2 3 4
1126 >>> # now swap the two points
1127 >>> rc.a, rc.b = rc.b, rc.a
Georg Brandl6911e3c2007-09-04 07:15:32 +00001128 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001129 3 4 3 4
1130 >>>
1131
1132Hm. We certainly expected the last statement to print ``3 4 1 2``. What
Thomas Woutersed03b412007-08-28 21:37:11 +00001133happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
Georg Brandl116aa622007-08-15 14:28:22 +00001134
1135 >>> temp0, temp1 = rc.b, rc.a
1136 >>> rc.a = temp0
1137 >>> rc.b = temp1
1138 >>>
1139
1140Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1141the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1142contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1143contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1144the expected effect.
1145
Thomas Woutersed03b412007-08-28 21:37:11 +00001146Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1147doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
Georg Brandl116aa622007-08-15 14:28:22 +00001148the root-object's underlying buffer.
1149
1150Another example that may behave different from what one would expect is this::
1151
1152 >>> s = c_char_p()
1153 >>> s.value = "abc def ghi"
1154 >>> s.value
1155 'abc def ghi'
1156 >>> s.value is s.value
1157 False
1158 >>>
1159
1160Why is it printing ``False``? ctypes instances are objects containing a memory
Georg Brandl9afde1c2007-11-01 20:32:30 +00001161block plus some :term:`descriptor`\s accessing the contents of the memory.
1162Storing a Python object in the memory block does not store the object itself,
1163instead the ``contents`` of the object is stored. Accessing the contents again
1164constructs a new Python object each time!
Georg Brandl116aa622007-08-15 14:28:22 +00001165
1166
1167.. _ctypes-variable-sized-data-types:
1168
1169Variable-sized data types
1170^^^^^^^^^^^^^^^^^^^^^^^^^
1171
Georg Brandl8d8f1972009-06-08 13:27:23 +00001172:mod:`ctypes` provides some support for variable-sized arrays and structures.
Georg Brandl116aa622007-08-15 14:28:22 +00001173
Georg Brandl8d8f1972009-06-08 13:27:23 +00001174The :func:`resize` function can be used to resize the memory buffer of an
1175existing ctypes object. The function takes the object as first argument, and
1176the requested size in bytes as the second argument. The memory block cannot be
1177made smaller than the natural memory block specified by the objects type, a
1178:exc:`ValueError` is raised if this is tried::
Georg Brandl116aa622007-08-15 14:28:22 +00001179
1180 >>> short_array = (c_short * 4)()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001181 >>> print(sizeof(short_array))
Georg Brandl116aa622007-08-15 14:28:22 +00001182 8
1183 >>> resize(short_array, 4)
1184 Traceback (most recent call last):
1185 ...
1186 ValueError: minimum size is 8
1187 >>> resize(short_array, 32)
1188 >>> sizeof(short_array)
1189 32
1190 >>> sizeof(type(short_array))
1191 8
1192 >>>
1193
1194This is nice and fine, but how would one access the additional elements
1195contained in this array? Since the type still only knows about 4 elements, we
1196get errors accessing other elements::
1197
1198 >>> short_array[:]
1199 [0, 0, 0, 0]
1200 >>> short_array[7]
1201 Traceback (most recent call last):
1202 ...
1203 IndexError: invalid index
1204 >>>
1205
Georg Brandl8d8f1972009-06-08 13:27:23 +00001206Another way to use variable-sized data types with :mod:`ctypes` is to use the
Georg Brandl116aa622007-08-15 14:28:22 +00001207dynamic nature of Python, and (re-)define the data type after the required size
1208is already known, on a case by case basis.
1209
1210
Georg Brandl116aa622007-08-15 14:28:22 +00001211.. _ctypes-ctypes-reference:
1212
1213ctypes reference
1214----------------
1215
1216
1217.. _ctypes-finding-shared-libraries:
1218
1219Finding shared libraries
1220^^^^^^^^^^^^^^^^^^^^^^^^
1221
1222When programming in a compiled language, shared libraries are accessed when
1223compiling/linking a program, and when the program is run.
1224
Georg Brandl8d8f1972009-06-08 13:27:23 +00001225The purpose of the :func:`find_library` function is to locate a library in a way
Georg Brandl116aa622007-08-15 14:28:22 +00001226similar to what the compiler does (on platforms with several versions of a
1227shared library the most recent should be loaded), while the ctypes library
1228loaders act like when a program is run, and call the runtime loader directly.
1229
Georg Brandl8d8f1972009-06-08 13:27:23 +00001230The :mod:`ctypes.util` module provides a function which can help to determine
1231the library to load.
Georg Brandl116aa622007-08-15 14:28:22 +00001232
1233
1234.. data:: find_library(name)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001235 :module: ctypes.util
Georg Brandl116aa622007-08-15 14:28:22 +00001236 :noindex:
1237
1238 Try to find a library and return a pathname. *name* is the library name without
1239 any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1240 is the form used for the posix linker option :option:`-l`). If no library can
1241 be found, returns ``None``.
1242
Thomas Woutersed03b412007-08-28 21:37:11 +00001243The exact functionality is system dependent.
Georg Brandl116aa622007-08-15 14:28:22 +00001244
Georg Brandl1d837bc2009-12-29 11:24:00 +00001245On Linux, :func:`find_library` tries to run external programs
1246(``/sbin/ldconfig``, ``gcc``, and ``objdump``) to find the library file. It
1247returns the filename of the library file. Here are some examples::
Georg Brandl116aa622007-08-15 14:28:22 +00001248
1249 >>> from ctypes.util import find_library
1250 >>> find_library("m")
1251 'libm.so.6'
1252 >>> find_library("c")
1253 'libc.so.6'
1254 >>> find_library("bz2")
1255 'libbz2.so.1.0'
1256 >>>
1257
Georg Brandl8d8f1972009-06-08 13:27:23 +00001258On OS X, :func:`find_library` tries several predefined naming schemes and paths
1259to locate the library, and returns a full pathname if successful::
Georg Brandl116aa622007-08-15 14:28:22 +00001260
1261 >>> from ctypes.util import find_library
1262 >>> find_library("c")
1263 '/usr/lib/libc.dylib'
1264 >>> find_library("m")
1265 '/usr/lib/libm.dylib'
1266 >>> find_library("bz2")
1267 '/usr/lib/libbz2.dylib'
1268 >>> find_library("AGL")
1269 '/System/Library/Frameworks/AGL.framework/AGL'
1270 >>>
1271
Georg Brandl8d8f1972009-06-08 13:27:23 +00001272On Windows, :func:`find_library` searches along the system search path, and
1273returns the full pathname, but since there is no predefined naming scheme a call
1274like ``find_library("c")`` will fail and return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001275
Georg Brandl8d8f1972009-06-08 13:27:23 +00001276If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
Georg Brandl116aa622007-08-15 14:28:22 +00001277the shared library name at development type, and hardcode that into the wrapper
Georg Brandl8d8f1972009-06-08 13:27:23 +00001278module instead of using :func:`find_library` to locate the library at runtime.
Georg Brandl116aa622007-08-15 14:28:22 +00001279
1280
1281.. _ctypes-loading-shared-libraries:
1282
1283Loading shared libraries
1284^^^^^^^^^^^^^^^^^^^^^^^^
1285
1286There are several ways to loaded shared libraries into the Python process. One
1287way is to instantiate one of the following classes:
1288
1289
Thomas Hellerb795f5282008-06-10 15:26:58 +00001290.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001291
1292 Instances of this class represent loaded shared libraries. Functions in these
1293 libraries use the standard C calling convention, and are assumed to return
Georg Brandl60203b42010-10-06 10:11:56 +00001294 :c:type:`int`.
Georg Brandl116aa622007-08-15 14:28:22 +00001295
1296
Thomas Hellerb795f5282008-06-10 15:26:58 +00001297.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001298
1299 Windows only: Instances of this class represent loaded shared libraries,
1300 functions in these libraries use the ``stdcall`` calling convention, and are
1301 assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1302 values contain information specifying whether the function call failed or
1303 succeeded, together with additional error code. If the return value signals a
Antoine Pitrou442ee032011-10-12 18:53:23 +02001304 failure, an :class:`OSError` is automatically raised.
1305
1306 .. versionchanged:: 3.3
1307 :exc:`WindowsError` used to be raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001308
1309
Thomas Hellerb795f5282008-06-10 15:26:58 +00001310.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001311
1312 Windows only: Instances of this class represent loaded shared libraries,
1313 functions in these libraries use the ``stdcall`` calling convention, and are
Georg Brandl60203b42010-10-06 10:11:56 +00001314 assumed to return :c:type:`int` by default.
Georg Brandl116aa622007-08-15 14:28:22 +00001315
1316 On Windows CE only the standard calling convention is used, for convenience the
1317 :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1318 platform.
1319
Georg Brandl9afde1c2007-11-01 20:32:30 +00001320The Python :term:`global interpreter lock` is released before calling any
1321function exported by these libraries, and reacquired afterwards.
Georg Brandl116aa622007-08-15 14:28:22 +00001322
1323
1324.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1325
1326 Instances of this class behave like :class:`CDLL` instances, except that the
1327 Python GIL is *not* released during the function call, and after the function
1328 execution the Python error flag is checked. If the error flag is set, a Python
1329 exception is raised.
1330
1331 Thus, this is only useful to call Python C api functions directly.
1332
1333All these classes can be instantiated by calling them with at least one
1334argument, the pathname of the shared library. If you have an existing handle to
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001335an already loaded shared library, it can be passed as the ``handle`` named
Georg Brandl1d837bc2009-12-29 11:24:00 +00001336parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary``
Georg Brandl116aa622007-08-15 14:28:22 +00001337function is used to load the library into the process, and to get a handle to
1338it.
1339
1340The *mode* parameter can be used to specify how the library is loaded. For
Georg Brandl1d837bc2009-12-29 11:24:00 +00001341details, consult the :manpage:`dlopen(3)` manpage, on Windows, *mode* is
1342ignored.
Georg Brandl116aa622007-08-15 14:28:22 +00001343
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001344The *use_errno* parameter, when set to True, enables a ctypes mechanism that
1345allows to access the system :data:`errno` error number in a safe way.
1346:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1347variable; if you call foreign functions created with ``use_errno=True`` then the
1348:data:`errno` value before the function call is swapped with the ctypes private
1349copy, the same happens immediately after the function call.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001350
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001351The function :func:`ctypes.get_errno` returns the value of the ctypes private
1352copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1353to a new value and returns the former value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001354
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001355The *use_last_error* parameter, when set to True, enables the same mechanism for
1356the Windows error code which is managed by the :func:`GetLastError` and
1357:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1358:func:`ctypes.set_last_error` are used to request and change the ctypes private
1359copy of the windows error code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001360
Georg Brandl116aa622007-08-15 14:28:22 +00001361.. data:: RTLD_GLOBAL
1362 :noindex:
1363
1364 Flag to use as *mode* parameter. On platforms where this flag is not available,
1365 it is defined as the integer zero.
1366
1367
1368.. data:: RTLD_LOCAL
1369 :noindex:
1370
1371 Flag to use as *mode* parameter. On platforms where this is not available, it
1372 is the same as *RTLD_GLOBAL*.
1373
1374
1375.. data:: DEFAULT_MODE
1376 :noindex:
1377
1378 The default mode which is used to load shared libraries. On OSX 10.3, this is
1379 *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1380
1381Instances of these classes have no public methods, however :meth:`__getattr__`
Thomas Woutersed03b412007-08-28 21:37:11 +00001382and :meth:`__getitem__` have special behavior: functions exported by the shared
Georg Brandl116aa622007-08-15 14:28:22 +00001383library can be accessed as attributes of by index. Please note that both
1384:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1385repeatedly returns the same object each time.
1386
1387The following public attributes are available, their name starts with an
1388underscore to not clash with exported function names:
1389
1390
1391.. attribute:: PyDLL._handle
1392
1393 The system handle used to access the library.
1394
1395
1396.. attribute:: PyDLL._name
1397
Thomas Woutersed03b412007-08-28 21:37:11 +00001398 The name of the library passed in the constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001399
1400Shared libraries can also be loaded by using one of the prefabricated objects,
1401which are instances of the :class:`LibraryLoader` class, either by calling the
1402:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1403loader instance.
1404
1405
1406.. class:: LibraryLoader(dlltype)
1407
Georg Brandl1d837bc2009-12-29 11:24:00 +00001408 Class which loads shared libraries. *dlltype* should be one of the
Georg Brandl116aa622007-08-15 14:28:22 +00001409 :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1410
Thomas Woutersed03b412007-08-28 21:37:11 +00001411 :meth:`__getattr__` has special behavior: It allows to load a shared library by
Georg Brandl116aa622007-08-15 14:28:22 +00001412 accessing it as attribute of a library loader instance. The result is cached,
1413 so repeated attribute accesses return the same library each time.
1414
Benjamin Petersone41251e2008-04-25 01:59:09 +00001415 .. method:: LoadLibrary(name)
Georg Brandl116aa622007-08-15 14:28:22 +00001416
Benjamin Petersone41251e2008-04-25 01:59:09 +00001417 Load a shared library into the process and return it. This method always
1418 returns a new instance of the library.
Georg Brandl116aa622007-08-15 14:28:22 +00001419
Georg Brandl116aa622007-08-15 14:28:22 +00001420
Georg Brandl8d8f1972009-06-08 13:27:23 +00001421These prefabricated library loaders are available:
Georg Brandl116aa622007-08-15 14:28:22 +00001422
1423.. data:: cdll
1424 :noindex:
1425
1426 Creates :class:`CDLL` instances.
1427
1428
1429.. data:: windll
1430 :noindex:
1431
1432 Windows only: Creates :class:`WinDLL` instances.
1433
1434
1435.. data:: oledll
1436 :noindex:
1437
1438 Windows only: Creates :class:`OleDLL` instances.
1439
1440
1441.. data:: pydll
1442 :noindex:
1443
1444 Creates :class:`PyDLL` instances.
1445
Georg Brandl8d8f1972009-06-08 13:27:23 +00001446
Georg Brandl116aa622007-08-15 14:28:22 +00001447For accessing the C Python api directly, a ready-to-use Python shared library
1448object is available:
1449
Georg Brandl116aa622007-08-15 14:28:22 +00001450.. data:: pythonapi
1451 :noindex:
1452
Georg Brandl1d837bc2009-12-29 11:24:00 +00001453 An instance of :class:`PyDLL` that exposes Python C API functions as
1454 attributes. Note that all these functions are assumed to return C
Georg Brandl60203b42010-10-06 10:11:56 +00001455 :c:type:`int`, which is of course not always the truth, so you have to assign
Georg Brandl1d837bc2009-12-29 11:24:00 +00001456 the correct :attr:`restype` attribute to use these functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001457
1458
1459.. _ctypes-foreign-functions:
1460
1461Foreign functions
1462^^^^^^^^^^^^^^^^^
1463
1464As explained in the previous section, foreign functions can be accessed as
1465attributes of loaded shared libraries. The function objects created in this way
1466by default accept any number of arguments, accept any ctypes data instances as
1467arguments, and return the default result type specified by the library loader.
1468They are instances of a private class:
1469
1470
1471.. class:: _FuncPtr
1472
1473 Base class for C callable foreign functions.
1474
Benjamin Petersone41251e2008-04-25 01:59:09 +00001475 Instances of foreign functions are also C compatible data types; they
1476 represent C function pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001477
Benjamin Petersone41251e2008-04-25 01:59:09 +00001478 This behavior can be customized by assigning to special attributes of the
1479 foreign function object.
Georg Brandl116aa622007-08-15 14:28:22 +00001480
Benjamin Petersone41251e2008-04-25 01:59:09 +00001481 .. attribute:: restype
Georg Brandl116aa622007-08-15 14:28:22 +00001482
Benjamin Petersone41251e2008-04-25 01:59:09 +00001483 Assign a ctypes type to specify the result type of the foreign function.
Georg Brandl60203b42010-10-06 10:11:56 +00001484 Use ``None`` for :c:type:`void`, a function not returning anything.
Georg Brandl116aa622007-08-15 14:28:22 +00001485
Benjamin Petersone41251e2008-04-25 01:59:09 +00001486 It is possible to assign a callable Python object that is not a ctypes
Georg Brandl60203b42010-10-06 10:11:56 +00001487 type, in this case the function is assumed to return a C :c:type:`int`, and
Georg Brandl1d837bc2009-12-29 11:24:00 +00001488 the callable will be called with this integer, allowing to do further
Benjamin Petersone41251e2008-04-25 01:59:09 +00001489 processing or error checking. Using this is deprecated, for more flexible
1490 post processing or error checking use a ctypes data type as
1491 :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001492
Benjamin Petersone41251e2008-04-25 01:59:09 +00001493 .. attribute:: argtypes
Georg Brandl116aa622007-08-15 14:28:22 +00001494
Benjamin Petersone41251e2008-04-25 01:59:09 +00001495 Assign a tuple of ctypes types to specify the argument types that the
1496 function accepts. Functions using the ``stdcall`` calling convention can
1497 only be called with the same number of arguments as the length of this
1498 tuple; functions using the C calling convention accept additional,
1499 unspecified arguments as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001500
Benjamin Petersone41251e2008-04-25 01:59:09 +00001501 When a foreign function is called, each actual argument is passed to the
1502 :meth:`from_param` class method of the items in the :attr:`argtypes`
1503 tuple, this method allows to adapt the actual argument to an object that
1504 the foreign function accepts. For example, a :class:`c_char_p` item in
Georg Brandl8d8f1972009-06-08 13:27:23 +00001505 the :attr:`argtypes` tuple will convert a string passed as argument into
1506 a bytes object using ctypes conversion rules.
Georg Brandl116aa622007-08-15 14:28:22 +00001507
Benjamin Petersone41251e2008-04-25 01:59:09 +00001508 New: It is now possible to put items in argtypes which are not ctypes
1509 types, but each item must have a :meth:`from_param` method which returns a
1510 value usable as argument (integer, string, ctypes instance). This allows
1511 to define adapters that can adapt custom objects as function parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001512
Benjamin Petersone41251e2008-04-25 01:59:09 +00001513 .. attribute:: errcheck
Georg Brandl116aa622007-08-15 14:28:22 +00001514
Benjamin Petersone41251e2008-04-25 01:59:09 +00001515 Assign a Python function or another callable to this attribute. The
1516 callable will be called with three or more arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001517
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001518 .. function:: callable(result, func, arguments)
1519 :noindex:
Georg Brandl8d8f1972009-06-08 13:27:23 +00001520 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001521
Georg Brandl1d837bc2009-12-29 11:24:00 +00001522 *result* is what the foreign function returns, as specified by the
1523 :attr:`restype` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001524
Georg Brandl1d837bc2009-12-29 11:24:00 +00001525 *func* is the foreign function object itself, this allows to reuse the
1526 same callable object to check or post process the results of several
1527 functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001528
Georg Brandl1d837bc2009-12-29 11:24:00 +00001529 *arguments* is a tuple containing the parameters originally passed to
1530 the function call, this allows to specialize the behavior on the
1531 arguments used.
Georg Brandl116aa622007-08-15 14:28:22 +00001532
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001533 The object that this function returns will be returned from the
1534 foreign function call, but it can also check the result value
1535 and raise an exception if the foreign function call failed.
Georg Brandl116aa622007-08-15 14:28:22 +00001536
1537
Georg Brandl8d8f1972009-06-08 13:27:23 +00001538.. exception:: ArgumentError
Georg Brandl116aa622007-08-15 14:28:22 +00001539
1540 This exception is raised when a foreign function call cannot convert one of the
1541 passed arguments.
1542
1543
1544.. _ctypes-function-prototypes:
1545
1546Function prototypes
1547^^^^^^^^^^^^^^^^^^^
1548
1549Foreign functions can also be created by instantiating function prototypes.
1550Function prototypes are similar to function prototypes in C; they describe a
1551function (return type, argument types, calling convention) without defining an
1552implementation. The factory functions must be called with the desired result
1553type and the argument types of the function.
1554
1555
Thomas Hellerb795f5282008-06-10 15:26:58 +00001556.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001557
1558 The returned function prototype creates functions that use the standard C
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001559 calling convention. The function will release the GIL during the call. If
1560 *use_errno* is set to True, the ctypes private copy of the system
Georg Brandla6053b42009-09-01 08:11:14 +00001561 :data:`errno` variable is exchanged with the real :data:`errno` value before
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001562 and after the call; *use_last_error* does the same for the Windows error
1563 code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001564
Georg Brandl116aa622007-08-15 14:28:22 +00001565
Thomas Hellerb795f5282008-06-10 15:26:58 +00001566.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001567
1568 Windows only: The returned function prototype creates functions that use the
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001569 ``stdcall`` calling convention, except on Windows CE where
1570 :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
1571 release the GIL during the call. *use_errno* and *use_last_error* have the
1572 same meaning as above.
Georg Brandl116aa622007-08-15 14:28:22 +00001573
1574
1575.. function:: PYFUNCTYPE(restype, *argtypes)
1576
1577 The returned function prototype creates functions that use the Python calling
1578 convention. The function will *not* release the GIL during the call.
1579
Thomas Heller2fadaa22008-06-16 19:56:33 +00001580Function prototypes created by these factory functions can be instantiated in
1581different ways, depending on the type and number of the parameters in the call:
Georg Brandl116aa622007-08-15 14:28:22 +00001582
1583
Thomas Heller2fadaa22008-06-16 19:56:33 +00001584 .. function:: prototype(address)
1585 :noindex:
1586 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001587
Thomas Heller2fadaa22008-06-16 19:56:33 +00001588 Returns a foreign function at the specified address which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00001589
1590
Thomas Heller2fadaa22008-06-16 19:56:33 +00001591 .. function:: prototype(callable)
1592 :noindex:
1593 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001594
Georg Brandl8d8f1972009-06-08 13:27:23 +00001595 Create a C callable function (a callback function) from a Python *callable*.
Georg Brandl116aa622007-08-15 14:28:22 +00001596
1597
Thomas Heller2fadaa22008-06-16 19:56:33 +00001598 .. function:: prototype(func_spec[, paramflags])
1599 :noindex:
1600 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001601
Georg Brandl1d837bc2009-12-29 11:24:00 +00001602 Returns a foreign function exported by a shared library. *func_spec* must
1603 be a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of
1604 the exported function as string, or the ordinal of the exported function
1605 as small integer. The second item is the shared library instance.
Georg Brandl116aa622007-08-15 14:28:22 +00001606
1607
Thomas Heller2fadaa22008-06-16 19:56:33 +00001608 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1609 :noindex:
1610 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001611
Georg Brandl8d8f1972009-06-08 13:27:23 +00001612 Returns a foreign function that will call a COM method. *vtbl_index* is
1613 the index into the virtual function table, a small non-negative
1614 integer. *name* is name of the COM method. *iid* is an optional pointer to
1615 the interface identifier which is used in extended error reporting.
Georg Brandl116aa622007-08-15 14:28:22 +00001616
Georg Brandl8d8f1972009-06-08 13:27:23 +00001617 COM methods use a special calling convention: They require a pointer to
1618 the COM interface as first argument, in addition to those parameters that
1619 are specified in the :attr:`argtypes` tuple.
Georg Brandl116aa622007-08-15 14:28:22 +00001620
Thomas Heller2fadaa22008-06-16 19:56:33 +00001621 The optional *paramflags* parameter creates foreign function wrappers with much
1622 more functionality than the features described above.
Georg Brandl116aa622007-08-15 14:28:22 +00001623
Thomas Heller2fadaa22008-06-16 19:56:33 +00001624 *paramflags* must be a tuple of the same length as :attr:`argtypes`.
Georg Brandl116aa622007-08-15 14:28:22 +00001625
Thomas Heller2fadaa22008-06-16 19:56:33 +00001626 Each item in this tuple contains further information about a parameter, it must
1627 be a tuple containing one, two, or three items.
Georg Brandl116aa622007-08-15 14:28:22 +00001628
Thomas Heller2fadaa22008-06-16 19:56:33 +00001629 The first item is an integer containing a combination of direction
1630 flags for the parameter:
Georg Brandl116aa622007-08-15 14:28:22 +00001631
Thomas Heller2fadaa22008-06-16 19:56:33 +00001632 1
1633 Specifies an input parameter to the function.
Georg Brandl116aa622007-08-15 14:28:22 +00001634
Thomas Heller2fadaa22008-06-16 19:56:33 +00001635 2
1636 Output parameter. The foreign function fills in a value.
Georg Brandl116aa622007-08-15 14:28:22 +00001637
Thomas Heller2fadaa22008-06-16 19:56:33 +00001638 4
1639 Input parameter which defaults to the integer zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001640
Thomas Heller2fadaa22008-06-16 19:56:33 +00001641 The optional second item is the parameter name as string. If this is specified,
1642 the foreign function can be called with named parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001643
Thomas Heller2fadaa22008-06-16 19:56:33 +00001644 The optional third item is the default value for this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001645
1646This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
1647that it supports default parameters and named arguments. The C declaration from
1648the windows header file is this::
1649
1650 WINUSERAPI int WINAPI
1651 MessageBoxA(
1652 HWND hWnd ,
1653 LPCSTR lpText,
1654 LPCSTR lpCaption,
1655 UINT uType);
1656
Georg Brandl8d8f1972009-06-08 13:27:23 +00001657Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001658
Thomas Heller2fadaa22008-06-16 19:56:33 +00001659 >>> from ctypes import c_int, WINFUNCTYPE, windll
1660 >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1661 >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
1662 >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1663 >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1664 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001665
1666The MessageBox foreign function can now be called in these ways::
1667
1668 >>> MessageBox()
1669 >>> MessageBox(text="Spam, spam, spam")
1670 >>> MessageBox(flags=2, text="foo bar")
1671 >>>
1672
1673A second example demonstrates output parameters. The win32 ``GetWindowRect``
1674function retrieves the dimensions of a specified window by copying them into
1675``RECT`` structure that the caller has to supply. Here is the C declaration::
1676
1677 WINUSERAPI BOOL WINAPI
1678 GetWindowRect(
1679 HWND hWnd,
1680 LPRECT lpRect);
1681
Georg Brandl8d8f1972009-06-08 13:27:23 +00001682Here is the wrapping with :mod:`ctypes`::
Georg Brandl116aa622007-08-15 14:28:22 +00001683
Thomas Heller2fadaa22008-06-16 19:56:33 +00001684 >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1685 >>> from ctypes.wintypes import BOOL, HWND, RECT
1686 >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1687 >>> paramflags = (1, "hwnd"), (2, "lprect")
1688 >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1689 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001690
1691Functions with output parameters will automatically return the output parameter
1692value if there is a single one, or a tuple containing the output parameter
1693values when there are more than one, so the GetWindowRect function now returns a
1694RECT instance, when called.
1695
1696Output parameters can be combined with the :attr:`errcheck` protocol to do
1697further output processing and error checking. The win32 ``GetWindowRect`` api
1698function returns a ``BOOL`` to signal success or failure, so this function could
1699do the error checking, and raises an exception when the api call failed::
1700
1701 >>> def errcheck(result, func, args):
1702 ... if not result:
1703 ... raise WinError()
1704 ... return args
Thomas Heller2fadaa22008-06-16 19:56:33 +00001705 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001706 >>> GetWindowRect.errcheck = errcheck
1707 >>>
1708
1709If the :attr:`errcheck` function returns the argument tuple it receives
Georg Brandl8d8f1972009-06-08 13:27:23 +00001710unchanged, :mod:`ctypes` continues the normal processing it does on the output
Georg Brandl116aa622007-08-15 14:28:22 +00001711parameters. If you want to return a tuple of window coordinates instead of a
1712``RECT`` instance, you can retrieve the fields in the function and return them
1713instead, the normal processing will no longer take place::
1714
1715 >>> def errcheck(result, func, args):
1716 ... if not result:
1717 ... raise WinError()
1718 ... rc = args[1]
1719 ... return rc.left, rc.top, rc.bottom, rc.right
Thomas Heller2fadaa22008-06-16 19:56:33 +00001720 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001721 >>> GetWindowRect.errcheck = errcheck
1722 >>>
1723
1724
1725.. _ctypes-utility-functions:
1726
1727Utility functions
1728^^^^^^^^^^^^^^^^^
1729
Georg Brandl116aa622007-08-15 14:28:22 +00001730.. function:: addressof(obj)
1731
Georg Brandl8d8f1972009-06-08 13:27:23 +00001732 Returns the address of the memory buffer as integer. *obj* must be an
Georg Brandl116aa622007-08-15 14:28:22 +00001733 instance of a ctypes type.
1734
1735
1736.. function:: alignment(obj_or_type)
1737
Georg Brandl8d8f1972009-06-08 13:27:23 +00001738 Returns the alignment requirements of a ctypes type. *obj_or_type* must be a
Georg Brandl116aa622007-08-15 14:28:22 +00001739 ctypes type or instance.
1740
1741
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001742.. function:: byref(obj[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +00001743
Georg Brandl1d837bc2009-12-29 11:24:00 +00001744 Returns a light-weight pointer to *obj*, which must be an instance of a
1745 ctypes type. *offset* defaults to zero, and must be an integer that will be
1746 added to the internal pointer value.
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001747
1748 ``byref(obj, offset)`` corresponds to this C code::
1749
1750 (((char *)&obj) + offset)
1751
Georg Brandl1d837bc2009-12-29 11:24:00 +00001752 The returned object can only be used as a foreign function call parameter.
1753 It behaves similar to ``pointer(obj)``, but the construction is a lot faster.
Georg Brandl116aa622007-08-15 14:28:22 +00001754
1755
1756.. function:: cast(obj, type)
1757
Georg Brandl8d8f1972009-06-08 13:27:23 +00001758 This function is similar to the cast operator in C. It returns a new instance
Georg Brandl1d837bc2009-12-29 11:24:00 +00001759 of *type* which points to the same memory block as *obj*. *type* must be a
Georg Brandl8d8f1972009-06-08 13:27:23 +00001760 pointer type, and *obj* must be an object that can be interpreted as a
Georg Brandl116aa622007-08-15 14:28:22 +00001761 pointer.
1762
1763
Georg Brandl8d8f1972009-06-08 13:27:23 +00001764.. function:: create_string_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001765
1766 This function creates a mutable character buffer. The returned object is a
1767 ctypes array of :class:`c_char`.
1768
Georg Brandl8d8f1972009-06-08 13:27:23 +00001769 *init_or_size* must be an integer which specifies the size of the array, or a
1770 bytes object which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001771
Georg Brandl8d8f1972009-06-08 13:27:23 +00001772 If a bytes object is specified as first argument, the buffer is made one item
1773 larger than its length so that the last element in the array is a NUL
Georg Brandl116aa622007-08-15 14:28:22 +00001774 termination character. An integer can be passed as second argument which allows
Georg Brandl8d8f1972009-06-08 13:27:23 +00001775 to specify the size of the array if the length of the bytes should not be used.
Georg Brandl116aa622007-08-15 14:28:22 +00001776
Georg Brandl116aa622007-08-15 14:28:22 +00001777
1778
Georg Brandl8d8f1972009-06-08 13:27:23 +00001779.. function:: create_unicode_buffer(init_or_size, size=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001780
1781 This function creates a mutable unicode character buffer. The returned object is
1782 a ctypes array of :class:`c_wchar`.
1783
Georg Brandl8d8f1972009-06-08 13:27:23 +00001784 *init_or_size* must be an integer which specifies the size of the array, or a
1785 string which will be used to initialize the array items.
Georg Brandl116aa622007-08-15 14:28:22 +00001786
Georg Brandl8d8f1972009-06-08 13:27:23 +00001787 If a string is specified as first argument, the buffer is made one item
Georg Brandl116aa622007-08-15 14:28:22 +00001788 larger than the length of the string so that the last element in the array is a
1789 NUL termination character. An integer can be passed as second argument which
1790 allows to specify the size of the array if the length of the string should not
1791 be used.
1792
Georg Brandl116aa622007-08-15 14:28:22 +00001793
1794
1795.. function:: DllCanUnloadNow()
1796
Georg Brandl1d837bc2009-12-29 11:24:00 +00001797 Windows only: This function is a hook which allows to implement in-process
1798 COM servers with ctypes. It is called from the DllCanUnloadNow function that
1799 the _ctypes extension dll exports.
Georg Brandl116aa622007-08-15 14:28:22 +00001800
1801
1802.. function:: DllGetClassObject()
1803
Georg Brandl1d837bc2009-12-29 11:24:00 +00001804 Windows only: This function is a hook which allows to implement in-process
1805 COM servers with ctypes. It is called from the DllGetClassObject function
1806 that the ``_ctypes`` extension dll exports.
1807
Georg Brandl116aa622007-08-15 14:28:22 +00001808
Thomas Heller2fadaa22008-06-16 19:56:33 +00001809.. function:: find_library(name)
1810 :module: ctypes.util
1811
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001812 Try to find a library and return a pathname. *name* is the library name
Benjamin Peterson28d88b42009-01-09 03:03:23 +00001813 without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001814 number (this is the form used for the posix linker option :option:`-l`). If
1815 no library can be found, returns ``None``.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001816
1817 The exact functionality is system dependent.
1818
Thomas Heller2fadaa22008-06-16 19:56:33 +00001819
1820.. function:: find_msvcrt()
1821 :module: ctypes.util
1822
Georg Brandl1d837bc2009-12-29 11:24:00 +00001823 Windows only: return the filename of the VC runtype library used by Python,
1824 and by the extension modules. If the name of the library cannot be
1825 determined, ``None`` is returned.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001826
Georg Brandl1d837bc2009-12-29 11:24:00 +00001827 If you need to free memory, for example, allocated by an extension module
1828 with a call to the ``free(void *)``, it is important that you use the
1829 function in the same library that allocated the memory.
1830
Thomas Heller2fadaa22008-06-16 19:56:33 +00001831
Georg Brandl116aa622007-08-15 14:28:22 +00001832.. function:: FormatError([code])
1833
Georg Brandl1d837bc2009-12-29 11:24:00 +00001834 Windows only: Returns a textual description of the error code *code*. If no
1835 error code is specified, the last error code is used by calling the Windows
1836 api function GetLastError.
Georg Brandl116aa622007-08-15 14:28:22 +00001837
1838
1839.. function:: GetLastError()
1840
1841 Windows only: Returns the last error code set by Windows in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001842 This function calls the Windows `GetLastError()` function directly,
1843 it does not return the ctypes-private copy of the error code.
Georg Brandl116aa622007-08-15 14:28:22 +00001844
Thomas Hellerb795f5282008-06-10 15:26:58 +00001845.. function:: get_errno()
1846
1847 Returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001848 :data:`errno` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001849
Thomas Hellerb795f5282008-06-10 15:26:58 +00001850.. function:: get_last_error()
1851
1852 Windows only: returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001853 :data:`LastError` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001854
Georg Brandl116aa622007-08-15 14:28:22 +00001855.. function:: memmove(dst, src, count)
1856
1857 Same as the standard C memmove library function: copies *count* bytes from
Georg Brandl1d837bc2009-12-29 11:24:00 +00001858 *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can
1859 be converted to pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001860
1861
1862.. function:: memset(dst, c, count)
1863
1864 Same as the standard C memset library function: fills the memory block at
1865 address *dst* with *count* bytes of value *c*. *dst* must be an integer
1866 specifying an address, or a ctypes instance.
1867
1868
1869.. function:: POINTER(type)
1870
1871 This factory function creates and returns a new ctypes pointer type. Pointer
1872 types are cached an reused internally, so calling this function repeatedly is
Georg Brandl1d837bc2009-12-29 11:24:00 +00001873 cheap. *type* must be a ctypes type.
Georg Brandl116aa622007-08-15 14:28:22 +00001874
1875
1876.. function:: pointer(obj)
1877
Georg Brandl8d8f1972009-06-08 13:27:23 +00001878 This function creates a new pointer instance, pointing to *obj*. The returned
Georg Brandl1d837bc2009-12-29 11:24:00 +00001879 object is of the type ``POINTER(type(obj))``.
Georg Brandl116aa622007-08-15 14:28:22 +00001880
1881 Note: If you just want to pass a pointer to an object to a foreign function
1882 call, you should use ``byref(obj)`` which is much faster.
1883
1884
1885.. function:: resize(obj, size)
1886
Georg Brandl1d837bc2009-12-29 11:24:00 +00001887 This function resizes the internal memory buffer of *obj*, which must be an
1888 instance of a ctypes type. It is not possible to make the buffer smaller
1889 than the native size of the objects type, as given by ``sizeof(type(obj))``,
1890 but it is possible to enlarge the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00001891
1892
Thomas Hellerb795f5282008-06-10 15:26:58 +00001893.. function:: set_errno(value)
1894
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001895 Set the current value of the ctypes-private copy of the system :data:`errno`
1896 variable in the calling thread to *value* and return the previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001897
Georg Brandl8d8f1972009-06-08 13:27:23 +00001898
Georg Brandl1d837bc2009-12-29 11:24:00 +00001899
Thomas Hellerb795f5282008-06-10 15:26:58 +00001900.. function:: set_last_error(value)
1901
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001902 Windows only: set the current value of the ctypes-private copy of the system
1903 :data:`LastError` variable in the calling thread to *value* and return the
1904 previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001905
Georg Brandl8d8f1972009-06-08 13:27:23 +00001906
Georg Brandl1d837bc2009-12-29 11:24:00 +00001907
Georg Brandl116aa622007-08-15 14:28:22 +00001908.. function:: sizeof(obj_or_type)
1909
1910 Returns the size in bytes of a ctypes type or instance memory buffer. Does the
1911 same as the C ``sizeof()`` function.
1912
1913
Georg Brandl8d8f1972009-06-08 13:27:23 +00001914.. function:: string_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001915
Ezio Melottie130a522011-10-19 10:58:56 +03001916 This function returns the C string starting at memory address *address* as a bytes
Georg Brandl8d8f1972009-06-08 13:27:23 +00001917 object. If size is specified, it is used as size, otherwise the string is assumed
1918 to be zero-terminated.
Georg Brandl116aa622007-08-15 14:28:22 +00001919
1920
1921.. function:: WinError(code=None, descr=None)
1922
1923 Windows only: this function is probably the worst-named thing in ctypes. It
Antoine Pitrou442ee032011-10-12 18:53:23 +02001924 creates an instance of OSError. If *code* is not specified,
Georg Brandl1d837bc2009-12-29 11:24:00 +00001925 ``GetLastError`` is called to determine the error code. If *descr* is not
Thomas Woutersed03b412007-08-28 21:37:11 +00001926 specified, :func:`FormatError` is called to get a textual description of the
Georg Brandl116aa622007-08-15 14:28:22 +00001927 error.
1928
Antoine Pitrou442ee032011-10-12 18:53:23 +02001929 .. versionchanged:: 3.3
1930 An instance of :exc:`WindowsError` used to be created.
1931
Georg Brandl116aa622007-08-15 14:28:22 +00001932
Georg Brandl8d8f1972009-06-08 13:27:23 +00001933.. function:: wstring_at(address, size=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001934
1935 This function returns the wide character string starting at memory address
Georg Brandl1d837bc2009-12-29 11:24:00 +00001936 *address* as a string. If *size* is specified, it is used as the number of
1937 characters of the string, otherwise the string is assumed to be
Georg Brandl116aa622007-08-15 14:28:22 +00001938 zero-terminated.
1939
1940
1941.. _ctypes-data-types:
1942
1943Data types
1944^^^^^^^^^^
1945
1946
1947.. class:: _CData
1948
Georg Brandl1d837bc2009-12-29 11:24:00 +00001949 This non-public class is the common base class of all ctypes data types.
1950 Among other things, all ctypes type instances contain a memory block that
1951 hold C compatible data; the address of the memory block is returned by the
Georg Brandl8d8f1972009-06-08 13:27:23 +00001952 :func:`addressof` helper function. Another instance variable is exposed as
Georg Brandl1d837bc2009-12-29 11:24:00 +00001953 :attr:`_objects`; this contains other Python objects that need to be kept
1954 alive in case the memory block contains pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001955
Benjamin Petersone41251e2008-04-25 01:59:09 +00001956 Common methods of ctypes data types, these are all class methods (to be
1957 exact, they are methods of the :term:`metaclass`):
Georg Brandl116aa622007-08-15 14:28:22 +00001958
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001959 .. method:: _CData.from_buffer(source[, offset])
1960
Georg Brandl1d837bc2009-12-29 11:24:00 +00001961 This method returns a ctypes instance that shares the buffer of the
1962 *source* object. The *source* object must support the writeable buffer
1963 interface. The optional *offset* parameter specifies an offset into the
1964 source buffer in bytes; the default is zero. If the source buffer is not
1965 large enough a :exc:`ValueError` is raised.
1966
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001967
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001968 .. method:: _CData.from_buffer_copy(source[, offset])
1969
Georg Brandl1d837bc2009-12-29 11:24:00 +00001970 This method creates a ctypes instance, copying the buffer from the
1971 *source* object buffer which must be readable. The optional *offset*
1972 parameter specifies an offset into the source buffer in bytes; the default
1973 is zero. If the source buffer is not large enough a :exc:`ValueError` is
1974 raised.
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001975
Benjamin Petersone41251e2008-04-25 01:59:09 +00001976 .. method:: from_address(address)
Georg Brandl116aa622007-08-15 14:28:22 +00001977
Benjamin Petersone41251e2008-04-25 01:59:09 +00001978 This method returns a ctypes type instance using the memory specified by
Georg Brandl1d837bc2009-12-29 11:24:00 +00001979 *address* which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00001980
Benjamin Petersone41251e2008-04-25 01:59:09 +00001981 .. method:: from_param(obj)
Georg Brandl116aa622007-08-15 14:28:22 +00001982
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001983 This method adapts *obj* to a ctypes type. It is called with the actual
1984 object used in a foreign function call when the type is present in the
1985 foreign function's :attr:`argtypes` tuple; it must return an object that
1986 can be used as a function call parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001987
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001988 All ctypes data types have a default implementation of this classmethod
Georg Brandl8d8f1972009-06-08 13:27:23 +00001989 that normally returns *obj* if that is an instance of the type. Some
Benjamin Petersone41251e2008-04-25 01:59:09 +00001990 types accept other objects as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001991
Benjamin Petersone41251e2008-04-25 01:59:09 +00001992 .. method:: in_dll(library, name)
Georg Brandl116aa622007-08-15 14:28:22 +00001993
Benjamin Petersone41251e2008-04-25 01:59:09 +00001994 This method returns a ctypes type instance exported by a shared
1995 library. *name* is the name of the symbol that exports the data, *library*
1996 is the loaded shared library.
Georg Brandl116aa622007-08-15 14:28:22 +00001997
Benjamin Petersone41251e2008-04-25 01:59:09 +00001998 Common instance variables of ctypes data types:
Georg Brandl116aa622007-08-15 14:28:22 +00001999
Benjamin Petersone41251e2008-04-25 01:59:09 +00002000 .. attribute:: _b_base_
Georg Brandl116aa622007-08-15 14:28:22 +00002001
Benjamin Petersone41251e2008-04-25 01:59:09 +00002002 Sometimes ctypes data instances do not own the memory block they contain,
2003 instead they share part of the memory block of a base object. The
2004 :attr:`_b_base_` read-only member is the root ctypes object that owns the
2005 memory block.
Georg Brandl116aa622007-08-15 14:28:22 +00002006
Benjamin Petersone41251e2008-04-25 01:59:09 +00002007 .. attribute:: _b_needsfree_
Georg Brandl116aa622007-08-15 14:28:22 +00002008
Benjamin Petersone41251e2008-04-25 01:59:09 +00002009 This read-only variable is true when the ctypes data instance has
2010 allocated the memory block itself, false otherwise.
2011
Benjamin Petersone41251e2008-04-25 01:59:09 +00002012 .. attribute:: _objects
2013
2014 This member is either ``None`` or a dictionary containing Python objects
2015 that need to be kept alive so that the memory block contents is kept
2016 valid. This object is only exposed for debugging; never modify the
2017 contents of this dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002018
2019
2020.. _ctypes-fundamental-data-types-2:
2021
2022Fundamental data types
2023^^^^^^^^^^^^^^^^^^^^^^
2024
Georg Brandl116aa622007-08-15 14:28:22 +00002025.. class:: _SimpleCData
2026
Benjamin Peterson35e8c462008-04-24 02:34:53 +00002027 This non-public class is the base class of all fundamental ctypes data
2028 types. It is mentioned here because it contains the common attributes of the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002029 fundamental ctypes data types. :class:`_SimpleCData` is a subclass of
2030 :class:`_CData`, so it inherits their methods and attributes. ctypes data
2031 types that are not and do not contain pointers can now be pickled.
Thomas Heller13394e92008-02-13 20:40:44 +00002032
Benjamin Petersone41251e2008-04-25 01:59:09 +00002033 Instances have a single attribute:
Georg Brandl116aa622007-08-15 14:28:22 +00002034
Benjamin Petersone41251e2008-04-25 01:59:09 +00002035 .. attribute:: value
Georg Brandl116aa622007-08-15 14:28:22 +00002036
Benjamin Petersone41251e2008-04-25 01:59:09 +00002037 This attribute contains the actual value of the instance. For integer and
2038 pointer types, it is an integer, for character types, it is a single
Georg Brandl8d8f1972009-06-08 13:27:23 +00002039 character bytes object or string, for character pointer types it is a
2040 Python bytes object or string.
Georg Brandl116aa622007-08-15 14:28:22 +00002041
Benjamin Petersone41251e2008-04-25 01:59:09 +00002042 When the ``value`` attribute is retrieved from a ctypes instance, usually
Georg Brandl8d8f1972009-06-08 13:27:23 +00002043 a new object is returned each time. :mod:`ctypes` does *not* implement
Benjamin Petersone41251e2008-04-25 01:59:09 +00002044 original object return, always a new object is constructed. The same is
2045 true for all other ctypes object instances.
Georg Brandl116aa622007-08-15 14:28:22 +00002046
Georg Brandl8d8f1972009-06-08 13:27:23 +00002047
Georg Brandl116aa622007-08-15 14:28:22 +00002048Fundamental data types, when returned as foreign function call results, or, for
2049example, by retrieving structure field members or array items, are transparently
2050converted to native Python types. In other words, if a foreign function has a
Georg Brandl8d8f1972009-06-08 13:27:23 +00002051:attr:`restype` of :class:`c_char_p`, you will always receive a Python bytes
2052object, *not* a :class:`c_char_p` instance.
2053
2054.. XXX above is false, it actually returns a Unicode string
Georg Brandl116aa622007-08-15 14:28:22 +00002055
Thomas Woutersed03b412007-08-28 21:37:11 +00002056Subclasses of fundamental data types do *not* inherit this behavior. So, if a
Georg Brandl116aa622007-08-15 14:28:22 +00002057foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2058receive an instance of this subclass from the function call. Of course, you can
2059get the value of the pointer by accessing the ``value`` attribute.
2060
2061These are the fundamental ctypes data types:
2062
Georg Brandl116aa622007-08-15 14:28:22 +00002063.. class:: c_byte
2064
Georg Brandl60203b42010-10-06 10:11:56 +00002065 Represents the C :c:type:`signed char` datatype, and interprets the value as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002066 small integer. The constructor accepts an optional integer initializer; no
2067 overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002068
2069
2070.. class:: c_char
2071
Georg Brandl60203b42010-10-06 10:11:56 +00002072 Represents the C :c:type:`char` datatype, and interprets the value as a single
Georg Brandl1d837bc2009-12-29 11:24:00 +00002073 character. The constructor accepts an optional string initializer, the
2074 length of the string must be exactly one character.
Georg Brandl116aa622007-08-15 14:28:22 +00002075
2076
2077.. class:: c_char_p
2078
Georg Brandl60203b42010-10-06 10:11:56 +00002079 Represents the C :c:type:`char *` datatype when it points to a zero-terminated
Georg Brandl1d837bc2009-12-29 11:24:00 +00002080 string. For a general character pointer that may also point to binary data,
2081 ``POINTER(c_char)`` must be used. The constructor accepts an integer
2082 address, or a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +00002083
2084
2085.. class:: c_double
2086
Georg Brandl60203b42010-10-06 10:11:56 +00002087 Represents the C :c:type:`double` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002088 optional float initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002089
2090
Thomas Wouters89d996e2007-09-08 17:39:28 +00002091.. class:: c_longdouble
2092
Georg Brandl60203b42010-10-06 10:11:56 +00002093 Represents the C :c:type:`long double` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002094 optional float initializer. On platforms where ``sizeof(long double) ==
2095 sizeof(double)`` it is an alias to :class:`c_double`.
Thomas Wouters89d996e2007-09-08 17:39:28 +00002096
Georg Brandl116aa622007-08-15 14:28:22 +00002097.. class:: c_float
2098
Georg Brandl60203b42010-10-06 10:11:56 +00002099 Represents the C :c:type:`float` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002100 optional float initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002101
2102
2103.. class:: c_int
2104
Georg Brandl60203b42010-10-06 10:11:56 +00002105 Represents the C :c:type:`signed int` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002106 optional integer initializer; no overflow checking is done. On platforms
2107 where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
Georg Brandl116aa622007-08-15 14:28:22 +00002108
2109
2110.. class:: c_int8
2111
Georg Brandl60203b42010-10-06 10:11:56 +00002112 Represents the C 8-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002113 :class:`c_byte`.
2114
2115
2116.. class:: c_int16
2117
Georg Brandl60203b42010-10-06 10:11:56 +00002118 Represents the C 16-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002119 :class:`c_short`.
2120
2121
2122.. class:: c_int32
2123
Georg Brandl60203b42010-10-06 10:11:56 +00002124 Represents the C 32-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002125 :class:`c_int`.
2126
2127
2128.. class:: c_int64
2129
Georg Brandl60203b42010-10-06 10:11:56 +00002130 Represents the C 64-bit :c:type:`signed int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002131 :class:`c_longlong`.
2132
2133
2134.. class:: c_long
2135
Georg Brandl60203b42010-10-06 10:11:56 +00002136 Represents the C :c:type:`signed long` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002137 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002138
2139
2140.. class:: c_longlong
2141
Georg Brandl60203b42010-10-06 10:11:56 +00002142 Represents the C :c:type:`signed long long` datatype. The constructor accepts
Georg Brandl1d837bc2009-12-29 11:24:00 +00002143 an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002144
2145
2146.. class:: c_short
2147
Georg Brandl60203b42010-10-06 10:11:56 +00002148 Represents the C :c:type:`signed short` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002149 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002150
2151
2152.. class:: c_size_t
2153
Georg Brandl60203b42010-10-06 10:11:56 +00002154 Represents the C :c:type:`size_t` datatype.
Georg Brandl116aa622007-08-15 14:28:22 +00002155
2156
Gregory P. Smith1a530912010-03-01 04:59:27 +00002157.. class:: c_ssize_t
2158
Georg Brandl60203b42010-10-06 10:11:56 +00002159 Represents the C :c:type:`ssize_t` datatype.
Gregory P. Smith1a530912010-03-01 04:59:27 +00002160
2161 .. versionadded:: 3.2
2162
2163
Georg Brandl116aa622007-08-15 14:28:22 +00002164.. class:: c_ubyte
2165
Georg Brandl60203b42010-10-06 10:11:56 +00002166 Represents the C :c:type:`unsigned char` datatype, it interprets the value as
Georg Brandl1d837bc2009-12-29 11:24:00 +00002167 small integer. The constructor accepts an optional integer initializer; no
2168 overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002169
2170
2171.. class:: c_uint
2172
Georg Brandl60203b42010-10-06 10:11:56 +00002173 Represents the C :c:type:`unsigned int` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002174 optional integer initializer; no overflow checking is done. On platforms
2175 where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
Georg Brandl116aa622007-08-15 14:28:22 +00002176
2177
2178.. class:: c_uint8
2179
Georg Brandl60203b42010-10-06 10:11:56 +00002180 Represents the C 8-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002181 :class:`c_ubyte`.
2182
2183
2184.. class:: c_uint16
2185
Georg Brandl60203b42010-10-06 10:11:56 +00002186 Represents the C 16-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002187 :class:`c_ushort`.
2188
2189
2190.. class:: c_uint32
2191
Georg Brandl60203b42010-10-06 10:11:56 +00002192 Represents the C 32-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002193 :class:`c_uint`.
2194
2195
2196.. class:: c_uint64
2197
Georg Brandl60203b42010-10-06 10:11:56 +00002198 Represents the C 64-bit :c:type:`unsigned int` datatype. Usually an alias for
Georg Brandl116aa622007-08-15 14:28:22 +00002199 :class:`c_ulonglong`.
2200
2201
2202.. class:: c_ulong
2203
Georg Brandl60203b42010-10-06 10:11:56 +00002204 Represents the C :c:type:`unsigned long` datatype. The constructor accepts an
Georg Brandl1d837bc2009-12-29 11:24:00 +00002205 optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002206
2207
2208.. class:: c_ulonglong
2209
Georg Brandl60203b42010-10-06 10:11:56 +00002210 Represents the C :c:type:`unsigned long long` datatype. The constructor
Georg Brandl1d837bc2009-12-29 11:24:00 +00002211 accepts an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002212
2213
2214.. class:: c_ushort
2215
Georg Brandl60203b42010-10-06 10:11:56 +00002216 Represents the C :c:type:`unsigned short` datatype. The constructor accepts
Georg Brandl1d837bc2009-12-29 11:24:00 +00002217 an optional integer initializer; no overflow checking is done.
Georg Brandl116aa622007-08-15 14:28:22 +00002218
2219
2220.. class:: c_void_p
2221
Georg Brandl60203b42010-10-06 10:11:56 +00002222 Represents the C :c:type:`void *` type. The value is represented as integer.
Georg Brandl1d837bc2009-12-29 11:24:00 +00002223 The constructor accepts an optional integer initializer.
Georg Brandl116aa622007-08-15 14:28:22 +00002224
2225
2226.. class:: c_wchar
2227
Georg Brandl60203b42010-10-06 10:11:56 +00002228 Represents the C :c:type:`wchar_t` datatype, and interprets the value as a
Georg Brandl1d837bc2009-12-29 11:24:00 +00002229 single character unicode string. The constructor accepts an optional string
Georg Brandl116aa622007-08-15 14:28:22 +00002230 initializer, the length of the string must be exactly one character.
2231
2232
2233.. class:: c_wchar_p
2234
Georg Brandl60203b42010-10-06 10:11:56 +00002235 Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a
Georg Brandl1d837bc2009-12-29 11:24:00 +00002236 zero-terminated wide character string. The constructor accepts an integer
Georg Brandl116aa622007-08-15 14:28:22 +00002237 address, or a string.
2238
2239
2240.. class:: c_bool
2241
Georg Brandl60203b42010-10-06 10:11:56 +00002242 Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from
Georg Brandl1d837bc2009-12-29 11:24:00 +00002243 C99). Its value can be True or False, and the constructor accepts any object
2244 that has a truth value.
Georg Brandl116aa622007-08-15 14:28:22 +00002245
Georg Brandl116aa622007-08-15 14:28:22 +00002246
2247.. class:: HRESULT
2248
Georg Brandl60203b42010-10-06 10:11:56 +00002249 Windows only: Represents a :c:type:`HRESULT` value, which contains success or
Georg Brandl116aa622007-08-15 14:28:22 +00002250 error information for a function or method call.
2251
2252
2253.. class:: py_object
2254
Georg Brandl60203b42010-10-06 10:11:56 +00002255 Represents the C :c:type:`PyObject *` datatype. Calling this without an
2256 argument creates a ``NULL`` :c:type:`PyObject *` pointer.
Georg Brandl116aa622007-08-15 14:28:22 +00002257
Georg Brandl1d837bc2009-12-29 11:24:00 +00002258The :mod:`ctypes.wintypes` module provides quite some other Windows specific
Georg Brandl60203b42010-10-06 10:11:56 +00002259data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`. Some
2260useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined.
Georg Brandl116aa622007-08-15 14:28:22 +00002261
2262
2263.. _ctypes-structured-data-types:
2264
2265Structured data types
2266^^^^^^^^^^^^^^^^^^^^^
2267
2268
2269.. class:: Union(*args, **kw)
2270
2271 Abstract base class for unions in native byte order.
2272
2273
2274.. class:: BigEndianStructure(*args, **kw)
2275
2276 Abstract base class for structures in *big endian* byte order.
2277
2278
2279.. class:: LittleEndianStructure(*args, **kw)
2280
2281 Abstract base class for structures in *little endian* byte order.
2282
2283Structures with non-native byte order cannot contain pointer type fields, or any
2284other data types containing pointer type fields.
2285
2286
2287.. class:: Structure(*args, **kw)
2288
2289 Abstract base class for structures in *native* byte order.
2290
Benjamin Petersone41251e2008-04-25 01:59:09 +00002291 Concrete structure and union types must be created by subclassing one of these
Georg Brandl8d8f1972009-06-08 13:27:23 +00002292 types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
Benjamin Petersone41251e2008-04-25 01:59:09 +00002293 create :term:`descriptor`\s which allow reading and writing the fields by direct
2294 attribute accesses. These are the
Georg Brandl116aa622007-08-15 14:28:22 +00002295
2296
Benjamin Petersone41251e2008-04-25 01:59:09 +00002297 .. attribute:: _fields_
Georg Brandl116aa622007-08-15 14:28:22 +00002298
Benjamin Petersone41251e2008-04-25 01:59:09 +00002299 A sequence defining the structure fields. The items must be 2-tuples or
2300 3-tuples. The first item is the name of the field, the second item
2301 specifies the type of the field; it can be any ctypes data type.
Georg Brandl116aa622007-08-15 14:28:22 +00002302
Benjamin Petersone41251e2008-04-25 01:59:09 +00002303 For integer type fields like :class:`c_int`, a third optional item can be
2304 given. It must be a small positive integer defining the bit width of the
2305 field.
Georg Brandl116aa622007-08-15 14:28:22 +00002306
Benjamin Petersone41251e2008-04-25 01:59:09 +00002307 Field names must be unique within one structure or union. This is not
2308 checked, only one field can be accessed when names are repeated.
Georg Brandl116aa622007-08-15 14:28:22 +00002309
Benjamin Petersone41251e2008-04-25 01:59:09 +00002310 It is possible to define the :attr:`_fields_` class variable *after* the
2311 class statement that defines the Structure subclass, this allows to create
2312 data types that directly or indirectly reference themselves::
Georg Brandl116aa622007-08-15 14:28:22 +00002313
Benjamin Petersone41251e2008-04-25 01:59:09 +00002314 class List(Structure):
2315 pass
2316 List._fields_ = [("pnext", POINTER(List)),
2317 ...
2318 ]
Georg Brandl116aa622007-08-15 14:28:22 +00002319
Benjamin Petersone41251e2008-04-25 01:59:09 +00002320 The :attr:`_fields_` class variable must, however, be defined before the
Georg Brandl8d8f1972009-06-08 13:27:23 +00002321 type is first used (an instance is created, :func:`sizeof` is called on it,
Benjamin Petersone41251e2008-04-25 01:59:09 +00002322 and so on). Later assignments to the :attr:`_fields_` class variable will
2323 raise an AttributeError.
Georg Brandl116aa622007-08-15 14:28:22 +00002324
Benjamin Petersone41251e2008-04-25 01:59:09 +00002325 Structure and union subclass constructors accept both positional and named
2326 arguments. Positional arguments are used to initialize the fields in the
2327 same order as they appear in the :attr:`_fields_` definition, named
2328 arguments are used to initialize the fields with the corresponding name.
Georg Brandl116aa622007-08-15 14:28:22 +00002329
Benjamin Petersone41251e2008-04-25 01:59:09 +00002330 It is possible to defined sub-subclasses of structure types, they inherit
2331 the fields of the base class plus the :attr:`_fields_` defined in the
2332 sub-subclass, if any.
Georg Brandl116aa622007-08-15 14:28:22 +00002333
2334
Benjamin Petersone41251e2008-04-25 01:59:09 +00002335 .. attribute:: _pack_
Georg Brandl116aa622007-08-15 14:28:22 +00002336
Benjamin Petersone41251e2008-04-25 01:59:09 +00002337 An optional small integer that allows to override the alignment of
2338 structure fields in the instance. :attr:`_pack_` must already be defined
2339 when :attr:`_fields_` is assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002340
2341
Benjamin Petersone41251e2008-04-25 01:59:09 +00002342 .. attribute:: _anonymous_
Georg Brandl116aa622007-08-15 14:28:22 +00002343
Benjamin Petersone41251e2008-04-25 01:59:09 +00002344 An optional sequence that lists the names of unnamed (anonymous) fields.
Georg Brandl1d837bc2009-12-29 11:24:00 +00002345 :attr:`_anonymous_` must be already defined when :attr:`_fields_` is
2346 assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002347
Benjamin Petersone41251e2008-04-25 01:59:09 +00002348 The fields listed in this variable must be structure or union type fields.
Georg Brandl8d8f1972009-06-08 13:27:23 +00002349 :mod:`ctypes` will create descriptors in the structure type that allows to
Benjamin Petersone41251e2008-04-25 01:59:09 +00002350 access the nested fields directly, without the need to create the
2351 structure or union field.
Georg Brandl116aa622007-08-15 14:28:22 +00002352
Benjamin Petersone41251e2008-04-25 01:59:09 +00002353 Here is an example type (Windows)::
Georg Brandl116aa622007-08-15 14:28:22 +00002354
Benjamin Petersone41251e2008-04-25 01:59:09 +00002355 class _U(Union):
2356 _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2357 ("lpadesc", POINTER(ARRAYDESC)),
2358 ("hreftype", HREFTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002359
Benjamin Petersone41251e2008-04-25 01:59:09 +00002360 class TYPEDESC(Structure):
Benjamin Petersonb58dda72009-01-18 22:27:04 +00002361 _anonymous_ = ("u",)
Benjamin Petersone41251e2008-04-25 01:59:09 +00002362 _fields_ = [("u", _U),
2363 ("vt", VARTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002364
Georg Brandl116aa622007-08-15 14:28:22 +00002365
Benjamin Petersone41251e2008-04-25 01:59:09 +00002366 The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2367 specifies which one of the union fields is valid. Since the ``u`` field
2368 is defined as anonymous field, it is now possible to access the members
2369 directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2370 are equivalent, but the former is faster since it does not need to create
2371 a temporary union instance::
Georg Brandl116aa622007-08-15 14:28:22 +00002372
Benjamin Petersone41251e2008-04-25 01:59:09 +00002373 td = TYPEDESC()
2374 td.vt = VT_PTR
2375 td.lptdesc = POINTER(some_type)
2376 td.u.lptdesc = POINTER(some_type)
Georg Brandl116aa622007-08-15 14:28:22 +00002377
Georg Brandl1d837bc2009-12-29 11:24:00 +00002378 It is possible to defined sub-subclasses of structures, they inherit the
2379 fields of the base class. If the subclass definition has a separate
2380 :attr:`_fields_` variable, the fields specified in this are appended to the
2381 fields of the base class.
Georg Brandl116aa622007-08-15 14:28:22 +00002382
Georg Brandl1d837bc2009-12-29 11:24:00 +00002383 Structure and union constructors accept both positional and keyword
2384 arguments. Positional arguments are used to initialize member fields in the
2385 same order as they are appear in :attr:`_fields_`. Keyword arguments in the
2386 constructor are interpreted as attribute assignments, so they will initialize
2387 :attr:`_fields_` with the same name, or create new attributes for names not
2388 present in :attr:`_fields_`.
Georg Brandl116aa622007-08-15 14:28:22 +00002389
2390
2391.. _ctypes-arrays-pointers:
2392
2393Arrays and pointers
2394^^^^^^^^^^^^^^^^^^^
2395
Georg Brandl1d837bc2009-12-29 11:24:00 +00002396Not yet written - please see the sections :ref:`ctypes-pointers` and section
2397:ref:`ctypes-arrays` in the tutorial.
Georg Brandl116aa622007-08-15 14:28:22 +00002398