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