Georg Brandl | 71515ca | 2009-05-17 12:29:12 +0000 | [diff] [blame] | 1 | :mod:`ctypes` --- A foreign function library for Python |
| 2 | ======================================================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3 | |
| 4 | .. module:: ctypes |
| 5 | :synopsis: A foreign function library for Python. |
Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 6 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 7 | .. moduleauthor:: Thomas Heller <theller@python.net> |
| 8 | |
Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 9 | -------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 10 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 11 | :mod:`ctypes` is a foreign function library for Python. It provides C compatible |
Benjamin Peterson | 3e4f055 | 2008-09-02 00:31:15 +0000 | [diff] [blame] | 12 | data types, and allows calling functions in DLLs or shared libraries. It can be |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 13 | used to wrap these libraries in pure Python. |
| 14 | |
| 15 | |
| 16 | .. _ctypes-ctypes-tutorial: |
| 17 | |
| 18 | ctypes tutorial |
| 19 | --------------- |
| 20 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 21 | Note: The code samples in this tutorial use :mod:`doctest` to make sure that |
| 22 | they actually work. Since some code samples behave differently under Linux, |
| 23 | Windows, or Mac OS X, they contain doctest directives in comments. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 24 | |
Berker Peksag | d85a1e6 | 2016-06-02 12:17:51 -0700 | [diff] [blame] | 25 | Note: Some code samples reference the ctypes :class:`c_int` type. On platforms |
Berker Peksag | 8891dfe | 2016-06-02 15:28:00 -0700 | [diff] [blame] | 26 | where ``sizeof(long) == sizeof(int)`` it is an alias to :class:`c_long`. |
| 27 | So, you should not be confused if :class:`c_long` is printed if you would expect |
| 28 | :class:`c_int` --- they are actually the same type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 29 | |
| 30 | .. _ctypes-loading-dynamic-link-libraries: |
| 31 | |
| 32 | Loading dynamic link libraries |
| 33 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 34 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 35 | :mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll* |
Benjamin Peterson | 3e4f055 | 2008-09-02 00:31:15 +0000 | [diff] [blame] | 36 | objects, for loading dynamic link libraries. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 37 | |
| 38 | You load libraries by accessing them as attributes of these objects. *cdll* |
| 39 | loads libraries which export functions using the standard ``cdecl`` calling |
| 40 | convention, while *windll* libraries call functions using the ``stdcall`` |
| 41 | calling convention. *oledll* also uses the ``stdcall`` calling convention, and |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 42 | assumes the functions return a Windows :c:type:`HRESULT` error code. The error |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 43 | code is used to automatically raise an :class:`OSError` exception when the |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 44 | function call fails. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 45 | |
Antoine Pitrou | 442ee03 | 2011-10-12 18:53:23 +0200 | [diff] [blame] | 46 | .. versionchanged:: 3.3 |
| 47 | Windows errors used to raise :exc:`WindowsError`, which is now an alias |
| 48 | of :exc:`OSError`. |
| 49 | |
| 50 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 51 | Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C |
| 52 | library containing most standard C functions, and uses the cdecl calling |
| 53 | convention:: |
| 54 | |
| 55 | >>> from ctypes import * |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 56 | >>> print(windll.kernel32) # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 57 | <WinDLL 'kernel32', handle ... at ...> |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 58 | >>> print(cdll.msvcrt) # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 59 | <CDLL 'msvcrt', handle ... at ...> |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 60 | >>> libc = cdll.msvcrt # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 61 | >>> |
| 62 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 63 | Windows appends the usual ``.dll`` file suffix automatically. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 64 | |
Steve Dower | d669b6b | 2016-03-12 08:25:22 -0800 | [diff] [blame] | 65 | .. note:: |
| 66 | Accessing the standard C library through ``cdll.msvcrt`` will use an |
| 67 | outdated version of the library that may be incompatible with the one |
| 68 | being used by Python. Where possible, use native Python functionality, |
| 69 | or else import and use the ``msvcrt`` module. |
| 70 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 71 | On Linux, it is required to specify the filename *including* the extension to |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 72 | load a library, so attribute access can not be used to load libraries. Either the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 73 | :meth:`LoadLibrary` method of the dll loaders should be used, or you should load |
| 74 | the library by creating an instance of CDLL by calling the constructor:: |
| 75 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 76 | >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 77 | <CDLL 'libc.so.6', handle ... at ...> |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 78 | >>> libc = CDLL("libc.so.6") # doctest: +LINUX |
| 79 | >>> libc # doctest: +LINUX |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 80 | <CDLL 'libc.so.6', handle ... at ...> |
| 81 | >>> |
| 82 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 83 | .. XXX Add section for Mac OS X. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 84 | |
| 85 | |
| 86 | .. _ctypes-accessing-functions-from-loaded-dlls: |
| 87 | |
| 88 | Accessing functions from loaded dlls |
| 89 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 90 | |
| 91 | Functions are accessed as attributes of dll objects:: |
| 92 | |
| 93 | >>> from ctypes import * |
| 94 | >>> libc.printf |
| 95 | <_FuncPtr object at 0x...> |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 96 | >>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 97 | <_FuncPtr object at 0x...> |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 98 | >>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 99 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 100 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 101 | File "ctypes.py", line 239, in __getattr__ |
| 102 | func = _StdcallFuncPtr(name, self) |
| 103 | AttributeError: function 'MyOwnFunction' not found |
| 104 | >>> |
| 105 | |
| 106 | Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI |
| 107 | as well as UNICODE versions of a function. The UNICODE version is exported with |
| 108 | an ``W`` appended to the name, while the ANSI version is exported with an ``A`` |
| 109 | appended to the name. The win32 ``GetModuleHandle`` function, which returns a |
| 110 | *module handle* for a given module name, has the following C prototype, and a |
| 111 | macro is used to expose one of them as ``GetModuleHandle`` depending on whether |
| 112 | UNICODE is defined or not:: |
| 113 | |
| 114 | /* ANSI version */ |
| 115 | HMODULE GetModuleHandleA(LPCSTR lpModuleName); |
| 116 | /* UNICODE version */ |
| 117 | HMODULE GetModuleHandleW(LPCWSTR lpModuleName); |
| 118 | |
| 119 | *windll* does not try to select one of them by magic, you must access the |
| 120 | version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW`` |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 121 | explicitly, and then call it with bytes or string objects respectively. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 122 | |
| 123 | Sometimes, dlls export functions with names which aren't valid Python |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 124 | identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use |
| 125 | :func:`getattr` to retrieve the function:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 126 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 127 | >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 128 | <_FuncPtr object at 0x...> |
| 129 | >>> |
| 130 | |
| 131 | On Windows, some dlls export functions not by name but by ordinal. These |
| 132 | functions can be accessed by indexing the dll object with the ordinal number:: |
| 133 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 134 | >>> cdll.kernel32[1] # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 135 | <_FuncPtr object at 0x...> |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 136 | >>> cdll.kernel32[0] # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 137 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 138 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 139 | File "ctypes.py", line 310, in __getitem__ |
| 140 | func = _StdcallFuncPtr(name, self) |
| 141 | AttributeError: function ordinal 0 not found |
| 142 | >>> |
| 143 | |
| 144 | |
| 145 | .. _ctypes-calling-functions: |
| 146 | |
| 147 | Calling functions |
| 148 | ^^^^^^^^^^^^^^^^^ |
| 149 | |
| 150 | You can call these functions like any other Python callable. This example uses |
| 151 | the ``time()`` function, which returns system time in seconds since the Unix |
| 152 | epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module |
| 153 | handle. |
| 154 | |
| 155 | This example calls both functions with a NULL pointer (``None`` should be used |
| 156 | as the NULL pointer):: |
| 157 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 158 | >>> print(libc.time(None)) # doctest: +SKIP |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 159 | 1150640792 |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 160 | >>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 161 | 0x1d000000 |
| 162 | >>> |
| 163 | |
Mariatta | f931fd1 | 2017-05-27 07:23:26 -0700 | [diff] [blame] | 164 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 165 | |
Mariatta | f931fd1 | 2017-05-27 07:23:26 -0700 | [diff] [blame] | 166 | :mod:`ctypes` may raise a :exc:`ValueError` after calling the function, if |
| 167 | it detects that an invalid number of arguments were passed. This behavior |
| 168 | should not be relied upon. It is deprecated in 3.6.2, and will be removed |
| 169 | in 3.7. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 170 | |
Mariatta | f931fd1 | 2017-05-27 07:23:26 -0700 | [diff] [blame] | 171 | :exc:`ValueError` is raised when you call an ``stdcall`` function with the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 172 | ``cdecl`` calling convention, or vice versa:: |
| 173 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 174 | >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 175 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 176 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 177 | ValueError: Procedure probably called with not enough arguments (4 bytes missing) |
| 178 | >>> |
| 179 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 180 | >>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 181 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 182 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 183 | ValueError: Procedure probably called with too many arguments (4 bytes in excess) |
| 184 | >>> |
| 185 | |
| 186 | To find out the correct calling convention you have to look into the C header |
| 187 | file or the documentation for the function you want to call. |
| 188 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 189 | On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 190 | crashes from general protection faults when functions are called with invalid |
| 191 | argument values:: |
| 192 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 193 | >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 194 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 195 | File "<stdin>", line 1, in <module> |
Antoine Pitrou | 442ee03 | 2011-10-12 18:53:23 +0200 | [diff] [blame] | 196 | OSError: exception: access violation reading 0x00000020 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 197 | >>> |
| 198 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 199 | There are, however, enough ways to crash Python with :mod:`ctypes`, so you |
Georg Brandl | b33c6eb | 2013-10-06 10:51:01 +0200 | [diff] [blame] | 200 | should be careful anyway. The :mod:`faulthandler` module can be helpful in |
| 201 | debugging crashes (e.g. from segmentation faults produced by erroneous C library |
| 202 | calls). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 203 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 204 | ``None``, integers, bytes objects and (unicode) strings are the only native |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 205 | Python objects that can directly be used as parameters in these function calls. |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 206 | ``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are passed |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 207 | as pointer to the memory block that contains their data (:c:type:`char *` or |
| 208 | :c:type:`wchar_t *`). Python integers are passed as the platforms default C |
| 209 | :c:type:`int` type, their value is masked to fit into the C type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 210 | |
| 211 | Before we move on calling functions with other parameter types, we have to learn |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 212 | more about :mod:`ctypes` data types. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 213 | |
| 214 | |
| 215 | .. _ctypes-fundamental-data-types: |
| 216 | |
| 217 | Fundamental data types |
| 218 | ^^^^^^^^^^^^^^^^^^^^^^ |
| 219 | |
Serhiy Storchaka | f47036c | 2013-12-24 11:04:36 +0200 | [diff] [blame] | 220 | :mod:`ctypes` defines a number of primitive C compatible data types: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 221 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 222 | +----------------------+------------------------------------------+----------------------------+ |
| 223 | | ctypes type | C type | Python type | |
| 224 | +======================+==========================================+============================+ |
Georg Brandl | ecdd63f | 2011-01-19 20:05:49 +0000 | [diff] [blame] | 225 | | :class:`c_bool` | :c:type:`_Bool` | bool (1) | |
| 226 | +----------------------+------------------------------------------+----------------------------+ |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 227 | | :class:`c_char` | :c:type:`char` | 1-character bytes object | |
| 228 | +----------------------+------------------------------------------+----------------------------+ |
| 229 | | :class:`c_wchar` | :c:type:`wchar_t` | 1-character string | |
| 230 | +----------------------+------------------------------------------+----------------------------+ |
| 231 | | :class:`c_byte` | :c:type:`char` | int | |
| 232 | +----------------------+------------------------------------------+----------------------------+ |
| 233 | | :class:`c_ubyte` | :c:type:`unsigned char` | int | |
| 234 | +----------------------+------------------------------------------+----------------------------+ |
| 235 | | :class:`c_short` | :c:type:`short` | int | |
| 236 | +----------------------+------------------------------------------+----------------------------+ |
| 237 | | :class:`c_ushort` | :c:type:`unsigned short` | int | |
| 238 | +----------------------+------------------------------------------+----------------------------+ |
| 239 | | :class:`c_int` | :c:type:`int` | int | |
| 240 | +----------------------+------------------------------------------+----------------------------+ |
| 241 | | :class:`c_uint` | :c:type:`unsigned int` | int | |
| 242 | +----------------------+------------------------------------------+----------------------------+ |
| 243 | | :class:`c_long` | :c:type:`long` | int | |
| 244 | +----------------------+------------------------------------------+----------------------------+ |
| 245 | | :class:`c_ulong` | :c:type:`unsigned long` | int | |
| 246 | +----------------------+------------------------------------------+----------------------------+ |
| 247 | | :class:`c_longlong` | :c:type:`__int64` or :c:type:`long long` | int | |
| 248 | +----------------------+------------------------------------------+----------------------------+ |
| 249 | | :class:`c_ulonglong` | :c:type:`unsigned __int64` or | int | |
| 250 | | | :c:type:`unsigned long long` | | |
| 251 | +----------------------+------------------------------------------+----------------------------+ |
Antoine Pitrou | 52cc722 | 2012-07-12 20:31:50 +0200 | [diff] [blame] | 252 | | :class:`c_size_t` | :c:type:`size_t` | int | |
| 253 | +----------------------+------------------------------------------+----------------------------+ |
| 254 | | :class:`c_ssize_t` | :c:type:`ssize_t` or | int | |
| 255 | | | :c:type:`Py_ssize_t` | | |
| 256 | +----------------------+------------------------------------------+----------------------------+ |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 257 | | :class:`c_float` | :c:type:`float` | float | |
| 258 | +----------------------+------------------------------------------+----------------------------+ |
| 259 | | :class:`c_double` | :c:type:`double` | float | |
| 260 | +----------------------+------------------------------------------+----------------------------+ |
| 261 | | :class:`c_longdouble`| :c:type:`long double` | float | |
| 262 | +----------------------+------------------------------------------+----------------------------+ |
| 263 | | :class:`c_char_p` | :c:type:`char *` (NUL terminated) | bytes object or ``None`` | |
| 264 | +----------------------+------------------------------------------+----------------------------+ |
| 265 | | :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | string or ``None`` | |
| 266 | +----------------------+------------------------------------------+----------------------------+ |
| 267 | | :class:`c_void_p` | :c:type:`void *` | int or ``None`` | |
| 268 | +----------------------+------------------------------------------+----------------------------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 269 | |
Georg Brandl | ecdd63f | 2011-01-19 20:05:49 +0000 | [diff] [blame] | 270 | (1) |
| 271 | The constructor accepts any object with a truth value. |
| 272 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 273 | All these types can be created by calling them with an optional initializer of |
| 274 | the correct type and value:: |
| 275 | |
| 276 | >>> c_int() |
| 277 | c_long(0) |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 278 | >>> c_wchar_p("Hello, World") |
Louie Lu | 0d637e2 | 2017-04-26 16:15:05 +0800 | [diff] [blame] | 279 | c_wchar_p(140018365411392) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 280 | >>> c_ushort(-3) |
| 281 | c_ushort(65533) |
| 282 | >>> |
| 283 | |
| 284 | Since these types are mutable, their value can also be changed afterwards:: |
| 285 | |
| 286 | >>> i = c_int(42) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 287 | >>> print(i) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 288 | c_long(42) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 289 | >>> print(i.value) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 290 | 42 |
| 291 | >>> i.value = -99 |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 292 | >>> print(i.value) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 293 | -99 |
| 294 | >>> |
| 295 | |
| 296 | Assigning a new value to instances of the pointer types :class:`c_char_p`, |
| 297 | :class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they |
| 298 | point to, *not the contents* of the memory block (of course not, because Python |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 299 | bytes objects are immutable):: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 300 | |
| 301 | >>> s = "Hello, World" |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 302 | >>> c_s = c_wchar_p(s) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 303 | >>> print(c_s) |
Louie Lu | 0d637e2 | 2017-04-26 16:15:05 +0800 | [diff] [blame] | 304 | c_wchar_p(139966785747344) |
| 305 | >>> print(c_s.value) |
| 306 | Hello World |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 307 | >>> c_s.value = "Hi, there" |
Louie Lu | 0d637e2 | 2017-04-26 16:15:05 +0800 | [diff] [blame] | 308 | >>> print(c_s) # the memory location has changed |
| 309 | c_wchar_p(139966783348904) |
| 310 | >>> print(c_s.value) |
| 311 | Hi, there |
| 312 | >>> print(s) # first object is unchanged |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 313 | Hello, World |
| 314 | >>> |
| 315 | |
| 316 | You should be careful, however, not to pass them to functions expecting pointers |
| 317 | to mutable memory. If you need mutable memory blocks, ctypes has a |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 318 | :func:`create_string_buffer` function which creates these in various ways. The |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 319 | current memory block contents can be accessed (or changed) with the ``raw`` |
| 320 | property; if you want to access it as NUL terminated string, use the ``value`` |
| 321 | property:: |
| 322 | |
| 323 | >>> from ctypes import * |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 324 | >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 325 | >>> print(sizeof(p), repr(p.raw)) |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 326 | 3 b'\x00\x00\x00' |
| 327 | >>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 328 | >>> print(sizeof(p), repr(p.raw)) |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 329 | 6 b'Hello\x00' |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 330 | >>> print(repr(p.value)) |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 331 | b'Hello' |
| 332 | >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 333 | >>> print(sizeof(p), repr(p.raw)) |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 334 | 10 b'Hello\x00\x00\x00\x00\x00' |
| 335 | >>> p.value = b"Hi" |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 336 | >>> print(sizeof(p), repr(p.raw)) |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 337 | 10 b'Hi\x00lo\x00\x00\x00\x00\x00' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 338 | >>> |
| 339 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 340 | The :func:`create_string_buffer` function replaces the :func:`c_buffer` function |
| 341 | (which is still available as an alias), as well as the :func:`c_string` function |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 342 | from earlier ctypes releases. To create a mutable memory block containing |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 343 | unicode characters of the C type :c:type:`wchar_t` use the |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 344 | :func:`create_unicode_buffer` function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 345 | |
| 346 | |
| 347 | .. _ctypes-calling-functions-continued: |
| 348 | |
| 349 | Calling functions, continued |
| 350 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 351 | |
| 352 | Note that printf prints to the real standard output channel, *not* to |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 353 | :data:`sys.stdout`, so these examples will only work at the console prompt, not |
| 354 | from within *IDLE* or *PythonWin*:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 355 | |
| 356 | >>> printf = libc.printf |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 357 | >>> printf(b"Hello, %s\n", b"World!") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 358 | Hello, World! |
| 359 | 14 |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 360 | >>> printf(b"Hello, %S\n", "World!") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 361 | Hello, World! |
Georg Brandl | 8a1e4c4 | 2009-05-25 21:13:36 +0000 | [diff] [blame] | 362 | 14 |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 363 | >>> printf(b"%d bottles of beer\n", 42) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 364 | 42 bottles of beer |
| 365 | 19 |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 366 | >>> printf(b"%f bottles of beer\n", 42.5) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 367 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 368 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 369 | ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2 |
| 370 | >>> |
| 371 | |
| 372 | As has been mentioned before, all Python types except integers, strings, and |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 373 | bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 374 | that they can be converted to the required C data type:: |
| 375 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 376 | >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14)) |
Georg Brandl | 8a1e4c4 | 2009-05-25 21:13:36 +0000 | [diff] [blame] | 377 | An int 1234, a double 3.140000 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 378 | 31 |
| 379 | >>> |
| 380 | |
| 381 | |
| 382 | .. _ctypes-calling-functions-with-own-custom-data-types: |
| 383 | |
| 384 | Calling functions with your own custom data types |
| 385 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 386 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 387 | You can also customize :mod:`ctypes` argument conversion to allow instances of |
| 388 | your own classes be used as function arguments. :mod:`ctypes` looks for an |
| 389 | :attr:`_as_parameter_` attribute and uses this as the function argument. Of |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 390 | course, it must be one of integer, string, or bytes:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 391 | |
Éric Araujo | 28053fb | 2010-11-22 03:09:19 +0000 | [diff] [blame] | 392 | >>> class Bottles: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 393 | ... def __init__(self, number): |
| 394 | ... self._as_parameter_ = number |
| 395 | ... |
| 396 | >>> bottles = Bottles(42) |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 397 | >>> printf(b"%d bottles of beer\n", bottles) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 398 | 42 bottles of beer |
| 399 | 19 |
| 400 | >>> |
| 401 | |
| 402 | If you don't want to store the instance's data in the :attr:`_as_parameter_` |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 403 | instance variable, you could define a :class:`property` which makes the |
| 404 | attribute available on request. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 405 | |
| 406 | |
| 407 | .. _ctypes-specifying-required-argument-types: |
| 408 | |
| 409 | Specifying the required argument types (function prototypes) |
| 410 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 411 | |
| 412 | It is possible to specify the required argument types of functions exported from |
| 413 | DLLs by setting the :attr:`argtypes` attribute. |
| 414 | |
| 415 | :attr:`argtypes` must be a sequence of C data types (the ``printf`` function is |
| 416 | probably not a good example here, because it takes a variable number and |
| 417 | different types of parameters depending on the format string, on the other hand |
| 418 | this is quite handy to experiment with this feature):: |
| 419 | |
| 420 | >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double] |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 421 | >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 422 | String 'Hi', Int 10, Double 2.200000 |
| 423 | 37 |
| 424 | >>> |
| 425 | |
| 426 | Specifying a format protects against incompatible argument types (just as a |
| 427 | prototype for a C function), and tries to convert the arguments to valid types:: |
| 428 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 429 | >>> printf(b"%d %d %d", 1, 2, 3) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 430 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 431 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 432 | ArgumentError: argument 2: exceptions.TypeError: wrong type |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 433 | >>> printf(b"%s %d %f\n", b"X", 2, 3) |
Georg Brandl | 8a1e4c4 | 2009-05-25 21:13:36 +0000 | [diff] [blame] | 434 | X 2 3.000000 |
| 435 | 13 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 436 | >>> |
| 437 | |
| 438 | If you have defined your own classes which you pass to function calls, you have |
| 439 | to implement a :meth:`from_param` class method for them to be able to use them |
| 440 | in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives |
| 441 | the Python object passed to the function call, it should do a typecheck or |
| 442 | whatever is needed to make sure this object is acceptable, and then return the |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 443 | object itself, its :attr:`_as_parameter_` attribute, or whatever you want to |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 444 | pass as the C function argument in this case. Again, the result should be an |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 445 | integer, string, bytes, a :mod:`ctypes` instance, or an object with an |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 446 | :attr:`_as_parameter_` attribute. |
| 447 | |
| 448 | |
| 449 | .. _ctypes-return-types: |
| 450 | |
| 451 | Return types |
| 452 | ^^^^^^^^^^^^ |
| 453 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 454 | By default functions are assumed to return the C :c:type:`int` type. Other |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 455 | return types can be specified by setting the :attr:`restype` attribute of the |
| 456 | function object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 457 | |
| 458 | Here is a more advanced example, it uses the ``strchr`` function, which expects |
| 459 | a string pointer and a char, and returns a pointer to a string:: |
| 460 | |
| 461 | >>> strchr = libc.strchr |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 462 | >>> strchr(b"abcdef", ord("d")) # doctest: +SKIP |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 463 | 8059983 |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 464 | >>> strchr.restype = c_char_p # c_char_p is a pointer to a string |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 465 | >>> strchr(b"abcdef", ord("d")) |
| 466 | b'def' |
| 467 | >>> print(strchr(b"abcdef", ord("x"))) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 468 | None |
| 469 | >>> |
| 470 | |
| 471 | If you want to avoid the ``ord("x")`` calls above, you can set the |
| 472 | :attr:`argtypes` attribute, and the second argument will be converted from a |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 473 | single character Python bytes object into a C char:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 474 | |
| 475 | >>> strchr.restype = c_char_p |
| 476 | >>> strchr.argtypes = [c_char_p, c_char] |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 477 | >>> strchr(b"abcdef", b"d") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 478 | 'def' |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 479 | >>> strchr(b"abcdef", b"def") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 480 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 481 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 482 | ArgumentError: argument 2: exceptions.TypeError: one character string expected |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 483 | >>> print(strchr(b"abcdef", b"x")) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 484 | None |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 485 | >>> strchr(b"abcdef", b"d") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 486 | 'def' |
| 487 | >>> |
| 488 | |
| 489 | You can also use a callable Python object (a function or a class for example) as |
| 490 | the :attr:`restype` attribute, if the foreign function returns an integer. The |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 491 | callable will be called with the *integer* the C function returns, and the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 492 | result of this call will be used as the result of your function call. This is |
| 493 | useful to check for error return values and automatically raise an exception:: |
| 494 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 495 | >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 496 | >>> def ValidHandle(value): |
| 497 | ... if value == 0: |
| 498 | ... raise WinError() |
| 499 | ... return value |
| 500 | ... |
| 501 | >>> |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 502 | >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS |
| 503 | >>> GetModuleHandle(None) # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 504 | 486539264 |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 505 | >>> GetModuleHandle("something silly") # doctest: +WINDOWS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 506 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 507 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 508 | File "<stdin>", line 3, in ValidHandle |
Antoine Pitrou | 442ee03 | 2011-10-12 18:53:23 +0200 | [diff] [blame] | 509 | OSError: [Errno 126] The specified module could not be found. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 510 | >>> |
| 511 | |
| 512 | ``WinError`` is a function which will call Windows ``FormatMessage()`` api to |
| 513 | get the string representation of an error code, and *returns* an exception. |
| 514 | ``WinError`` takes an optional error code parameter, if no one is used, it calls |
| 515 | :func:`GetLastError` to retrieve it. |
| 516 | |
| 517 | Please note that a much more powerful error checking mechanism is available |
| 518 | through the :attr:`errcheck` attribute; see the reference manual for details. |
| 519 | |
| 520 | |
| 521 | .. _ctypes-passing-pointers: |
| 522 | |
| 523 | Passing pointers (or: passing parameters by reference) |
| 524 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 525 | |
| 526 | Sometimes a C api function expects a *pointer* to a data type as parameter, |
| 527 | probably to write into the corresponding location, or if the data is too large |
| 528 | to be passed by value. This is also known as *passing parameters by reference*. |
| 529 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 530 | :mod:`ctypes` exports the :func:`byref` function which is used to pass parameters |
| 531 | by reference. The same effect can be achieved with the :func:`pointer` function, |
| 532 | although :func:`pointer` does a lot more work since it constructs a real pointer |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 533 | object, so it is faster to use :func:`byref` if you don't need the pointer |
| 534 | object in Python itself:: |
| 535 | |
| 536 | >>> i = c_int() |
| 537 | >>> f = c_float() |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 538 | >>> s = create_string_buffer(b'\000' * 32) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 539 | >>> print(i.value, f.value, repr(s.value)) |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 540 | 0 0.0 b'' |
| 541 | >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s", |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 542 | ... byref(i), byref(f), s) |
| 543 | 3 |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 544 | >>> print(i.value, f.value, repr(s.value)) |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 545 | 1 3.1400001049 b'Hello' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 546 | >>> |
| 547 | |
| 548 | |
| 549 | .. _ctypes-structures-unions: |
| 550 | |
| 551 | Structures and unions |
| 552 | ^^^^^^^^^^^^^^^^^^^^^ |
| 553 | |
| 554 | Structures and unions must derive from the :class:`Structure` and :class:`Union` |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 555 | base classes which are defined in the :mod:`ctypes` module. Each subclass must |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 556 | define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of |
| 557 | *2-tuples*, containing a *field name* and a *field type*. |
| 558 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 559 | The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other |
| 560 | derived :mod:`ctypes` type: structure, union, array, pointer. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 561 | |
| 562 | Here is a simple example of a POINT structure, which contains two integers named |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 563 | *x* and *y*, and also shows how to initialize a structure in the constructor:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 564 | |
| 565 | >>> from ctypes import * |
| 566 | >>> class POINT(Structure): |
| 567 | ... _fields_ = [("x", c_int), |
| 568 | ... ("y", c_int)] |
| 569 | ... |
| 570 | >>> point = POINT(10, 20) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 571 | >>> print(point.x, point.y) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 572 | 10 20 |
| 573 | >>> point = POINT(y=5) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 574 | >>> print(point.x, point.y) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 575 | 0 5 |
| 576 | >>> POINT(1, 2, 3) |
| 577 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 578 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 579 | ValueError: too many initializers |
| 580 | >>> |
| 581 | |
Eli Bendersky | f9164e1 | 2013-03-06 06:48:57 -0800 | [diff] [blame] | 582 | You can, however, build much more complicated structures. A structure can |
| 583 | itself contain other structures by using a structure as a field type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 584 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 585 | Here is a RECT structure which contains two POINTs named *upperleft* and |
| 586 | *lowerright*:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 587 | |
| 588 | >>> class RECT(Structure): |
| 589 | ... _fields_ = [("upperleft", POINT), |
| 590 | ... ("lowerright", POINT)] |
| 591 | ... |
| 592 | >>> rc = RECT(point) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 593 | >>> print(rc.upperleft.x, rc.upperleft.y) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 594 | 0 5 |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 595 | >>> print(rc.lowerright.x, rc.lowerright.y) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 596 | 0 0 |
| 597 | >>> |
| 598 | |
| 599 | Nested structures can also be initialized in the constructor in several ways:: |
| 600 | |
| 601 | >>> r = RECT(POINT(1, 2), POINT(3, 4)) |
| 602 | >>> r = RECT((1, 2), (3, 4)) |
| 603 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 604 | Field :term:`descriptor`\s can be retrieved from the *class*, they are useful |
| 605 | for debugging because they can provide useful information:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 606 | |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 607 | >>> print(POINT.x) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 608 | <Field type=c_long, ofs=0, size=4> |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 609 | >>> print(POINT.y) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 610 | <Field type=c_long, ofs=4, size=4> |
| 611 | >>> |
| 612 | |
| 613 | |
| 614 | .. _ctypes-structureunion-alignment-byte-order: |
| 615 | |
Eli Bendersky | 490cf44 | 2013-03-09 05:54:00 -0800 | [diff] [blame] | 616 | .. warning:: |
| 617 | |
| 618 | :mod:`ctypes` does not support passing unions or structures with bit-fields |
| 619 | to functions by value. While this may work on 32-bit x86, it's not |
| 620 | guaranteed by the library to work in the general case. Unions and |
| 621 | structures with bit-fields should always be passed to functions by pointer. |
| 622 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 623 | Structure/union alignment and byte order |
| 624 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 625 | |
| 626 | By default, Structure and Union fields are aligned in the same way the C |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 627 | compiler does it. It is possible to override this behavior be specifying a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 628 | :attr:`_pack_` class attribute in the subclass definition. This must be set to a |
| 629 | positive integer and specifies the maximum alignment for the fields. This is |
| 630 | what ``#pragma pack(n)`` also does in MSVC. |
| 631 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 632 | :mod:`ctypes` uses the native byte order for Structures and Unions. To build |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 633 | structures with non-native byte order, you can use one of the |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 634 | :class:`BigEndianStructure`, :class:`LittleEndianStructure`, |
| 635 | :class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These |
| 636 | classes cannot contain pointer fields. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 637 | |
| 638 | |
| 639 | .. _ctypes-bit-fields-in-structures-unions: |
| 640 | |
| 641 | Bit fields in structures and unions |
| 642 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 643 | |
| 644 | It is possible to create structures and unions containing bit fields. Bit fields |
| 645 | are only possible for integer fields, the bit width is specified as the third |
| 646 | item in the :attr:`_fields_` tuples:: |
| 647 | |
| 648 | >>> class Int(Structure): |
| 649 | ... _fields_ = [("first_16", c_int, 16), |
| 650 | ... ("second_16", c_int, 16)] |
| 651 | ... |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 652 | >>> print(Int.first_16) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 653 | <Field type=c_long, ofs=0:0, bits=16> |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 654 | >>> print(Int.second_16) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 655 | <Field type=c_long, ofs=0:16, bits=16> |
| 656 | >>> |
| 657 | |
| 658 | |
| 659 | .. _ctypes-arrays: |
| 660 | |
| 661 | Arrays |
| 662 | ^^^^^^ |
| 663 | |
| 664 | Arrays are sequences, containing a fixed number of instances of the same type. |
| 665 | |
| 666 | The recommended way to create array types is by multiplying a data type with a |
| 667 | positive integer:: |
| 668 | |
| 669 | TenPointsArrayType = POINT * 10 |
| 670 | |
Serhiy Storchaka | 6a7b3a7 | 2016-04-17 08:32:47 +0300 | [diff] [blame] | 671 | Here is an example of a somewhat artificial data type, a structure containing 4 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 672 | POINTs among other stuff:: |
| 673 | |
| 674 | >>> from ctypes import * |
| 675 | >>> class POINT(Structure): |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 676 | ... _fields_ = ("x", c_int), ("y", c_int) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 677 | ... |
| 678 | >>> class MyStruct(Structure): |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 679 | ... _fields_ = [("a", c_int), |
| 680 | ... ("b", c_float), |
| 681 | ... ("point_array", POINT * 4)] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 682 | >>> |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 683 | >>> print(len(MyStruct().point_array)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 684 | 4 |
| 685 | >>> |
| 686 | |
| 687 | Instances are created in the usual way, by calling the class:: |
| 688 | |
| 689 | arr = TenPointsArrayType() |
| 690 | for pt in arr: |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 691 | print(pt.x, pt.y) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 692 | |
| 693 | The above code print a series of ``0 0`` lines, because the array contents is |
| 694 | initialized to zeros. |
| 695 | |
| 696 | Initializers of the correct type can also be specified:: |
| 697 | |
| 698 | >>> from ctypes import * |
| 699 | >>> TenIntegers = c_int * 10 |
| 700 | >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 701 | >>> print(ii) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 702 | <c_long_Array_10 object at 0x...> |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 703 | >>> for i in ii: print(i, end=" ") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 704 | ... |
| 705 | 1 2 3 4 5 6 7 8 9 10 |
| 706 | >>> |
| 707 | |
| 708 | |
| 709 | .. _ctypes-pointers: |
| 710 | |
| 711 | Pointers |
| 712 | ^^^^^^^^ |
| 713 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 714 | Pointer instances are created by calling the :func:`pointer` function on a |
| 715 | :mod:`ctypes` type:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 716 | |
| 717 | >>> from ctypes import * |
| 718 | >>> i = c_int(42) |
| 719 | >>> pi = pointer(i) |
| 720 | >>> |
| 721 | |
Martin Panter | 34360c8 | 2016-01-29 10:12:19 +0000 | [diff] [blame] | 722 | Pointer instances have a :attr:`~_Pointer.contents` attribute which |
| 723 | returns the object to which the pointer points, the ``i`` object above:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 724 | |
| 725 | >>> pi.contents |
| 726 | c_long(42) |
| 727 | >>> |
| 728 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 729 | Note that :mod:`ctypes` does not have OOR (original object return), it constructs a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 730 | new, equivalent object each time you retrieve an attribute:: |
| 731 | |
| 732 | >>> pi.contents is i |
| 733 | False |
| 734 | >>> pi.contents is pi.contents |
| 735 | False |
| 736 | >>> |
| 737 | |
| 738 | Assigning another :class:`c_int` instance to the pointer's contents attribute |
| 739 | would cause the pointer to point to the memory location where this is stored:: |
| 740 | |
| 741 | >>> i = c_int(99) |
| 742 | >>> pi.contents = i |
| 743 | >>> pi.contents |
| 744 | c_long(99) |
| 745 | >>> |
| 746 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 747 | .. XXX Document dereferencing pointers, and that it is preferred over the |
| 748 | .contents attribute. |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 749 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 750 | Pointer instances can also be indexed with integers:: |
| 751 | |
| 752 | >>> pi[0] |
| 753 | 99 |
| 754 | >>> |
| 755 | |
| 756 | Assigning to an integer index changes the pointed to value:: |
| 757 | |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 758 | >>> print(i) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 759 | c_long(99) |
| 760 | >>> pi[0] = 22 |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 761 | >>> print(i) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 762 | c_long(22) |
| 763 | >>> |
| 764 | |
| 765 | It is also possible to use indexes different from 0, but you must know what |
| 766 | you're doing, just as in C: You can access or change arbitrary memory locations. |
| 767 | Generally you only use this feature if you receive a pointer from a C function, |
| 768 | and you *know* that the pointer actually points to an array instead of a single |
| 769 | item. |
| 770 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 771 | Behind the scenes, the :func:`pointer` function does more than simply create |
| 772 | pointer instances, it has to create pointer *types* first. This is done with the |
| 773 | :func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a |
| 774 | new type:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 775 | |
| 776 | >>> PI = POINTER(c_int) |
| 777 | >>> PI |
| 778 | <class 'ctypes.LP_c_long'> |
| 779 | >>> PI(42) |
| 780 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 781 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 782 | TypeError: expected c_long instead of int |
| 783 | >>> PI(c_int(42)) |
| 784 | <ctypes.LP_c_long object at 0x...> |
| 785 | >>> |
| 786 | |
| 787 | Calling the pointer type without an argument creates a ``NULL`` pointer. |
| 788 | ``NULL`` pointers have a ``False`` boolean value:: |
| 789 | |
| 790 | >>> null_ptr = POINTER(c_int)() |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 791 | >>> print(bool(null_ptr)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 792 | False |
| 793 | >>> |
| 794 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 795 | :mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 796 | invalid non-\ ``NULL`` pointers would crash Python):: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 797 | |
| 798 | >>> null_ptr[0] |
| 799 | Traceback (most recent call last): |
| 800 | .... |
| 801 | ValueError: NULL pointer access |
| 802 | >>> |
| 803 | |
| 804 | >>> null_ptr[0] = 1234 |
| 805 | Traceback (most recent call last): |
| 806 | .... |
| 807 | ValueError: NULL pointer access |
| 808 | >>> |
| 809 | |
| 810 | |
| 811 | .. _ctypes-type-conversions: |
| 812 | |
| 813 | Type conversions |
| 814 | ^^^^^^^^^^^^^^^^ |
| 815 | |
| 816 | Usually, ctypes does strict type checking. This means, if you have |
| 817 | ``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of |
| 818 | a member field in a structure definition, only instances of exactly the same |
| 819 | type are accepted. There are some exceptions to this rule, where ctypes accepts |
| 820 | other objects. For example, you can pass compatible array instances instead of |
| 821 | pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int:: |
| 822 | |
| 823 | >>> class Bar(Structure): |
| 824 | ... _fields_ = [("count", c_int), ("values", POINTER(c_int))] |
| 825 | ... |
| 826 | >>> bar = Bar() |
| 827 | >>> bar.values = (c_int * 3)(1, 2, 3) |
| 828 | >>> bar.count = 3 |
| 829 | >>> for i in range(bar.count): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 830 | ... print(bar.values[i]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 831 | ... |
| 832 | 1 |
| 833 | 2 |
| 834 | 3 |
| 835 | >>> |
| 836 | |
Eli Bendersky | f81de8d | 2013-03-08 05:31:54 -0800 | [diff] [blame] | 837 | In addition, if a function argument is explicitly declared to be a pointer type |
| 838 | (such as ``POINTER(c_int)``) in :attr:`argtypes`, an object of the pointed |
| 839 | type (``c_int`` in this case) can be passed to the function. ctypes will apply |
| 840 | the required :func:`byref` conversion in this case automatically. |
| 841 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 842 | To set a POINTER type field to ``NULL``, you can assign ``None``:: |
| 843 | |
| 844 | >>> bar.values = None |
| 845 | >>> |
| 846 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 847 | .. XXX list other conversions... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 848 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 849 | Sometimes you have instances of incompatible types. In C, you can cast one type |
| 850 | into another type. :mod:`ctypes` provides a :func:`cast` function which can be |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 851 | used in the same way. The ``Bar`` structure defined above accepts |
| 852 | ``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field, |
| 853 | but not instances of other types:: |
| 854 | |
| 855 | >>> bar.values = (c_byte * 4)() |
| 856 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 857 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 858 | TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance |
| 859 | >>> |
| 860 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 861 | For these cases, the :func:`cast` function is handy. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 862 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 863 | The :func:`cast` function can be used to cast a ctypes instance into a pointer |
| 864 | to a different ctypes data type. :func:`cast` takes two parameters, a ctypes |
| 865 | object that is or can be converted to a pointer of some kind, and a ctypes |
| 866 | pointer type. It returns an instance of the second argument, which references |
| 867 | the same memory block as the first argument:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 868 | |
| 869 | >>> a = (c_byte * 4)() |
| 870 | >>> cast(a, POINTER(c_int)) |
| 871 | <ctypes.LP_c_long object at ...> |
| 872 | >>> |
| 873 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 874 | So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 875 | structure:: |
| 876 | |
| 877 | >>> bar = Bar() |
| 878 | >>> bar.values = cast((c_byte * 4)(), POINTER(c_int)) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 879 | >>> print(bar.values[0]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 880 | 0 |
| 881 | >>> |
| 882 | |
| 883 | |
| 884 | .. _ctypes-incomplete-types: |
| 885 | |
| 886 | Incomplete Types |
| 887 | ^^^^^^^^^^^^^^^^ |
| 888 | |
| 889 | *Incomplete Types* are structures, unions or arrays whose members are not yet |
| 890 | specified. In C, they are specified by forward declarations, which are defined |
| 891 | later:: |
| 892 | |
| 893 | struct cell; /* forward declaration */ |
| 894 | |
Sandro Tosi | 692dba2 | 2011-08-02 16:17:14 +0200 | [diff] [blame] | 895 | struct cell { |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 896 | char *name; |
| 897 | struct cell *next; |
Sandro Tosi | 692dba2 | 2011-08-02 16:17:14 +0200 | [diff] [blame] | 898 | }; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 899 | |
| 900 | The straightforward translation into ctypes code would be this, but it does not |
| 901 | work:: |
| 902 | |
| 903 | >>> class cell(Structure): |
| 904 | ... _fields_ = [("name", c_char_p), |
| 905 | ... ("next", POINTER(cell))] |
| 906 | ... |
| 907 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 908 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 909 | File "<stdin>", line 2, in cell |
| 910 | NameError: name 'cell' is not defined |
| 911 | >>> |
| 912 | |
| 913 | because the new ``class cell`` is not available in the class statement itself. |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 914 | In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 915 | attribute later, after the class statement:: |
| 916 | |
| 917 | >>> from ctypes import * |
| 918 | >>> class cell(Structure): |
| 919 | ... pass |
| 920 | ... |
| 921 | >>> cell._fields_ = [("name", c_char_p), |
| 922 | ... ("next", POINTER(cell))] |
| 923 | >>> |
| 924 | |
| 925 | Lets try it. We create two instances of ``cell``, and let them point to each |
| 926 | other, and finally follow the pointer chain a few times:: |
| 927 | |
| 928 | >>> c1 = cell() |
| 929 | >>> c1.name = "foo" |
| 930 | >>> c2 = cell() |
| 931 | >>> c2.name = "bar" |
| 932 | >>> c1.next = pointer(c2) |
| 933 | >>> c2.next = pointer(c1) |
| 934 | >>> p = c1 |
| 935 | >>> for i in range(8): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 936 | ... print(p.name, end=" ") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 937 | ... p = p.next[0] |
| 938 | ... |
| 939 | foo bar foo bar foo bar foo bar |
Benjamin Peterson | 3e4f055 | 2008-09-02 00:31:15 +0000 | [diff] [blame] | 940 | >>> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 941 | |
| 942 | |
| 943 | .. _ctypes-callback-functions: |
| 944 | |
| 945 | Callback functions |
| 946 | ^^^^^^^^^^^^^^^^^^ |
| 947 | |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 948 | :mod:`ctypes` allows creating C callable function pointers from Python callables. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 949 | These are sometimes called *callback functions*. |
| 950 | |
Eli Bendersky | 2a1e74a | 2012-03-16 09:17:43 +0200 | [diff] [blame] | 951 | First, you must create a class for the callback function. The class knows the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 952 | calling convention, the return type, and the number and types of arguments this |
| 953 | function will receive. |
| 954 | |
Eli Bendersky | 2a1e74a | 2012-03-16 09:17:43 +0200 | [diff] [blame] | 955 | The :func:`CFUNCTYPE` factory function creates types for callback functions |
| 956 | using the ``cdecl`` calling convention. On Windows, the :func:`WINFUNCTYPE` |
| 957 | factory function creates types for callback functions using the ``stdcall`` |
| 958 | calling convention. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 959 | |
| 960 | Both of these factory functions are called with the result type as first |
| 961 | argument, and the callback functions expected argument types as the remaining |
| 962 | arguments. |
| 963 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 964 | I will present an example here which uses the standard C library's |
Eli Bendersky | 2a1e74a | 2012-03-16 09:17:43 +0200 | [diff] [blame] | 965 | :c:func:`qsort` function, that is used to sort items with the help of a callback |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 966 | function. :c:func:`qsort` will be used to sort an array of integers:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 967 | |
| 968 | >>> IntArray5 = c_int * 5 |
| 969 | >>> ia = IntArray5(5, 1, 7, 33, 99) |
| 970 | >>> qsort = libc.qsort |
| 971 | >>> qsort.restype = None |
| 972 | >>> |
| 973 | |
| 974 | :func:`qsort` must be called with a pointer to the data to sort, the number of |
| 975 | items in the data array, the size of one item, and a pointer to the comparison |
| 976 | function, the callback. The callback will then be called with two pointers to |
| 977 | items, and it must return a negative integer if the first item is smaller than |
Eli Bendersky | 2a1e74a | 2012-03-16 09:17:43 +0200 | [diff] [blame] | 978 | the second, a zero if they are equal, and a positive integer otherwise. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 979 | |
| 980 | So our callback function receives pointers to integers, and must return an |
| 981 | integer. First we create the ``type`` for the callback function:: |
| 982 | |
| 983 | >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) |
| 984 | >>> |
| 985 | |
Eli Bendersky | 2a1e74a | 2012-03-16 09:17:43 +0200 | [diff] [blame] | 986 | To get started, here is a simple callback that shows the values it gets |
| 987 | passed:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 988 | |
| 989 | >>> def py_cmp_func(a, b): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 990 | ... print("py_cmp_func", a[0], b[0]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 991 | ... return 0 |
| 992 | ... |
| 993 | >>> cmp_func = CMPFUNC(py_cmp_func) |
| 994 | >>> |
| 995 | |
Eli Bendersky | 2a1e74a | 2012-03-16 09:17:43 +0200 | [diff] [blame] | 996 | The result:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 997 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 998 | >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 999 | py_cmp_func 5 1 |
| 1000 | py_cmp_func 33 99 |
| 1001 | py_cmp_func 7 33 |
| 1002 | py_cmp_func 5 7 |
| 1003 | py_cmp_func 1 7 |
| 1004 | >>> |
| 1005 | |
Eli Bendersky | 2a1e74a | 2012-03-16 09:17:43 +0200 | [diff] [blame] | 1006 | Now we can actually compare the two items and return a useful result:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1007 | |
| 1008 | >>> def py_cmp_func(a, b): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 1009 | ... print("py_cmp_func", a[0], b[0]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1010 | ... return a[0] - b[0] |
| 1011 | ... |
| 1012 | >>> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1013 | >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX |
| 1014 | py_cmp_func 5 1 |
| 1015 | py_cmp_func 33 99 |
| 1016 | py_cmp_func 7 33 |
| 1017 | py_cmp_func 1 7 |
| 1018 | py_cmp_func 5 7 |
| 1019 | >>> |
| 1020 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1021 | As we can easily check, our array is sorted now:: |
| 1022 | |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 1023 | >>> for i in ia: print(i, end=" ") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1024 | ... |
| 1025 | 1 5 7 33 99 |
| 1026 | >>> |
| 1027 | |
Andrés Delfino | 379e9d6 | 2018-07-13 09:50:20 -0300 | [diff] [blame] | 1028 | The function factories can be used as decorator factories, so we may as well |
| 1029 | write:: |
| 1030 | |
| 1031 | >>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) |
| 1032 | ... def py_cmp_func(a, b): |
| 1033 | ... print("py_cmp_func", a[0], b[0]) |
| 1034 | ... return a[0] - b[0] |
| 1035 | ... |
| 1036 | >>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func) |
| 1037 | py_cmp_func 5 1 |
| 1038 | py_cmp_func 33 99 |
| 1039 | py_cmp_func 7 33 |
| 1040 | py_cmp_func 1 7 |
| 1041 | py_cmp_func 5 7 |
| 1042 | >>> |
| 1043 | |
Benjamin Peterson | 1cfe009 | 2014-01-20 00:10:23 -0500 | [diff] [blame] | 1044 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1045 | |
Benjamin Peterson | 1cfe009 | 2014-01-20 00:10:23 -0500 | [diff] [blame] | 1046 | Make sure you keep references to :func:`CFUNCTYPE` objects as long as they |
| 1047 | are used from C code. :mod:`ctypes` doesn't, and if you don't, they may be |
| 1048 | garbage collected, crashing your program when a callback is made. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1049 | |
Benjamin Peterson | 1cfe009 | 2014-01-20 00:10:23 -0500 | [diff] [blame] | 1050 | Also, note that if the callback function is called in a thread created |
| 1051 | outside of Python's control (e.g. by the foreign code that calls the |
| 1052 | callback), ctypes creates a new dummy Python thread on every invocation. This |
| 1053 | behavior is correct for most purposes, but it means that values stored with |
Georg Brandl | 6b4c847 | 2014-10-30 22:26:26 +0100 | [diff] [blame] | 1054 | :class:`threading.local` will *not* survive across different callbacks, even when |
Benjamin Peterson | 1cfe009 | 2014-01-20 00:10:23 -0500 | [diff] [blame] | 1055 | those calls are made from the same C thread. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1056 | |
| 1057 | .. _ctypes-accessing-values-exported-from-dlls: |
| 1058 | |
| 1059 | Accessing values exported from dlls |
| 1060 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1061 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1062 | Some shared libraries not only export functions, they also export variables. An |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1063 | example in the Python library itself is the :c:data:`Py_OptimizeFlag`, an integer |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1064 | set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1065 | startup. |
| 1066 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1067 | :mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1068 | the type. *pythonapi* is a predefined symbol giving access to the Python C |
| 1069 | api:: |
| 1070 | |
| 1071 | >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag") |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 1072 | >>> print(opt_flag) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1073 | c_long(0) |
| 1074 | >>> |
| 1075 | |
| 1076 | If the interpreter would have been started with :option:`-O`, the sample would |
| 1077 | have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been |
| 1078 | specified. |
| 1079 | |
| 1080 | An extended example which also demonstrates the use of pointers accesses the |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1081 | :c:data:`PyImport_FrozenModules` pointer exported by Python. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1082 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1083 | Quoting the docs for that value: |
| 1084 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1085 | This pointer is initialized to point to an array of :c:type:`struct _frozen` |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1086 | records, terminated by one whose members are all *NULL* or zero. When a frozen |
| 1087 | module is imported, it is searched in this table. Third-party code could play |
| 1088 | tricks with this to provide a dynamically created collection of frozen modules. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1089 | |
| 1090 | So manipulating this pointer could even prove useful. To restrict the example |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1091 | size, we show only how this table can be read with :mod:`ctypes`:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1092 | |
| 1093 | >>> from ctypes import * |
| 1094 | >>> |
| 1095 | >>> class struct_frozen(Structure): |
| 1096 | ... _fields_ = [("name", c_char_p), |
| 1097 | ... ("code", POINTER(c_ubyte)), |
| 1098 | ... ("size", c_int)] |
| 1099 | ... |
| 1100 | >>> |
| 1101 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1102 | We have defined the :c:type:`struct _frozen` data type, so we can get the pointer |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1103 | to the table:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1104 | |
| 1105 | >>> FrozenTable = POINTER(struct_frozen) |
| 1106 | >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules") |
| 1107 | >>> |
| 1108 | |
| 1109 | Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we |
| 1110 | can iterate over it, but we just have to make sure that our loop terminates, |
| 1111 | because pointers have no size. Sooner or later it would probably crash with an |
| 1112 | access violation or whatever, so it's better to break out of the loop when we |
| 1113 | hit the NULL entry:: |
| 1114 | |
| 1115 | >>> for item in table: |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 1116 | ... if item.name is None: |
| 1117 | ... break |
Martin Panter | f47a400 | 2016-05-15 00:13:04 +0000 | [diff] [blame] | 1118 | ... print(item.name.decode("ascii"), item.size) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1119 | ... |
Martin Panter | f47a400 | 2016-05-15 00:13:04 +0000 | [diff] [blame] | 1120 | _frozen_importlib 31764 |
| 1121 | _frozen_importlib_external 41499 |
| 1122 | __hello__ 161 |
| 1123 | __phello__ -161 |
| 1124 | __phello__.spam 161 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1125 | >>> |
| 1126 | |
| 1127 | The fact that standard Python has a frozen module and a frozen package |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1128 | (indicated by the negative size member) is not well known, it is only used for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1129 | testing. Try it out with ``import __hello__`` for example. |
| 1130 | |
| 1131 | |
| 1132 | .. _ctypes-surprises: |
| 1133 | |
| 1134 | Surprises |
| 1135 | ^^^^^^^^^ |
| 1136 | |
R David Murray | a2959ce | 2012-10-31 10:50:27 -0400 | [diff] [blame] | 1137 | There are some edges in :mod:`ctypes` where you might expect something other |
| 1138 | than what actually happens. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1139 | |
| 1140 | Consider the following example:: |
| 1141 | |
| 1142 | >>> from ctypes import * |
| 1143 | >>> class POINT(Structure): |
| 1144 | ... _fields_ = ("x", c_int), ("y", c_int) |
| 1145 | ... |
| 1146 | >>> class RECT(Structure): |
| 1147 | ... _fields_ = ("a", POINT), ("b", POINT) |
| 1148 | ... |
| 1149 | >>> p1 = POINT(1, 2) |
| 1150 | >>> p2 = POINT(3, 4) |
| 1151 | >>> rc = RECT(p1, p2) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 1152 | >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1153 | 1 2 3 4 |
| 1154 | >>> # now swap the two points |
| 1155 | >>> rc.a, rc.b = rc.b, rc.a |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 1156 | >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1157 | 3 4 3 4 |
| 1158 | >>> |
| 1159 | |
| 1160 | Hm. We certainly expected the last statement to print ``3 4 1 2``. What |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1161 | happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1162 | |
| 1163 | >>> temp0, temp1 = rc.b, rc.a |
| 1164 | >>> rc.a = temp0 |
| 1165 | >>> rc.b = temp1 |
| 1166 | >>> |
| 1167 | |
| 1168 | Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of |
| 1169 | the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer |
| 1170 | contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the |
| 1171 | contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have |
| 1172 | the expected effect. |
| 1173 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1174 | Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays |
| 1175 | doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1176 | the root-object's underlying buffer. |
| 1177 | |
| 1178 | Another example that may behave different from what one would expect is this:: |
| 1179 | |
| 1180 | >>> s = c_char_p() |
| 1181 | >>> s.value = "abc def ghi" |
| 1182 | >>> s.value |
| 1183 | 'abc def ghi' |
| 1184 | >>> s.value is s.value |
| 1185 | False |
| 1186 | >>> |
| 1187 | |
| 1188 | Why is it printing ``False``? ctypes instances are objects containing a memory |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1189 | block plus some :term:`descriptor`\s accessing the contents of the memory. |
| 1190 | Storing a Python object in the memory block does not store the object itself, |
| 1191 | instead the ``contents`` of the object is stored. Accessing the contents again |
| 1192 | constructs a new Python object each time! |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1193 | |
| 1194 | |
| 1195 | .. _ctypes-variable-sized-data-types: |
| 1196 | |
| 1197 | Variable-sized data types |
| 1198 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1199 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1200 | :mod:`ctypes` provides some support for variable-sized arrays and structures. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1201 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1202 | The :func:`resize` function can be used to resize the memory buffer of an |
| 1203 | existing ctypes object. The function takes the object as first argument, and |
| 1204 | the requested size in bytes as the second argument. The memory block cannot be |
| 1205 | made smaller than the natural memory block specified by the objects type, a |
| 1206 | :exc:`ValueError` is raised if this is tried:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1207 | |
| 1208 | >>> short_array = (c_short * 4)() |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 1209 | >>> print(sizeof(short_array)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1210 | 8 |
| 1211 | >>> resize(short_array, 4) |
| 1212 | Traceback (most recent call last): |
| 1213 | ... |
| 1214 | ValueError: minimum size is 8 |
| 1215 | >>> resize(short_array, 32) |
| 1216 | >>> sizeof(short_array) |
| 1217 | 32 |
| 1218 | >>> sizeof(type(short_array)) |
| 1219 | 8 |
| 1220 | >>> |
| 1221 | |
| 1222 | This is nice and fine, but how would one access the additional elements |
| 1223 | contained in this array? Since the type still only knows about 4 elements, we |
| 1224 | get errors accessing other elements:: |
| 1225 | |
| 1226 | >>> short_array[:] |
| 1227 | [0, 0, 0, 0] |
| 1228 | >>> short_array[7] |
| 1229 | Traceback (most recent call last): |
| 1230 | ... |
| 1231 | IndexError: invalid index |
| 1232 | >>> |
| 1233 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1234 | Another way to use variable-sized data types with :mod:`ctypes` is to use the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1235 | dynamic nature of Python, and (re-)define the data type after the required size |
| 1236 | is already known, on a case by case basis. |
| 1237 | |
| 1238 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1239 | .. _ctypes-ctypes-reference: |
| 1240 | |
| 1241 | ctypes reference |
| 1242 | ---------------- |
| 1243 | |
| 1244 | |
| 1245 | .. _ctypes-finding-shared-libraries: |
| 1246 | |
| 1247 | Finding shared libraries |
| 1248 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1249 | |
| 1250 | When programming in a compiled language, shared libraries are accessed when |
| 1251 | compiling/linking a program, and when the program is run. |
| 1252 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1253 | The purpose of the :func:`find_library` function is to locate a library in a way |
Vinay Sajip | 82df3b3 | 2016-08-17 16:20:07 +0100 | [diff] [blame] | 1254 | similar to what the compiler or runtime loader does (on platforms with several |
| 1255 | versions of a shared library the most recent should be loaded), while the ctypes |
| 1256 | library loaders act like when a program is run, and call the runtime loader |
| 1257 | directly. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1258 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1259 | The :mod:`ctypes.util` module provides a function which can help to determine |
| 1260 | the library to load. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1261 | |
| 1262 | |
| 1263 | .. data:: find_library(name) |
Benjamin Peterson | 5c6d787 | 2009-02-06 02:40:07 +0000 | [diff] [blame] | 1264 | :module: ctypes.util |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1265 | :noindex: |
| 1266 | |
| 1267 | Try to find a library and return a pathname. *name* is the library name without |
| 1268 | any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this |
Martin Panter | 5c67933 | 2016-10-30 04:20:17 +0000 | [diff] [blame] | 1269 | is the form used for the posix linker option :option:`!-l`). If no library can |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1270 | be found, returns ``None``. |
| 1271 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1272 | The exact functionality is system dependent. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1273 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1274 | On Linux, :func:`find_library` tries to run external programs |
Vinay Sajip | 82df3b3 | 2016-08-17 16:20:07 +0100 | [diff] [blame] | 1275 | (``/sbin/ldconfig``, ``gcc``, ``objdump`` and ``ld``) to find the library file. |
| 1276 | It returns the filename of the library file. |
| 1277 | |
| 1278 | .. versionchanged:: 3.6 |
| 1279 | On Linux, the value of the environment variable ``LD_LIBRARY_PATH`` is used |
| 1280 | when searching for libraries, if a library cannot be found by any other means. |
| 1281 | |
| 1282 | Here are some examples:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1283 | |
| 1284 | >>> from ctypes.util import find_library |
| 1285 | >>> find_library("m") |
| 1286 | 'libm.so.6' |
| 1287 | >>> find_library("c") |
| 1288 | 'libc.so.6' |
| 1289 | >>> find_library("bz2") |
| 1290 | 'libbz2.so.1.0' |
| 1291 | >>> |
| 1292 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1293 | On OS X, :func:`find_library` tries several predefined naming schemes and paths |
| 1294 | to locate the library, and returns a full pathname if successful:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1295 | |
| 1296 | >>> from ctypes.util import find_library |
| 1297 | >>> find_library("c") |
| 1298 | '/usr/lib/libc.dylib' |
| 1299 | >>> find_library("m") |
| 1300 | '/usr/lib/libm.dylib' |
| 1301 | >>> find_library("bz2") |
| 1302 | '/usr/lib/libbz2.dylib' |
| 1303 | >>> find_library("AGL") |
| 1304 | '/System/Library/Frameworks/AGL.framework/AGL' |
| 1305 | >>> |
| 1306 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1307 | On Windows, :func:`find_library` searches along the system search path, and |
| 1308 | returns the full pathname, but since there is no predefined naming scheme a call |
| 1309 | like ``find_library("c")`` will fail and return ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1310 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1311 | If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine |
Ned Deily | ea3cfc5 | 2013-05-20 14:29:44 -0700 | [diff] [blame] | 1312 | the shared library name at development time, and hardcode that into the wrapper |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1313 | module instead of using :func:`find_library` to locate the library at runtime. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1314 | |
| 1315 | |
| 1316 | .. _ctypes-loading-shared-libraries: |
| 1317 | |
| 1318 | Loading shared libraries |
| 1319 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1320 | |
Zachary Ware | 46a78bc | 2016-01-01 12:22:16 -0600 | [diff] [blame] | 1321 | There are several ways to load shared libraries into the Python process. One |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1322 | way is to instantiate one of the following classes: |
| 1323 | |
| 1324 | |
Steve Dower | 2438cdf | 2019-03-29 16:37:16 -0700 | [diff] [blame] | 1325 | .. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1326 | |
| 1327 | Instances of this class represent loaded shared libraries. Functions in these |
| 1328 | libraries use the standard C calling convention, and are assumed to return |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1329 | :c:type:`int`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1330 | |
| 1331 | |
Steve Dower | 2438cdf | 2019-03-29 16:37:16 -0700 | [diff] [blame] | 1332 | .. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1333 | |
| 1334 | Windows only: Instances of this class represent loaded shared libraries, |
| 1335 | functions in these libraries use the ``stdcall`` calling convention, and are |
| 1336 | assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT` |
| 1337 | values contain information specifying whether the function call failed or |
| 1338 | succeeded, together with additional error code. If the return value signals a |
Antoine Pitrou | 442ee03 | 2011-10-12 18:53:23 +0200 | [diff] [blame] | 1339 | failure, an :class:`OSError` is automatically raised. |
| 1340 | |
| 1341 | .. versionchanged:: 3.3 |
| 1342 | :exc:`WindowsError` used to be raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1343 | |
| 1344 | |
Steve Dower | 2438cdf | 2019-03-29 16:37:16 -0700 | [diff] [blame] | 1345 | .. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1346 | |
| 1347 | Windows only: Instances of this class represent loaded shared libraries, |
| 1348 | functions in these libraries use the ``stdcall`` calling convention, and are |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1349 | assumed to return :c:type:`int` by default. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1350 | |
| 1351 | On Windows CE only the standard calling convention is used, for convenience the |
| 1352 | :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this |
| 1353 | platform. |
| 1354 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1355 | The Python :term:`global interpreter lock` is released before calling any |
| 1356 | function exported by these libraries, and reacquired afterwards. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1357 | |
| 1358 | |
| 1359 | .. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None) |
| 1360 | |
| 1361 | Instances of this class behave like :class:`CDLL` instances, except that the |
| 1362 | Python GIL is *not* released during the function call, and after the function |
| 1363 | execution the Python error flag is checked. If the error flag is set, a Python |
| 1364 | exception is raised. |
| 1365 | |
| 1366 | Thus, this is only useful to call Python C api functions directly. |
| 1367 | |
| 1368 | All these classes can be instantiated by calling them with at least one |
| 1369 | argument, the pathname of the shared library. If you have an existing handle to |
Benjamin Peterson | 4469d0c | 2008-11-30 22:46:23 +0000 | [diff] [blame] | 1370 | an already loaded shared library, it can be passed as the ``handle`` named |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1371 | parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1372 | function is used to load the library into the process, and to get a handle to |
| 1373 | it. |
| 1374 | |
| 1375 | The *mode* parameter can be used to specify how the library is loaded. For |
Martin Panter | f18a5da | 2016-09-27 05:10:40 +0000 | [diff] [blame] | 1376 | details, consult the :manpage:`dlopen(3)` manpage. On Windows, *mode* is |
| 1377 | ignored. On posix systems, RTLD_NOW is always added, and is not |
| 1378 | configurable. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1379 | |
Serhiy Storchaka | 4adf01c | 2016-10-19 18:30:05 +0300 | [diff] [blame] | 1380 | The *use_errno* parameter, when set to true, enables a ctypes mechanism that |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1381 | allows accessing the system :data:`errno` error number in a safe way. |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1382 | :mod:`ctypes` maintains a thread-local copy of the systems :data:`errno` |
| 1383 | variable; if you call foreign functions created with ``use_errno=True`` then the |
| 1384 | :data:`errno` value before the function call is swapped with the ctypes private |
| 1385 | copy, the same happens immediately after the function call. |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1386 | |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1387 | The function :func:`ctypes.get_errno` returns the value of the ctypes private |
| 1388 | copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy |
| 1389 | to a new value and returns the former value. |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1390 | |
Serhiy Storchaka | 4adf01c | 2016-10-19 18:30:05 +0300 | [diff] [blame] | 1391 | The *use_last_error* parameter, when set to true, enables the same mechanism for |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1392 | the Windows error code which is managed by the :func:`GetLastError` and |
| 1393 | :func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and |
| 1394 | :func:`ctypes.set_last_error` are used to request and change the ctypes private |
| 1395 | copy of the windows error code. |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1396 | |
Steve Dower | 2438cdf | 2019-03-29 16:37:16 -0700 | [diff] [blame] | 1397 | The *winmode* parameter is used on Windows to specify how the library is loaded |
| 1398 | (since *mode* is ignored). It takes any value that is valid for the Win32 API |
| 1399 | ``LoadLibraryEx`` flags parameter. When omitted, the default is to use the flags |
| 1400 | that result in the most secure DLL load to avoiding issues such as DLL |
| 1401 | hijacking. Passing the full path to the DLL is the safest way to ensure the |
| 1402 | correct library and dependencies are loaded. |
| 1403 | |
| 1404 | .. versionchanged:: 3.8 |
| 1405 | Added *winmode* parameter. |
| 1406 | |
| 1407 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1408 | .. data:: RTLD_GLOBAL |
| 1409 | :noindex: |
| 1410 | |
| 1411 | Flag to use as *mode* parameter. On platforms where this flag is not available, |
| 1412 | it is defined as the integer zero. |
| 1413 | |
| 1414 | |
| 1415 | .. data:: RTLD_LOCAL |
| 1416 | :noindex: |
| 1417 | |
| 1418 | Flag to use as *mode* parameter. On platforms where this is not available, it |
| 1419 | is the same as *RTLD_GLOBAL*. |
| 1420 | |
| 1421 | |
| 1422 | .. data:: DEFAULT_MODE |
| 1423 | :noindex: |
| 1424 | |
| 1425 | The default mode which is used to load shared libraries. On OSX 10.3, this is |
| 1426 | *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*. |
| 1427 | |
R David Murray | 9db487b | 2014-10-04 18:25:07 -0400 | [diff] [blame] | 1428 | Instances of these classes have no public methods. Functions exported by the |
| 1429 | shared library can be accessed as attributes or by index. Please note that |
| 1430 | accessing the function through an attribute caches the result and therefore |
| 1431 | accessing it repeatedly returns the same object each time. On the other hand, |
Marco Buttu | b2a7c2f | 2017-03-02 12:02:43 +0100 | [diff] [blame] | 1432 | accessing it through an index returns a new object each time:: |
R David Murray | 9db487b | 2014-10-04 18:25:07 -0400 | [diff] [blame] | 1433 | |
Marco Buttu | b2a7c2f | 2017-03-02 12:02:43 +0100 | [diff] [blame] | 1434 | >>> from ctypes import CDLL |
| 1435 | >>> libc = CDLL("libc.so.6") # On Linux |
R David Murray | 9db487b | 2014-10-04 18:25:07 -0400 | [diff] [blame] | 1436 | >>> libc.time == libc.time |
| 1437 | True |
| 1438 | >>> libc['time'] == libc['time'] |
| 1439 | False |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1440 | |
| 1441 | The following public attributes are available, their name starts with an |
| 1442 | underscore to not clash with exported function names: |
| 1443 | |
| 1444 | |
| 1445 | .. attribute:: PyDLL._handle |
| 1446 | |
| 1447 | The system handle used to access the library. |
| 1448 | |
| 1449 | |
| 1450 | .. attribute:: PyDLL._name |
| 1451 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1452 | The name of the library passed in the constructor. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1453 | |
| 1454 | Shared libraries can also be loaded by using one of the prefabricated objects, |
| 1455 | which are instances of the :class:`LibraryLoader` class, either by calling the |
| 1456 | :meth:`LoadLibrary` method, or by retrieving the library as attribute of the |
| 1457 | loader instance. |
| 1458 | |
| 1459 | |
| 1460 | .. class:: LibraryLoader(dlltype) |
| 1461 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1462 | Class which loads shared libraries. *dlltype* should be one of the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1463 | :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types. |
| 1464 | |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1465 | :meth:`__getattr__` has special behavior: It allows loading a shared library by |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1466 | accessing it as attribute of a library loader instance. The result is cached, |
| 1467 | so repeated attribute accesses return the same library each time. |
| 1468 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1469 | .. method:: LoadLibrary(name) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1470 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1471 | Load a shared library into the process and return it. This method always |
| 1472 | returns a new instance of the library. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1473 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1474 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1475 | These prefabricated library loaders are available: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1476 | |
| 1477 | .. data:: cdll |
| 1478 | :noindex: |
| 1479 | |
| 1480 | Creates :class:`CDLL` instances. |
| 1481 | |
| 1482 | |
| 1483 | .. data:: windll |
| 1484 | :noindex: |
| 1485 | |
| 1486 | Windows only: Creates :class:`WinDLL` instances. |
| 1487 | |
| 1488 | |
| 1489 | .. data:: oledll |
| 1490 | :noindex: |
| 1491 | |
| 1492 | Windows only: Creates :class:`OleDLL` instances. |
| 1493 | |
| 1494 | |
| 1495 | .. data:: pydll |
| 1496 | :noindex: |
| 1497 | |
| 1498 | Creates :class:`PyDLL` instances. |
| 1499 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1500 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1501 | For accessing the C Python api directly, a ready-to-use Python shared library |
| 1502 | object is available: |
| 1503 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1504 | .. data:: pythonapi |
| 1505 | :noindex: |
| 1506 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1507 | An instance of :class:`PyDLL` that exposes Python C API functions as |
| 1508 | attributes. Note that all these functions are assumed to return C |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1509 | :c:type:`int`, which is of course not always the truth, so you have to assign |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1510 | the correct :attr:`restype` attribute to use these functions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1511 | |
Steve Dower | b82e17e | 2019-05-23 08:45:22 -0700 | [diff] [blame] | 1512 | .. audit-event:: ctypes.dlopen name |
| 1513 | |
| 1514 | Loading a library through any of these objects raises an |
| 1515 | :ref:`auditing event <auditing>` ``ctypes.dlopen`` with string argument |
| 1516 | ``name``, the name used to load the library. |
| 1517 | |
| 1518 | .. audit-event:: ctypes.dlsym "library name" |
| 1519 | |
| 1520 | Accessing a function on a loaded library raises an auditing event |
| 1521 | ``ctypes.dlsym`` with arguments ``library`` (the library object) and ``name`` |
| 1522 | (the symbol's name as a string or integer). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1523 | |
| 1524 | .. _ctypes-foreign-functions: |
| 1525 | |
| 1526 | Foreign functions |
| 1527 | ^^^^^^^^^^^^^^^^^ |
| 1528 | |
| 1529 | As explained in the previous section, foreign functions can be accessed as |
| 1530 | attributes of loaded shared libraries. The function objects created in this way |
| 1531 | by default accept any number of arguments, accept any ctypes data instances as |
| 1532 | arguments, and return the default result type specified by the library loader. |
| 1533 | They are instances of a private class: |
| 1534 | |
| 1535 | |
| 1536 | .. class:: _FuncPtr |
| 1537 | |
| 1538 | Base class for C callable foreign functions. |
| 1539 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1540 | Instances of foreign functions are also C compatible data types; they |
| 1541 | represent C function pointers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1542 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1543 | This behavior can be customized by assigning to special attributes of the |
| 1544 | foreign function object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1545 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1546 | .. attribute:: restype |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1547 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1548 | Assign a ctypes type to specify the result type of the foreign function. |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1549 | Use ``None`` for :c:type:`void`, a function not returning anything. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1550 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1551 | It is possible to assign a callable Python object that is not a ctypes |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1552 | type, in this case the function is assumed to return a C :c:type:`int`, and |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1553 | the callable will be called with this integer, allowing further |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1554 | processing or error checking. Using this is deprecated, for more flexible |
| 1555 | post processing or error checking use a ctypes data type as |
| 1556 | :attr:`restype` and assign a callable to the :attr:`errcheck` attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1557 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1558 | .. attribute:: argtypes |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1559 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1560 | Assign a tuple of ctypes types to specify the argument types that the |
| 1561 | function accepts. Functions using the ``stdcall`` calling convention can |
| 1562 | only be called with the same number of arguments as the length of this |
| 1563 | tuple; functions using the C calling convention accept additional, |
| 1564 | unspecified arguments as well. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1565 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1566 | When a foreign function is called, each actual argument is passed to the |
| 1567 | :meth:`from_param` class method of the items in the :attr:`argtypes` |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1568 | tuple, this method allows adapting the actual argument to an object that |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1569 | the foreign function accepts. For example, a :class:`c_char_p` item in |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1570 | the :attr:`argtypes` tuple will convert a string passed as argument into |
| 1571 | a bytes object using ctypes conversion rules. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1572 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1573 | New: It is now possible to put items in argtypes which are not ctypes |
| 1574 | types, but each item must have a :meth:`from_param` method which returns a |
| 1575 | value usable as argument (integer, string, ctypes instance). This allows |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1576 | defining adapters that can adapt custom objects as function parameters. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1577 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1578 | .. attribute:: errcheck |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1579 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 1580 | Assign a Python function or another callable to this attribute. The |
| 1581 | callable will be called with three or more arguments: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1582 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1583 | .. function:: callable(result, func, arguments) |
| 1584 | :noindex: |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1585 | :module: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1586 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1587 | *result* is what the foreign function returns, as specified by the |
| 1588 | :attr:`restype` attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1589 | |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1590 | *func* is the foreign function object itself, this allows reusing the |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1591 | same callable object to check or post process the results of several |
| 1592 | functions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1593 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1594 | *arguments* is a tuple containing the parameters originally passed to |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1595 | the function call, this allows specializing the behavior on the |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1596 | arguments used. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1597 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1598 | The object that this function returns will be returned from the |
| 1599 | foreign function call, but it can also check the result value |
| 1600 | and raise an exception if the foreign function call failed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1601 | |
| 1602 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1603 | .. exception:: ArgumentError |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1604 | |
| 1605 | This exception is raised when a foreign function call cannot convert one of the |
| 1606 | passed arguments. |
| 1607 | |
| 1608 | |
| 1609 | .. _ctypes-function-prototypes: |
| 1610 | |
| 1611 | Function prototypes |
| 1612 | ^^^^^^^^^^^^^^^^^^^ |
| 1613 | |
| 1614 | Foreign functions can also be created by instantiating function prototypes. |
| 1615 | Function prototypes are similar to function prototypes in C; they describe a |
| 1616 | function (return type, argument types, calling convention) without defining an |
| 1617 | implementation. The factory functions must be called with the desired result |
Andrés Delfino | 379e9d6 | 2018-07-13 09:50:20 -0300 | [diff] [blame] | 1618 | type and the argument types of the function, and can be used as decorator |
| 1619 | factories, and as such, be applied to functions through the ``@wrapper`` syntax. |
| 1620 | See :ref:`ctypes-callback-functions` for examples. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1621 | |
| 1622 | |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1623 | .. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1624 | |
| 1625 | The returned function prototype creates functions that use the standard C |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1626 | calling convention. The function will release the GIL during the call. If |
Serhiy Storchaka | 4adf01c | 2016-10-19 18:30:05 +0300 | [diff] [blame] | 1627 | *use_errno* is set to true, the ctypes private copy of the system |
Georg Brandl | a6053b4 | 2009-09-01 08:11:14 +0000 | [diff] [blame] | 1628 | :data:`errno` variable is exchanged with the real :data:`errno` value before |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1629 | and after the call; *use_last_error* does the same for the Windows error |
| 1630 | code. |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1631 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1632 | |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1633 | .. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1634 | |
| 1635 | Windows only: The returned function prototype creates functions that use the |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1636 | ``stdcall`` calling convention, except on Windows CE where |
| 1637 | :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will |
| 1638 | release the GIL during the call. *use_errno* and *use_last_error* have the |
| 1639 | same meaning as above. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1640 | |
| 1641 | |
| 1642 | .. function:: PYFUNCTYPE(restype, *argtypes) |
| 1643 | |
| 1644 | The returned function prototype creates functions that use the Python calling |
| 1645 | convention. The function will *not* release the GIL during the call. |
| 1646 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1647 | Function prototypes created by these factory functions can be instantiated in |
| 1648 | different ways, depending on the type and number of the parameters in the call: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1649 | |
| 1650 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1651 | .. function:: prototype(address) |
| 1652 | :noindex: |
| 1653 | :module: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1654 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1655 | Returns a foreign function at the specified address which must be an integer. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1656 | |
| 1657 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1658 | .. function:: prototype(callable) |
| 1659 | :noindex: |
| 1660 | :module: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1661 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1662 | Create a C callable function (a callback function) from a Python *callable*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1663 | |
| 1664 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1665 | .. function:: prototype(func_spec[, paramflags]) |
| 1666 | :noindex: |
| 1667 | :module: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1668 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1669 | Returns a foreign function exported by a shared library. *func_spec* must |
| 1670 | be a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of |
| 1671 | the exported function as string, or the ordinal of the exported function |
| 1672 | as small integer. The second item is the shared library instance. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1673 | |
| 1674 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1675 | .. function:: prototype(vtbl_index, name[, paramflags[, iid]]) |
| 1676 | :noindex: |
| 1677 | :module: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1678 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1679 | Returns a foreign function that will call a COM method. *vtbl_index* is |
| 1680 | the index into the virtual function table, a small non-negative |
| 1681 | integer. *name* is name of the COM method. *iid* is an optional pointer to |
| 1682 | the interface identifier which is used in extended error reporting. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1683 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1684 | COM methods use a special calling convention: They require a pointer to |
| 1685 | the COM interface as first argument, in addition to those parameters that |
| 1686 | are specified in the :attr:`argtypes` tuple. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1687 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1688 | The optional *paramflags* parameter creates foreign function wrappers with much |
| 1689 | more functionality than the features described above. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1690 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1691 | *paramflags* must be a tuple of the same length as :attr:`argtypes`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1692 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1693 | Each item in this tuple contains further information about a parameter, it must |
| 1694 | be a tuple containing one, two, or three items. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1695 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1696 | The first item is an integer containing a combination of direction |
| 1697 | flags for the parameter: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1698 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1699 | 1 |
| 1700 | Specifies an input parameter to the function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1701 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1702 | 2 |
| 1703 | Output parameter. The foreign function fills in a value. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1704 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1705 | 4 |
| 1706 | Input parameter which defaults to the integer zero. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1707 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1708 | The optional second item is the parameter name as string. If this is specified, |
| 1709 | the foreign function can be called with named parameters. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1710 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1711 | The optional third item is the default value for this parameter. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1712 | |
Berker Peksag | de55c61 | 2016-09-28 17:07:01 +0300 | [diff] [blame] | 1713 | This example demonstrates how to wrap the Windows ``MessageBoxW`` function so |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1714 | that it supports default parameters and named arguments. The C declaration from |
| 1715 | the windows header file is this:: |
| 1716 | |
| 1717 | WINUSERAPI int WINAPI |
Berker Peksag | de55c61 | 2016-09-28 17:07:01 +0300 | [diff] [blame] | 1718 | MessageBoxW( |
Serhiy Storchaka | a4d170d | 2013-12-23 18:20:51 +0200 | [diff] [blame] | 1719 | HWND hWnd, |
Berker Peksag | de55c61 | 2016-09-28 17:07:01 +0300 | [diff] [blame] | 1720 | LPCWSTR lpText, |
| 1721 | LPCWSTR lpCaption, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1722 | UINT uType); |
| 1723 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1724 | Here is the wrapping with :mod:`ctypes`:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1725 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1726 | >>> from ctypes import c_int, WINFUNCTYPE, windll |
Berker Peksag | de55c61 | 2016-09-28 17:07:01 +0300 | [diff] [blame] | 1727 | >>> from ctypes.wintypes import HWND, LPCWSTR, UINT |
| 1728 | >>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT) |
| 1729 | >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0) |
| 1730 | >>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1731 | |
Berker Peksag | de55c61 | 2016-09-28 17:07:01 +0300 | [diff] [blame] | 1732 | The ``MessageBox`` foreign function can now be called in these ways:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1733 | |
| 1734 | >>> MessageBox() |
| 1735 | >>> MessageBox(text="Spam, spam, spam") |
| 1736 | >>> MessageBox(flags=2, text="foo bar") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1737 | |
| 1738 | A second example demonstrates output parameters. The win32 ``GetWindowRect`` |
| 1739 | function retrieves the dimensions of a specified window by copying them into |
| 1740 | ``RECT`` structure that the caller has to supply. Here is the C declaration:: |
| 1741 | |
| 1742 | WINUSERAPI BOOL WINAPI |
| 1743 | GetWindowRect( |
| 1744 | HWND hWnd, |
| 1745 | LPRECT lpRect); |
| 1746 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1747 | Here is the wrapping with :mod:`ctypes`:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1748 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1749 | >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError |
| 1750 | >>> from ctypes.wintypes import BOOL, HWND, RECT |
| 1751 | >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT)) |
| 1752 | >>> paramflags = (1, "hwnd"), (2, "lprect") |
| 1753 | >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags) |
| 1754 | >>> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1755 | |
| 1756 | Functions with output parameters will automatically return the output parameter |
| 1757 | value if there is a single one, or a tuple containing the output parameter |
| 1758 | values when there are more than one, so the GetWindowRect function now returns a |
| 1759 | RECT instance, when called. |
| 1760 | |
| 1761 | Output parameters can be combined with the :attr:`errcheck` protocol to do |
| 1762 | further output processing and error checking. The win32 ``GetWindowRect`` api |
| 1763 | function returns a ``BOOL`` to signal success or failure, so this function could |
| 1764 | do the error checking, and raises an exception when the api call failed:: |
| 1765 | |
| 1766 | >>> def errcheck(result, func, args): |
| 1767 | ... if not result: |
| 1768 | ... raise WinError() |
| 1769 | ... return args |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1770 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1771 | >>> GetWindowRect.errcheck = errcheck |
| 1772 | >>> |
| 1773 | |
| 1774 | If the :attr:`errcheck` function returns the argument tuple it receives |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1775 | unchanged, :mod:`ctypes` continues the normal processing it does on the output |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1776 | parameters. If you want to return a tuple of window coordinates instead of a |
| 1777 | ``RECT`` instance, you can retrieve the fields in the function and return them |
| 1778 | instead, the normal processing will no longer take place:: |
| 1779 | |
| 1780 | >>> def errcheck(result, func, args): |
| 1781 | ... if not result: |
| 1782 | ... raise WinError() |
| 1783 | ... rc = args[1] |
| 1784 | ... return rc.left, rc.top, rc.bottom, rc.right |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1785 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1786 | >>> GetWindowRect.errcheck = errcheck |
| 1787 | >>> |
| 1788 | |
| 1789 | |
| 1790 | .. _ctypes-utility-functions: |
| 1791 | |
| 1792 | Utility functions |
| 1793 | ^^^^^^^^^^^^^^^^^ |
| 1794 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1795 | .. function:: addressof(obj) |
| 1796 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1797 | Returns the address of the memory buffer as integer. *obj* must be an |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1798 | instance of a ctypes type. |
| 1799 | |
| 1800 | |
| 1801 | .. function:: alignment(obj_or_type) |
| 1802 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1803 | Returns the alignment requirements of a ctypes type. *obj_or_type* must be a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1804 | ctypes type or instance. |
| 1805 | |
| 1806 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1807 | .. function:: byref(obj[, offset]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1808 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1809 | Returns a light-weight pointer to *obj*, which must be an instance of a |
| 1810 | ctypes type. *offset* defaults to zero, and must be an integer that will be |
| 1811 | added to the internal pointer value. |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1812 | |
| 1813 | ``byref(obj, offset)`` corresponds to this C code:: |
| 1814 | |
| 1815 | (((char *)&obj) + offset) |
| 1816 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1817 | The returned object can only be used as a foreign function call parameter. |
| 1818 | It behaves similar to ``pointer(obj)``, but the construction is a lot faster. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1819 | |
| 1820 | |
| 1821 | .. function:: cast(obj, type) |
| 1822 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1823 | This function is similar to the cast operator in C. It returns a new instance |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1824 | of *type* which points to the same memory block as *obj*. *type* must be a |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1825 | pointer type, and *obj* must be an object that can be interpreted as a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1826 | pointer. |
| 1827 | |
| 1828 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1829 | .. function:: create_string_buffer(init_or_size, size=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1830 | |
| 1831 | This function creates a mutable character buffer. The returned object is a |
| 1832 | ctypes array of :class:`c_char`. |
| 1833 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1834 | *init_or_size* must be an integer which specifies the size of the array, or a |
| 1835 | bytes object which will be used to initialize the array items. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1836 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1837 | If a bytes object is specified as first argument, the buffer is made one item |
| 1838 | larger than its length so that the last element in the array is a NUL |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1839 | termination character. An integer can be passed as second argument which allows |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1840 | specifying the size of the array if the length of the bytes should not be used. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1841 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1842 | |
| 1843 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1844 | .. function:: create_unicode_buffer(init_or_size, size=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1845 | |
| 1846 | This function creates a mutable unicode character buffer. The returned object is |
| 1847 | a ctypes array of :class:`c_wchar`. |
| 1848 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1849 | *init_or_size* must be an integer which specifies the size of the array, or a |
| 1850 | string which will be used to initialize the array items. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1851 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1852 | If a string is specified as first argument, the buffer is made one item |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1853 | larger than the length of the string so that the last element in the array is a |
| 1854 | NUL termination character. An integer can be passed as second argument which |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1855 | allows specifying the size of the array if the length of the string should not |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1856 | be used. |
| 1857 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1858 | |
| 1859 | |
| 1860 | .. function:: DllCanUnloadNow() |
| 1861 | |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1862 | Windows only: This function is a hook which allows implementing in-process |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1863 | COM servers with ctypes. It is called from the DllCanUnloadNow function that |
| 1864 | the _ctypes extension dll exports. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1865 | |
| 1866 | |
| 1867 | .. function:: DllGetClassObject() |
| 1868 | |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 1869 | Windows only: This function is a hook which allows implementing in-process |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1870 | COM servers with ctypes. It is called from the DllGetClassObject function |
| 1871 | that the ``_ctypes`` extension dll exports. |
| 1872 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1873 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1874 | .. function:: find_library(name) |
| 1875 | :module: ctypes.util |
| 1876 | |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1877 | Try to find a library and return a pathname. *name* is the library name |
Benjamin Peterson | 28d88b4 | 2009-01-09 03:03:23 +0000 | [diff] [blame] | 1878 | without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version |
Martin Panter | 5c67933 | 2016-10-30 04:20:17 +0000 | [diff] [blame] | 1879 | number (this is the form used for the posix linker option :option:`!-l`). If |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1880 | no library can be found, returns ``None``. |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1881 | |
| 1882 | The exact functionality is system dependent. |
| 1883 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1884 | |
| 1885 | .. function:: find_msvcrt() |
| 1886 | :module: ctypes.util |
| 1887 | |
Georg Brandl | 8ed75cd | 2014-10-31 10:25:48 +0100 | [diff] [blame] | 1888 | Windows only: return the filename of the VC runtime library used by Python, |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1889 | and by the extension modules. If the name of the library cannot be |
| 1890 | determined, ``None`` is returned. |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1891 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1892 | If you need to free memory, for example, allocated by an extension module |
| 1893 | with a call to the ``free(void *)``, it is important that you use the |
| 1894 | function in the same library that allocated the memory. |
| 1895 | |
Thomas Heller | 2fadaa2 | 2008-06-16 19:56:33 +0000 | [diff] [blame] | 1896 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1897 | .. function:: FormatError([code]) |
| 1898 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1899 | Windows only: Returns a textual description of the error code *code*. If no |
| 1900 | error code is specified, the last error code is used by calling the Windows |
| 1901 | api function GetLastError. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1902 | |
| 1903 | |
| 1904 | .. function:: GetLastError() |
| 1905 | |
| 1906 | Windows only: Returns the last error code set by Windows in the calling thread. |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1907 | This function calls the Windows `GetLastError()` function directly, |
| 1908 | it does not return the ctypes-private copy of the error code. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1909 | |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1910 | .. function:: get_errno() |
| 1911 | |
| 1912 | Returns the current value of the ctypes-private copy of the system |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1913 | :data:`errno` variable in the calling thread. |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1914 | |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1915 | .. function:: get_last_error() |
| 1916 | |
| 1917 | Windows only: returns the current value of the ctypes-private copy of the system |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1918 | :data:`LastError` variable in the calling thread. |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1919 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1920 | .. function:: memmove(dst, src, count) |
| 1921 | |
| 1922 | Same as the standard C memmove library function: copies *count* bytes from |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1923 | *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can |
| 1924 | be converted to pointers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1925 | |
| 1926 | |
| 1927 | .. function:: memset(dst, c, count) |
| 1928 | |
| 1929 | Same as the standard C memset library function: fills the memory block at |
| 1930 | address *dst* with *count* bytes of value *c*. *dst* must be an integer |
| 1931 | specifying an address, or a ctypes instance. |
| 1932 | |
| 1933 | |
| 1934 | .. function:: POINTER(type) |
| 1935 | |
| 1936 | This factory function creates and returns a new ctypes pointer type. Pointer |
Serhiy Storchaka | 6a7b3a7 | 2016-04-17 08:32:47 +0300 | [diff] [blame] | 1937 | types are cached and reused internally, so calling this function repeatedly is |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1938 | cheap. *type* must be a ctypes type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1939 | |
| 1940 | |
| 1941 | .. function:: pointer(obj) |
| 1942 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1943 | This function creates a new pointer instance, pointing to *obj*. The returned |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1944 | object is of the type ``POINTER(type(obj))``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1945 | |
| 1946 | Note: If you just want to pass a pointer to an object to a foreign function |
| 1947 | call, you should use ``byref(obj)`` which is much faster. |
| 1948 | |
| 1949 | |
| 1950 | .. function:: resize(obj, size) |
| 1951 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1952 | This function resizes the internal memory buffer of *obj*, which must be an |
| 1953 | instance of a ctypes type. It is not possible to make the buffer smaller |
| 1954 | than the native size of the objects type, as given by ``sizeof(type(obj))``, |
| 1955 | but it is possible to enlarge the buffer. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1956 | |
| 1957 | |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1958 | .. function:: set_errno(value) |
| 1959 | |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1960 | Set the current value of the ctypes-private copy of the system :data:`errno` |
| 1961 | variable in the calling thread to *value* and return the previous value. |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1962 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1963 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1964 | |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1965 | .. function:: set_last_error(value) |
| 1966 | |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1967 | Windows only: set the current value of the ctypes-private copy of the system |
| 1968 | :data:`LastError` variable in the calling thread to *value* and return the |
| 1969 | previous value. |
Thomas Heller | b795f528 | 2008-06-10 15:26:58 +0000 | [diff] [blame] | 1970 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1971 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1972 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1973 | .. function:: sizeof(obj_or_type) |
| 1974 | |
Ezio Melotti | e459750 | 2013-10-21 04:41:40 +0300 | [diff] [blame] | 1975 | Returns the size in bytes of a ctypes type or instance memory buffer. |
| 1976 | Does the same as the C ``sizeof`` operator. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1977 | |
| 1978 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1979 | .. function:: string_at(address, size=-1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1980 | |
Ezio Melotti | e130a52 | 2011-10-19 10:58:56 +0300 | [diff] [blame] | 1981 | This function returns the C string starting at memory address *address* as a bytes |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1982 | object. If size is specified, it is used as size, otherwise the string is assumed |
| 1983 | to be zero-terminated. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1984 | |
| 1985 | |
| 1986 | .. function:: WinError(code=None, descr=None) |
| 1987 | |
| 1988 | Windows only: this function is probably the worst-named thing in ctypes. It |
Antoine Pitrou | 442ee03 | 2011-10-12 18:53:23 +0200 | [diff] [blame] | 1989 | creates an instance of OSError. If *code* is not specified, |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 1990 | ``GetLastError`` is called to determine the error code. If *descr* is not |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1991 | specified, :func:`FormatError` is called to get a textual description of the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1992 | error. |
| 1993 | |
Antoine Pitrou | 442ee03 | 2011-10-12 18:53:23 +0200 | [diff] [blame] | 1994 | .. versionchanged:: 3.3 |
| 1995 | An instance of :exc:`WindowsError` used to be created. |
| 1996 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1997 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 1998 | .. function:: wstring_at(address, size=-1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1999 | |
| 2000 | This function returns the wide character string starting at memory address |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2001 | *address* as a string. If *size* is specified, it is used as the number of |
| 2002 | characters of the string, otherwise the string is assumed to be |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2003 | zero-terminated. |
| 2004 | |
| 2005 | |
| 2006 | .. _ctypes-data-types: |
| 2007 | |
| 2008 | Data types |
| 2009 | ^^^^^^^^^^ |
| 2010 | |
| 2011 | |
| 2012 | .. class:: _CData |
| 2013 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2014 | This non-public class is the common base class of all ctypes data types. |
| 2015 | Among other things, all ctypes type instances contain a memory block that |
| 2016 | hold C compatible data; the address of the memory block is returned by the |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 2017 | :func:`addressof` helper function. Another instance variable is exposed as |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2018 | :attr:`_objects`; this contains other Python objects that need to be kept |
| 2019 | alive in case the memory block contains pointers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2020 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2021 | Common methods of ctypes data types, these are all class methods (to be |
| 2022 | exact, they are methods of the :term:`metaclass`): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2023 | |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 2024 | .. method:: _CData.from_buffer(source[, offset]) |
| 2025 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2026 | This method returns a ctypes instance that shares the buffer of the |
| 2027 | *source* object. The *source* object must support the writeable buffer |
| 2028 | interface. The optional *offset* parameter specifies an offset into the |
| 2029 | source buffer in bytes; the default is zero. If the source buffer is not |
| 2030 | large enough a :exc:`ValueError` is raised. |
| 2031 | |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 2032 | |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 2033 | .. method:: _CData.from_buffer_copy(source[, offset]) |
| 2034 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2035 | This method creates a ctypes instance, copying the buffer from the |
| 2036 | *source* object buffer which must be readable. The optional *offset* |
| 2037 | parameter specifies an offset into the source buffer in bytes; the default |
| 2038 | is zero. If the source buffer is not large enough a :exc:`ValueError` is |
| 2039 | raised. |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 2040 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2041 | .. method:: from_address(address) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2042 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2043 | This method returns a ctypes type instance using the memory specified by |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2044 | *address* which must be an integer. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2045 | |
Steve Dower | b82e17e | 2019-05-23 08:45:22 -0700 | [diff] [blame] | 2046 | .. audit-event:: ctypes.cdata address |
| 2047 | |
| 2048 | This method, and others that indirectly call this method, raises an |
Steve Dower | 60419a7 | 2019-06-24 08:42:54 -0700 | [diff] [blame^] | 2049 | :ref:`auditing event <auditing>` ``ctypes.cdata`` with argument |
Steve Dower | b82e17e | 2019-05-23 08:45:22 -0700 | [diff] [blame] | 2050 | ``address``. |
| 2051 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2052 | .. method:: from_param(obj) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2053 | |
Benjamin Peterson | 3e4f055 | 2008-09-02 00:31:15 +0000 | [diff] [blame] | 2054 | This method adapts *obj* to a ctypes type. It is called with the actual |
| 2055 | object used in a foreign function call when the type is present in the |
| 2056 | foreign function's :attr:`argtypes` tuple; it must return an object that |
| 2057 | can be used as a function call parameter. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2058 | |
Benjamin Peterson | 3e4f055 | 2008-09-02 00:31:15 +0000 | [diff] [blame] | 2059 | All ctypes data types have a default implementation of this classmethod |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 2060 | that normally returns *obj* if that is an instance of the type. Some |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2061 | types accept other objects as well. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2062 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2063 | .. method:: in_dll(library, name) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2064 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2065 | This method returns a ctypes type instance exported by a shared |
| 2066 | library. *name* is the name of the symbol that exports the data, *library* |
| 2067 | is the loaded shared library. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2068 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2069 | Common instance variables of ctypes data types: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2070 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2071 | .. attribute:: _b_base_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2072 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2073 | Sometimes ctypes data instances do not own the memory block they contain, |
| 2074 | instead they share part of the memory block of a base object. The |
| 2075 | :attr:`_b_base_` read-only member is the root ctypes object that owns the |
| 2076 | memory block. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2077 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2078 | .. attribute:: _b_needsfree_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2079 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2080 | This read-only variable is true when the ctypes data instance has |
| 2081 | allocated the memory block itself, false otherwise. |
| 2082 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2083 | .. attribute:: _objects |
| 2084 | |
| 2085 | This member is either ``None`` or a dictionary containing Python objects |
| 2086 | that need to be kept alive so that the memory block contents is kept |
| 2087 | valid. This object is only exposed for debugging; never modify the |
| 2088 | contents of this dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2089 | |
| 2090 | |
| 2091 | .. _ctypes-fundamental-data-types-2: |
| 2092 | |
| 2093 | Fundamental data types |
| 2094 | ^^^^^^^^^^^^^^^^^^^^^^ |
| 2095 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2096 | .. class:: _SimpleCData |
| 2097 | |
Benjamin Peterson | 35e8c46 | 2008-04-24 02:34:53 +0000 | [diff] [blame] | 2098 | This non-public class is the base class of all fundamental ctypes data |
| 2099 | types. It is mentioned here because it contains the common attributes of the |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 2100 | fundamental ctypes data types. :class:`_SimpleCData` is a subclass of |
| 2101 | :class:`_CData`, so it inherits their methods and attributes. ctypes data |
| 2102 | types that are not and do not contain pointers can now be pickled. |
Thomas Heller | 13394e9 | 2008-02-13 20:40:44 +0000 | [diff] [blame] | 2103 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2104 | Instances have a single attribute: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2105 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2106 | .. attribute:: value |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2107 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2108 | This attribute contains the actual value of the instance. For integer and |
| 2109 | pointer types, it is an integer, for character types, it is a single |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 2110 | character bytes object or string, for character pointer types it is a |
| 2111 | Python bytes object or string. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2112 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2113 | When the ``value`` attribute is retrieved from a ctypes instance, usually |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 2114 | a new object is returned each time. :mod:`ctypes` does *not* implement |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2115 | original object return, always a new object is constructed. The same is |
| 2116 | true for all other ctypes object instances. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2117 | |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 2118 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2119 | Fundamental data types, when returned as foreign function call results, or, for |
| 2120 | example, by retrieving structure field members or array items, are transparently |
| 2121 | converted to native Python types. In other words, if a foreign function has a |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 2122 | :attr:`restype` of :class:`c_char_p`, you will always receive a Python bytes |
| 2123 | object, *not* a :class:`c_char_p` instance. |
| 2124 | |
| 2125 | .. XXX above is false, it actually returns a Unicode string |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2126 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 2127 | Subclasses of fundamental data types do *not* inherit this behavior. So, if a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2128 | foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will |
| 2129 | receive an instance of this subclass from the function call. Of course, you can |
| 2130 | get the value of the pointer by accessing the ``value`` attribute. |
| 2131 | |
| 2132 | These are the fundamental ctypes data types: |
| 2133 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2134 | .. class:: c_byte |
| 2135 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2136 | Represents the C :c:type:`signed char` datatype, and interprets the value as |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2137 | small integer. The constructor accepts an optional integer initializer; no |
| 2138 | overflow checking is done. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2139 | |
| 2140 | |
| 2141 | .. class:: c_char |
| 2142 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2143 | Represents the C :c:type:`char` datatype, and interprets the value as a single |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2144 | character. The constructor accepts an optional string initializer, the |
| 2145 | length of the string must be exactly one character. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2146 | |
| 2147 | |
| 2148 | .. class:: c_char_p |
| 2149 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2150 | Represents the C :c:type:`char *` datatype when it points to a zero-terminated |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2151 | string. For a general character pointer that may also point to binary data, |
| 2152 | ``POINTER(c_char)`` must be used. The constructor accepts an integer |
| 2153 | address, or a bytes object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2154 | |
| 2155 | |
| 2156 | .. class:: c_double |
| 2157 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2158 | Represents the C :c:type:`double` datatype. The constructor accepts an |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2159 | optional float initializer. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2160 | |
| 2161 | |
Thomas Wouters | 89d996e | 2007-09-08 17:39:28 +0000 | [diff] [blame] | 2162 | .. class:: c_longdouble |
| 2163 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2164 | Represents the C :c:type:`long double` datatype. The constructor accepts an |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2165 | optional float initializer. On platforms where ``sizeof(long double) == |
| 2166 | sizeof(double)`` it is an alias to :class:`c_double`. |
Thomas Wouters | 89d996e | 2007-09-08 17:39:28 +0000 | [diff] [blame] | 2167 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2168 | .. class:: c_float |
| 2169 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2170 | Represents the C :c:type:`float` datatype. The constructor accepts an |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2171 | optional float initializer. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2172 | |
| 2173 | |
| 2174 | .. class:: c_int |
| 2175 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2176 | Represents the C :c:type:`signed int` datatype. The constructor accepts an |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2177 | optional integer initializer; no overflow checking is done. On platforms |
| 2178 | where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2179 | |
| 2180 | |
| 2181 | .. class:: c_int8 |
| 2182 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2183 | Represents the C 8-bit :c:type:`signed int` datatype. Usually an alias for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2184 | :class:`c_byte`. |
| 2185 | |
| 2186 | |
| 2187 | .. class:: c_int16 |
| 2188 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2189 | Represents the C 16-bit :c:type:`signed int` datatype. Usually an alias for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2190 | :class:`c_short`. |
| 2191 | |
| 2192 | |
| 2193 | .. class:: c_int32 |
| 2194 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2195 | Represents the C 32-bit :c:type:`signed int` datatype. Usually an alias for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2196 | :class:`c_int`. |
| 2197 | |
| 2198 | |
| 2199 | .. class:: c_int64 |
| 2200 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2201 | Represents the C 64-bit :c:type:`signed int` datatype. Usually an alias for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2202 | :class:`c_longlong`. |
| 2203 | |
| 2204 | |
| 2205 | .. class:: c_long |
| 2206 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2207 | Represents the C :c:type:`signed long` datatype. The constructor accepts an |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2208 | optional integer initializer; no overflow checking is done. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2209 | |
| 2210 | |
| 2211 | .. class:: c_longlong |
| 2212 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2213 | Represents the C :c:type:`signed long long` datatype. The constructor accepts |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2214 | an optional integer initializer; no overflow checking is done. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2215 | |
| 2216 | |
| 2217 | .. class:: c_short |
| 2218 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2219 | Represents the C :c:type:`signed short` datatype. The constructor accepts an |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2220 | optional integer initializer; no overflow checking is done. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2221 | |
| 2222 | |
| 2223 | .. class:: c_size_t |
| 2224 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2225 | Represents the C :c:type:`size_t` datatype. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2226 | |
| 2227 | |
Gregory P. Smith | 1a53091 | 2010-03-01 04:59:27 +0000 | [diff] [blame] | 2228 | .. class:: c_ssize_t |
| 2229 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2230 | Represents the C :c:type:`ssize_t` datatype. |
Gregory P. Smith | 1a53091 | 2010-03-01 04:59:27 +0000 | [diff] [blame] | 2231 | |
| 2232 | .. versionadded:: 3.2 |
| 2233 | |
| 2234 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2235 | .. class:: c_ubyte |
| 2236 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2237 | Represents the C :c:type:`unsigned char` datatype, it interprets the value as |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2238 | small integer. The constructor accepts an optional integer initializer; no |
| 2239 | overflow checking is done. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2240 | |
| 2241 | |
| 2242 | .. class:: c_uint |
| 2243 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2244 | Represents the C :c:type:`unsigned int` datatype. The constructor accepts an |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2245 | optional integer initializer; no overflow checking is done. On platforms |
| 2246 | where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2247 | |
| 2248 | |
| 2249 | .. class:: c_uint8 |
| 2250 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2251 | Represents the C 8-bit :c:type:`unsigned int` datatype. Usually an alias for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2252 | :class:`c_ubyte`. |
| 2253 | |
| 2254 | |
| 2255 | .. class:: c_uint16 |
| 2256 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2257 | Represents the C 16-bit :c:type:`unsigned int` datatype. Usually an alias for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2258 | :class:`c_ushort`. |
| 2259 | |
| 2260 | |
| 2261 | .. class:: c_uint32 |
| 2262 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2263 | Represents the C 32-bit :c:type:`unsigned int` datatype. Usually an alias for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2264 | :class:`c_uint`. |
| 2265 | |
| 2266 | |
| 2267 | .. class:: c_uint64 |
| 2268 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2269 | Represents the C 64-bit :c:type:`unsigned int` datatype. Usually an alias for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2270 | :class:`c_ulonglong`. |
| 2271 | |
| 2272 | |
| 2273 | .. class:: c_ulong |
| 2274 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2275 | Represents the C :c:type:`unsigned long` datatype. The constructor accepts an |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2276 | optional integer initializer; no overflow checking is done. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2277 | |
| 2278 | |
| 2279 | .. class:: c_ulonglong |
| 2280 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2281 | Represents the C :c:type:`unsigned long long` datatype. The constructor |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2282 | accepts an optional integer initializer; no overflow checking is done. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2283 | |
| 2284 | |
| 2285 | .. class:: c_ushort |
| 2286 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2287 | Represents the C :c:type:`unsigned short` datatype. The constructor accepts |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2288 | an optional integer initializer; no overflow checking is done. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2289 | |
| 2290 | |
| 2291 | .. class:: c_void_p |
| 2292 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2293 | Represents the C :c:type:`void *` type. The value is represented as integer. |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2294 | The constructor accepts an optional integer initializer. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2295 | |
| 2296 | |
| 2297 | .. class:: c_wchar |
| 2298 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2299 | Represents the C :c:type:`wchar_t` datatype, and interprets the value as a |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2300 | single character unicode string. The constructor accepts an optional string |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2301 | initializer, the length of the string must be exactly one character. |
| 2302 | |
| 2303 | |
| 2304 | .. class:: c_wchar_p |
| 2305 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2306 | Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2307 | zero-terminated wide character string. The constructor accepts an integer |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2308 | address, or a string. |
| 2309 | |
| 2310 | |
| 2311 | .. class:: c_bool |
| 2312 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2313 | Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from |
Serhiy Storchaka | fbc1c26 | 2013-11-29 12:17:13 +0200 | [diff] [blame] | 2314 | C99). Its value can be ``True`` or ``False``, and the constructor accepts any object |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2315 | that has a truth value. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2316 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2317 | |
| 2318 | .. class:: HRESULT |
| 2319 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2320 | Windows only: Represents a :c:type:`HRESULT` value, which contains success or |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2321 | error information for a function or method call. |
| 2322 | |
| 2323 | |
| 2324 | .. class:: py_object |
| 2325 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2326 | Represents the C :c:type:`PyObject *` datatype. Calling this without an |
| 2327 | argument creates a ``NULL`` :c:type:`PyObject *` pointer. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2328 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2329 | The :mod:`ctypes.wintypes` module provides quite some other Windows specific |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 2330 | data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`. Some |
| 2331 | useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2332 | |
| 2333 | |
| 2334 | .. _ctypes-structured-data-types: |
| 2335 | |
| 2336 | Structured data types |
| 2337 | ^^^^^^^^^^^^^^^^^^^^^ |
| 2338 | |
| 2339 | |
| 2340 | .. class:: Union(*args, **kw) |
| 2341 | |
| 2342 | Abstract base class for unions in native byte order. |
| 2343 | |
| 2344 | |
| 2345 | .. class:: BigEndianStructure(*args, **kw) |
| 2346 | |
| 2347 | Abstract base class for structures in *big endian* byte order. |
| 2348 | |
| 2349 | |
| 2350 | .. class:: LittleEndianStructure(*args, **kw) |
| 2351 | |
| 2352 | Abstract base class for structures in *little endian* byte order. |
| 2353 | |
| 2354 | Structures with non-native byte order cannot contain pointer type fields, or any |
| 2355 | other data types containing pointer type fields. |
| 2356 | |
| 2357 | |
| 2358 | .. class:: Structure(*args, **kw) |
| 2359 | |
| 2360 | Abstract base class for structures in *native* byte order. |
| 2361 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2362 | Concrete structure and union types must be created by subclassing one of these |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 2363 | types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2364 | create :term:`descriptor`\s which allow reading and writing the fields by direct |
| 2365 | attribute accesses. These are the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2366 | |
| 2367 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2368 | .. attribute:: _fields_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2369 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2370 | A sequence defining the structure fields. The items must be 2-tuples or |
| 2371 | 3-tuples. The first item is the name of the field, the second item |
| 2372 | specifies the type of the field; it can be any ctypes data type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2373 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2374 | For integer type fields like :class:`c_int`, a third optional item can be |
| 2375 | given. It must be a small positive integer defining the bit width of the |
| 2376 | field. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2377 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2378 | Field names must be unique within one structure or union. This is not |
| 2379 | checked, only one field can be accessed when names are repeated. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2380 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2381 | It is possible to define the :attr:`_fields_` class variable *after* the |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 2382 | class statement that defines the Structure subclass, this allows creating |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2383 | data types that directly or indirectly reference themselves:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2384 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2385 | class List(Structure): |
| 2386 | pass |
| 2387 | List._fields_ = [("pnext", POINTER(List)), |
| 2388 | ... |
| 2389 | ] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2390 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2391 | The :attr:`_fields_` class variable must, however, be defined before the |
Georg Brandl | 8d8f197 | 2009-06-08 13:27:23 +0000 | [diff] [blame] | 2392 | type is first used (an instance is created, :func:`sizeof` is called on it, |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2393 | and so on). Later assignments to the :attr:`_fields_` class variable will |
| 2394 | raise an AttributeError. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2395 | |
Yavor Konstantinov | 133fc89 | 2019-05-15 08:02:13 -0700 | [diff] [blame] | 2396 | It is possible to define sub-subclasses of structure types, they inherit |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2397 | the fields of the base class plus the :attr:`_fields_` defined in the |
| 2398 | sub-subclass, if any. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2399 | |
| 2400 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2401 | .. attribute:: _pack_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2402 | |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 2403 | An optional small integer that allows overriding the alignment of |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2404 | structure fields in the instance. :attr:`_pack_` must already be defined |
| 2405 | when :attr:`_fields_` is assigned, otherwise it will have no effect. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2406 | |
| 2407 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2408 | .. attribute:: _anonymous_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2409 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2410 | An optional sequence that lists the names of unnamed (anonymous) fields. |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2411 | :attr:`_anonymous_` must be already defined when :attr:`_fields_` is |
| 2412 | assigned, otherwise it will have no effect. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2413 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2414 | The fields listed in this variable must be structure or union type fields. |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 2415 | :mod:`ctypes` will create descriptors in the structure type that allows |
| 2416 | accessing the nested fields directly, without the need to create the |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2417 | structure or union field. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2418 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2419 | Here is an example type (Windows):: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2420 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2421 | class _U(Union): |
| 2422 | _fields_ = [("lptdesc", POINTER(TYPEDESC)), |
| 2423 | ("lpadesc", POINTER(ARRAYDESC)), |
| 2424 | ("hreftype", HREFTYPE)] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2425 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2426 | class TYPEDESC(Structure): |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 2427 | _anonymous_ = ("u",) |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2428 | _fields_ = [("u", _U), |
| 2429 | ("vt", VARTYPE)] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2430 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2431 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2432 | The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field |
| 2433 | specifies which one of the union fields is valid. Since the ``u`` field |
| 2434 | is defined as anonymous field, it is now possible to access the members |
| 2435 | directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` |
| 2436 | are equivalent, but the former is faster since it does not need to create |
| 2437 | a temporary union instance:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2438 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 2439 | td = TYPEDESC() |
| 2440 | td.vt = VT_PTR |
| 2441 | td.lptdesc = POINTER(some_type) |
| 2442 | td.u.lptdesc = POINTER(some_type) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2443 | |
Yavor Konstantinov | 133fc89 | 2019-05-15 08:02:13 -0700 | [diff] [blame] | 2444 | It is possible to define sub-subclasses of structures, they inherit the |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2445 | fields of the base class. If the subclass definition has a separate |
| 2446 | :attr:`_fields_` variable, the fields specified in this are appended to the |
| 2447 | fields of the base class. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2448 | |
Georg Brandl | 1d837bc | 2009-12-29 11:24:00 +0000 | [diff] [blame] | 2449 | Structure and union constructors accept both positional and keyword |
| 2450 | arguments. Positional arguments are used to initialize member fields in the |
| 2451 | same order as they are appear in :attr:`_fields_`. Keyword arguments in the |
| 2452 | constructor are interpreted as attribute assignments, so they will initialize |
| 2453 | :attr:`_fields_` with the same name, or create new attributes for names not |
| 2454 | present in :attr:`_fields_`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2455 | |
| 2456 | |
| 2457 | .. _ctypes-arrays-pointers: |
| 2458 | |
| 2459 | Arrays and pointers |
| 2460 | ^^^^^^^^^^^^^^^^^^^ |
| 2461 | |
Martin Panter | 34360c8 | 2016-01-29 10:12:19 +0000 | [diff] [blame] | 2462 | .. class:: Array(\*args) |
| 2463 | |
| 2464 | Abstract base class for arrays. |
| 2465 | |
| 2466 | The recommended way to create concrete array types is by multiplying any |
| 2467 | :mod:`ctypes` data type with a positive integer. Alternatively, you can subclass |
| 2468 | this type and define :attr:`_length_` and :attr:`_type_` class variables. |
| 2469 | Array elements can be read and written using standard |
| 2470 | subscript and slice accesses; for slice reads, the resulting object is |
| 2471 | *not* itself an :class:`Array`. |
| 2472 | |
| 2473 | |
| 2474 | .. attribute:: _length_ |
| 2475 | |
| 2476 | A positive integer specifying the number of elements in the array. |
| 2477 | Out-of-range subscripts result in an :exc:`IndexError`. Will be |
| 2478 | returned by :func:`len`. |
| 2479 | |
| 2480 | |
| 2481 | .. attribute:: _type_ |
| 2482 | |
| 2483 | Specifies the type of each element in the array. |
| 2484 | |
| 2485 | |
| 2486 | Array subclass constructors accept positional arguments, used to |
| 2487 | initialize the elements in order. |
| 2488 | |
| 2489 | |
| 2490 | .. class:: _Pointer |
| 2491 | |
| 2492 | Private, abstract base class for pointers. |
| 2493 | |
| 2494 | Concrete pointer types are created by calling :func:`POINTER` with the |
| 2495 | type that will be pointed to; this is done automatically by |
| 2496 | :func:`pointer`. |
| 2497 | |
| 2498 | If a pointer points to an array, its elements can be read and |
| 2499 | written using standard subscript and slice accesses. Pointer objects |
| 2500 | have no size, so :func:`len` will raise :exc:`TypeError`. Negative |
| 2501 | subscripts will read from the memory *before* the pointer (as in C), and |
| 2502 | out-of-range subscripts will probably crash with an access violation (if |
| 2503 | you're lucky). |
| 2504 | |
| 2505 | |
| 2506 | .. attribute:: _type_ |
| 2507 | |
| 2508 | Specifies the type pointed to. |
| 2509 | |
| 2510 | .. attribute:: contents |
| 2511 | |
| 2512 | Returns the object to which to pointer points. Assigning to this |
| 2513 | attribute changes the pointer to point to the assigned object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2514 | |