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