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