/Doc/library/ctypes.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 2482 lines · 1769 code · 713 blank · 0 comment · 0 complexity · 6bd179d674b269a799687de33ef31e0a MD5 · raw file

Large files are truncated click here to view the full file

  1. :mod:`ctypes` --- A foreign function library for Python.
  2. ========================================================
  3. .. module:: ctypes
  4. :synopsis: A foreign function library for Python.
  5. .. moduleauthor:: Thomas Heller <theller@python.net>
  6. .. versionadded:: 2.5
  7. ``ctypes`` is a foreign function library for Python. It provides C compatible
  8. data types, and allows calling functions in DLLs or shared libraries. It can be
  9. used to wrap these libraries in pure Python.
  10. .. _ctypes-ctypes-tutorial:
  11. ctypes tutorial
  12. ---------------
  13. Note: The code samples in this tutorial use ``doctest`` to make sure that they
  14. actually work. Since some code samples behave differently under Linux, Windows,
  15. or Mac OS X, they contain doctest directives in comments.
  16. Note: Some code samples reference the ctypes :class:`c_int` type. This type is
  17. an alias for the :class:`c_long` type on 32-bit systems. So, you should not be
  18. confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
  19. they are actually the same type.
  20. .. _ctypes-loading-dynamic-link-libraries:
  21. Loading dynamic link libraries
  22. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  23. ``ctypes`` exports the *cdll*, and on Windows *windll* and *oledll*
  24. objects, for loading dynamic link libraries.
  25. You load libraries by accessing them as attributes of these objects. *cdll*
  26. loads libraries which export functions using the standard ``cdecl`` calling
  27. convention, while *windll* libraries call functions using the ``stdcall``
  28. calling convention. *oledll* also uses the ``stdcall`` calling convention, and
  29. assumes the functions return a Windows :class:`HRESULT` error code. The error
  30. code is used to automatically raise a :class:`WindowsError` exception when
  31. the function call fails.
  32. Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
  33. library containing most standard C functions, and uses the cdecl calling
  34. convention::
  35. >>> from ctypes import *
  36. >>> print windll.kernel32 # doctest: +WINDOWS
  37. <WinDLL 'kernel32', handle ... at ...>
  38. >>> print cdll.msvcrt # doctest: +WINDOWS
  39. <CDLL 'msvcrt', handle ... at ...>
  40. >>> libc = cdll.msvcrt # doctest: +WINDOWS
  41. >>>
  42. Windows appends the usual ``.dll`` file suffix automatically.
  43. On Linux, it is required to specify the filename *including* the extension to
  44. load a library, so attribute access can not be used to load libraries. Either the
  45. :meth:`LoadLibrary` method of the dll loaders should be used, or you should load
  46. the library by creating an instance of CDLL by calling the constructor::
  47. >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
  48. <CDLL 'libc.so.6', handle ... at ...>
  49. >>> libc = CDLL("libc.so.6") # doctest: +LINUX
  50. >>> libc # doctest: +LINUX
  51. <CDLL 'libc.so.6', handle ... at ...>
  52. >>>
  53. .. XXX Add section for Mac OS X.
  54. .. _ctypes-accessing-functions-from-loaded-dlls:
  55. Accessing functions from loaded dlls
  56. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  57. Functions are accessed as attributes of dll objects::
  58. >>> from ctypes import *
  59. >>> libc.printf
  60. <_FuncPtr object at 0x...>
  61. >>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
  62. <_FuncPtr object at 0x...>
  63. >>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS
  64. Traceback (most recent call last):
  65. File "<stdin>", line 1, in ?
  66. File "ctypes.py", line 239, in __getattr__
  67. func = _StdcallFuncPtr(name, self)
  68. AttributeError: function 'MyOwnFunction' not found
  69. >>>
  70. Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
  71. as well as UNICODE versions of a function. The UNICODE version is exported with
  72. an ``W`` appended to the name, while the ANSI version is exported with an ``A``
  73. appended to the name. The win32 ``GetModuleHandle`` function, which returns a
  74. *module handle* for a given module name, has the following C prototype, and a
  75. macro is used to expose one of them as ``GetModuleHandle`` depending on whether
  76. UNICODE is defined or not::
  77. /* ANSI version */
  78. HMODULE GetModuleHandleA(LPCSTR lpModuleName);
  79. /* UNICODE version */
  80. HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
  81. *windll* does not try to select one of them by magic, you must access the
  82. version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
  83. explicitly, and then call it with strings or unicode strings
  84. respectively.
  85. Sometimes, dlls export functions with names which aren't valid Python
  86. identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use ``getattr``
  87. to retrieve the function::
  88. >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
  89. <_FuncPtr object at 0x...>
  90. >>>
  91. On Windows, some dlls export functions not by name but by ordinal. These
  92. functions can be accessed by indexing the dll object with the ordinal number::
  93. >>> cdll.kernel32[1] # doctest: +WINDOWS
  94. <_FuncPtr object at 0x...>
  95. >>> cdll.kernel32[0] # doctest: +WINDOWS
  96. Traceback (most recent call last):
  97. File "<stdin>", line 1, in ?
  98. File "ctypes.py", line 310, in __getitem__
  99. func = _StdcallFuncPtr(name, self)
  100. AttributeError: function ordinal 0 not found
  101. >>>
  102. .. _ctypes-calling-functions:
  103. Calling functions
  104. ^^^^^^^^^^^^^^^^^
  105. You can call these functions like any other Python callable. This example uses
  106. the ``time()`` function, which returns system time in seconds since the Unix
  107. epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
  108. handle.
  109. This example calls both functions with a NULL pointer (``None`` should be used
  110. as the NULL pointer)::
  111. >>> print libc.time(None) # doctest: +SKIP
  112. 1150640792
  113. >>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
  114. 0x1d000000
  115. >>>
  116. ``ctypes`` tries to protect you from calling functions with the wrong number of
  117. arguments or the wrong calling convention. Unfortunately this only works on
  118. Windows. It does this by examining the stack after the function returns, so
  119. although an error is raised the function *has* been called::
  120. >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
  121. Traceback (most recent call last):
  122. File "<stdin>", line 1, in ?
  123. ValueError: Procedure probably called with not enough arguments (4 bytes missing)
  124. >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
  125. Traceback (most recent call last):
  126. File "<stdin>", line 1, in ?
  127. ValueError: Procedure probably called with too many arguments (4 bytes in excess)
  128. >>>
  129. The same exception is raised when you call an ``stdcall`` function with the
  130. ``cdecl`` calling convention, or vice versa::
  131. >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
  132. Traceback (most recent call last):
  133. File "<stdin>", line 1, in ?
  134. ValueError: Procedure probably called with not enough arguments (4 bytes missing)
  135. >>>
  136. >>> windll.msvcrt.printf("spam") # doctest: +WINDOWS
  137. Traceback (most recent call last):
  138. File "<stdin>", line 1, in ?
  139. ValueError: Procedure probably called with too many arguments (4 bytes in excess)
  140. >>>
  141. To find out the correct calling convention you have to look into the C header
  142. file or the documentation for the function you want to call.
  143. On Windows, ``ctypes`` uses win32 structured exception handling to prevent
  144. crashes from general protection faults when functions are called with invalid
  145. argument values::
  146. >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
  147. Traceback (most recent call last):
  148. File "<stdin>", line 1, in ?
  149. WindowsError: exception: access violation reading 0x00000020
  150. >>>
  151. There are, however, enough ways to crash Python with ``ctypes``, so you should
  152. be careful anyway.
  153. ``None``, integers, longs, byte strings and unicode strings are the only native
  154. Python objects that can directly be used as parameters in these function calls.
  155. ``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are
  156. passed as pointer to the memory block that contains their data (``char *`` or
  157. ``wchar_t *``). Python integers and Python longs are passed as the platforms
  158. default C ``int`` type, their value is masked to fit into the C type.
  159. Before we move on calling functions with other parameter types, we have to learn
  160. more about ``ctypes`` data types.
  161. .. _ctypes-fundamental-data-types:
  162. Fundamental data types
  163. ^^^^^^^^^^^^^^^^^^^^^^
  164. ``ctypes`` defines a number of primitive C compatible data types :
  165. +----------------------+--------------------------------+----------------------------+
  166. | ctypes type | C type | Python type |
  167. +======================+================================+============================+
  168. | :class:`c_char` | ``char`` | 1-character string |
  169. +----------------------+--------------------------------+----------------------------+
  170. | :class:`c_wchar` | ``wchar_t`` | 1-character unicode string |
  171. +----------------------+--------------------------------+----------------------------+
  172. | :class:`c_byte` | ``char`` | int/long |
  173. +----------------------+--------------------------------+----------------------------+
  174. | :class:`c_ubyte` | ``unsigned char`` | int/long |
  175. +----------------------+--------------------------------+----------------------------+
  176. | :class:`c_short` | ``short`` | int/long |
  177. +----------------------+--------------------------------+----------------------------+
  178. | :class:`c_ushort` | ``unsigned short`` | int/long |
  179. +----------------------+--------------------------------+----------------------------+
  180. | :class:`c_int` | ``int`` | int/long |
  181. +----------------------+--------------------------------+----------------------------+
  182. | :class:`c_uint` | ``unsigned int`` | int/long |
  183. +----------------------+--------------------------------+----------------------------+
  184. | :class:`c_long` | ``long`` | int/long |
  185. +----------------------+--------------------------------+----------------------------+
  186. | :class:`c_ulong` | ``unsigned long`` | int/long |
  187. +----------------------+--------------------------------+----------------------------+
  188. | :class:`c_longlong` | ``__int64`` or ``long long`` | int/long |
  189. +----------------------+--------------------------------+----------------------------+
  190. | :class:`c_ulonglong` | ``unsigned __int64`` or | int/long |
  191. | | ``unsigned long long`` | |
  192. +----------------------+--------------------------------+----------------------------+
  193. | :class:`c_float` | ``float`` | float |
  194. +----------------------+--------------------------------+----------------------------+
  195. | :class:`c_double` | ``double`` | float |
  196. +----------------------+--------------------------------+----------------------------+
  197. | :class:`c_longdouble`| ``long double`` | float |
  198. +----------------------+--------------------------------+----------------------------+
  199. | :class:`c_char_p` | ``char *`` (NUL terminated) | string or ``None`` |
  200. +----------------------+--------------------------------+----------------------------+
  201. | :class:`c_wchar_p` | ``wchar_t *`` (NUL terminated) | unicode or ``None`` |
  202. +----------------------+--------------------------------+----------------------------+
  203. | :class:`c_void_p` | ``void *`` | int/long or ``None`` |
  204. +----------------------+--------------------------------+----------------------------+
  205. All these types can be created by calling them with an optional initializer of
  206. the correct type and value::
  207. >>> c_int()
  208. c_long(0)
  209. >>> c_char_p("Hello, World")
  210. c_char_p('Hello, World')
  211. >>> c_ushort(-3)
  212. c_ushort(65533)
  213. >>>
  214. Since these types are mutable, their value can also be changed afterwards::
  215. >>> i = c_int(42)
  216. >>> print i
  217. c_long(42)
  218. >>> print i.value
  219. 42
  220. >>> i.value = -99
  221. >>> print i.value
  222. -99
  223. >>>
  224. Assigning a new value to instances of the pointer types :class:`c_char_p`,
  225. :class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
  226. point to, *not the contents* of the memory block (of course not, because Python
  227. strings are immutable)::
  228. >>> s = "Hello, World"
  229. >>> c_s = c_char_p(s)
  230. >>> print c_s
  231. c_char_p('Hello, World')
  232. >>> c_s.value = "Hi, there"
  233. >>> print c_s
  234. c_char_p('Hi, there')
  235. >>> print s # first string is unchanged
  236. Hello, World
  237. >>>
  238. You should be careful, however, not to pass them to functions expecting pointers
  239. to mutable memory. If you need mutable memory blocks, ctypes has a
  240. ``create_string_buffer`` function which creates these in various ways. The
  241. current memory block contents can be accessed (or changed) with the ``raw``
  242. property; if you want to access it as NUL terminated string, use the ``value``
  243. property::
  244. >>> from ctypes import *
  245. >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
  246. >>> print sizeof(p), repr(p.raw)
  247. 3 '\x00\x00\x00'
  248. >>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string
  249. >>> print sizeof(p), repr(p.raw)
  250. 6 'Hello\x00'
  251. >>> print repr(p.value)
  252. 'Hello'
  253. >>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer
  254. >>> print sizeof(p), repr(p.raw)
  255. 10 'Hello\x00\x00\x00\x00\x00'
  256. >>> p.value = "Hi"
  257. >>> print sizeof(p), repr(p.raw)
  258. 10 'Hi\x00lo\x00\x00\x00\x00\x00'
  259. >>>
  260. The ``create_string_buffer`` function replaces the ``c_buffer`` function (which
  261. is still available as an alias), as well as the ``c_string`` function from
  262. earlier ctypes releases. To create a mutable memory block containing unicode
  263. characters of the C type ``wchar_t`` use the ``create_unicode_buffer`` function.
  264. .. _ctypes-calling-functions-continued:
  265. Calling functions, continued
  266. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  267. Note that printf prints to the real standard output channel, *not* to
  268. ``sys.stdout``, so these examples will only work at the console prompt, not from
  269. within *IDLE* or *PythonWin*::
  270. >>> printf = libc.printf
  271. >>> printf("Hello, %s\n", "World!")
  272. Hello, World!
  273. 14
  274. >>> printf("Hello, %S\n", u"World!")
  275. Hello, World!
  276. 14
  277. >>> printf("%d bottles of beer\n", 42)
  278. 42 bottles of beer
  279. 19
  280. >>> printf("%f bottles of beer\n", 42.5)
  281. Traceback (most recent call last):
  282. File "<stdin>", line 1, in ?
  283. ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
  284. >>>
  285. As has been mentioned before, all Python types except integers, strings, and
  286. unicode strings have to be wrapped in their corresponding ``ctypes`` type, so
  287. that they can be converted to the required C data type::
  288. >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
  289. An int 1234, a double 3.140000
  290. 31
  291. >>>
  292. .. _ctypes-calling-functions-with-own-custom-data-types:
  293. Calling functions with your own custom data types
  294. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  295. You can also customize ``ctypes`` argument conversion to allow instances of your
  296. own classes be used as function arguments. ``ctypes`` looks for an
  297. :attr:`_as_parameter_` attribute and uses this as the function argument. Of
  298. course, it must be one of integer, string, or unicode::
  299. >>> class Bottles(object):
  300. ... def __init__(self, number):
  301. ... self._as_parameter_ = number
  302. ...
  303. >>> bottles = Bottles(42)
  304. >>> printf("%d bottles of beer\n", bottles)
  305. 42 bottles of beer
  306. 19
  307. >>>
  308. If you don't want to store the instance's data in the :attr:`_as_parameter_`
  309. instance variable, you could define a ``property`` which makes the data
  310. available.
  311. .. _ctypes-specifying-required-argument-types:
  312. Specifying the required argument types (function prototypes)
  313. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  314. It is possible to specify the required argument types of functions exported from
  315. DLLs by setting the :attr:`argtypes` attribute.
  316. :attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
  317. probably not a good example here, because it takes a variable number and
  318. different types of parameters depending on the format string, on the other hand
  319. this is quite handy to experiment with this feature)::
  320. >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
  321. >>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
  322. String 'Hi', Int 10, Double 2.200000
  323. 37
  324. >>>
  325. Specifying a format protects against incompatible argument types (just as a
  326. prototype for a C function), and tries to convert the arguments to valid types::
  327. >>> printf("%d %d %d", 1, 2, 3)
  328. Traceback (most recent call last):
  329. File "<stdin>", line 1, in ?
  330. ArgumentError: argument 2: exceptions.TypeError: wrong type
  331. >>> printf("%s %d %f\n", "X", 2, 3)
  332. X 2 3.000000
  333. 13
  334. >>>
  335. If you have defined your own classes which you pass to function calls, you have
  336. to implement a :meth:`from_param` class method for them to be able to use them
  337. in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
  338. the Python object passed to the function call, it should do a typecheck or
  339. whatever is needed to make sure this object is acceptable, and then return the
  340. object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
  341. pass as the C function argument in this case. Again, the result should be an
  342. integer, string, unicode, a ``ctypes`` instance, or an object with an
  343. :attr:`_as_parameter_` attribute.
  344. .. _ctypes-return-types:
  345. Return types
  346. ^^^^^^^^^^^^
  347. By default functions are assumed to return the C ``int`` type. Other return
  348. types can be specified by setting the :attr:`restype` attribute of the function
  349. object.
  350. Here is a more advanced example, it uses the ``strchr`` function, which expects
  351. a string pointer and a char, and returns a pointer to a string::
  352. >>> strchr = libc.strchr
  353. >>> strchr("abcdef", ord("d")) # doctest: +SKIP
  354. 8059983
  355. >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
  356. >>> strchr("abcdef", ord("d"))
  357. 'def'
  358. >>> print strchr("abcdef", ord("x"))
  359. None
  360. >>>
  361. If you want to avoid the ``ord("x")`` calls above, you can set the
  362. :attr:`argtypes` attribute, and the second argument will be converted from a
  363. single character Python string into a C char::
  364. >>> strchr.restype = c_char_p
  365. >>> strchr.argtypes = [c_char_p, c_char]
  366. >>> strchr("abcdef", "d")
  367. 'def'
  368. >>> strchr("abcdef", "def")
  369. Traceback (most recent call last):
  370. File "<stdin>", line 1, in ?
  371. ArgumentError: argument 2: exceptions.TypeError: one character string expected
  372. >>> print strchr("abcdef", "x")
  373. None
  374. >>> strchr("abcdef", "d")
  375. 'def'
  376. >>>
  377. You can also use a callable Python object (a function or a class for example) as
  378. the :attr:`restype` attribute, if the foreign function returns an integer. The
  379. callable will be called with the ``integer`` the C function returns, and the
  380. result of this call will be used as the result of your function call. This is
  381. useful to check for error return values and automatically raise an exception::
  382. >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
  383. >>> def ValidHandle(value):
  384. ... if value == 0:
  385. ... raise WinError()
  386. ... return value
  387. ...
  388. >>>
  389. >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
  390. >>> GetModuleHandle(None) # doctest: +WINDOWS
  391. 486539264
  392. >>> GetModuleHandle("something silly") # doctest: +WINDOWS
  393. Traceback (most recent call last):
  394. File "<stdin>", line 1, in ?
  395. File "<stdin>", line 3, in ValidHandle
  396. WindowsError: [Errno 126] The specified module could not be found.
  397. >>>
  398. ``WinError`` is a function which will call Windows ``FormatMessage()`` api to
  399. get the string representation of an error code, and *returns* an exception.
  400. ``WinError`` takes an optional error code parameter, if no one is used, it calls
  401. :func:`GetLastError` to retrieve it.
  402. Please note that a much more powerful error checking mechanism is available
  403. through the :attr:`errcheck` attribute; see the reference manual for details.
  404. .. _ctypes-passing-pointers:
  405. Passing pointers (or: passing parameters by reference)
  406. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  407. Sometimes a C api function expects a *pointer* to a data type as parameter,
  408. probably to write into the corresponding location, or if the data is too large
  409. to be passed by value. This is also known as *passing parameters by reference*.
  410. ``ctypes`` exports the :func:`byref` function which is used to pass parameters
  411. by reference. The same effect can be achieved with the ``pointer`` function,
  412. although ``pointer`` does a lot more work since it constructs a real pointer
  413. object, so it is faster to use :func:`byref` if you don't need the pointer
  414. object in Python itself::
  415. >>> i = c_int()
  416. >>> f = c_float()
  417. >>> s = create_string_buffer('\000' * 32)
  418. >>> print i.value, f.value, repr(s.value)
  419. 0 0.0 ''
  420. >>> libc.sscanf("1 3.14 Hello", "%d %f %s",
  421. ... byref(i), byref(f), s)
  422. 3
  423. >>> print i.value, f.value, repr(s.value)
  424. 1 3.1400001049 'Hello'
  425. >>>
  426. .. _ctypes-structures-unions:
  427. Structures and unions
  428. ^^^^^^^^^^^^^^^^^^^^^
  429. Structures and unions must derive from the :class:`Structure` and :class:`Union`
  430. base classes which are defined in the ``ctypes`` module. Each subclass must
  431. define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
  432. *2-tuples*, containing a *field name* and a *field type*.
  433. The field type must be a ``ctypes`` type like :class:`c_int`, or any other
  434. derived ``ctypes`` type: structure, union, array, pointer.
  435. Here is a simple example of a POINT structure, which contains two integers named
  436. ``x`` and ``y``, and also shows how to initialize a structure in the
  437. constructor::
  438. >>> from ctypes import *
  439. >>> class POINT(Structure):
  440. ... _fields_ = [("x", c_int),
  441. ... ("y", c_int)]
  442. ...
  443. >>> point = POINT(10, 20)
  444. >>> print point.x, point.y
  445. 10 20
  446. >>> point = POINT(y=5)
  447. >>> print point.x, point.y
  448. 0 5
  449. >>> POINT(1, 2, 3)
  450. Traceback (most recent call last):
  451. File "<stdin>", line 1, in ?
  452. ValueError: too many initializers
  453. >>>
  454. You can, however, build much more complicated structures. Structures can itself
  455. contain other structures by using a structure as a field type.
  456. Here is a RECT structure which contains two POINTs named ``upperleft`` and
  457. ``lowerright`` ::
  458. >>> class RECT(Structure):
  459. ... _fields_ = [("upperleft", POINT),
  460. ... ("lowerright", POINT)]
  461. ...
  462. >>> rc = RECT(point)
  463. >>> print rc.upperleft.x, rc.upperleft.y
  464. 0 5
  465. >>> print rc.lowerright.x, rc.lowerright.y
  466. 0 0
  467. >>>
  468. Nested structures can also be initialized in the constructor in several ways::
  469. >>> r = RECT(POINT(1, 2), POINT(3, 4))
  470. >>> r = RECT((1, 2), (3, 4))
  471. Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
  472. for debugging because they can provide useful information::
  473. >>> print POINT.x
  474. <Field type=c_long, ofs=0, size=4>
  475. >>> print POINT.y
  476. <Field type=c_long, ofs=4, size=4>
  477. >>>
  478. .. _ctypes-structureunion-alignment-byte-order:
  479. Structure/union alignment and byte order
  480. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  481. By default, Structure and Union fields are aligned in the same way the C
  482. compiler does it. It is possible to override this behavior be specifying a
  483. :attr:`_pack_` class attribute in the subclass definition. This must be set to a
  484. positive integer and specifies the maximum alignment for the fields. This is
  485. what ``#pragma pack(n)`` also does in MSVC.
  486. ``ctypes`` uses the native byte order for Structures and Unions. To build
  487. structures with non-native byte order, you can use one of the
  488. BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
  489. base classes. These classes cannot contain pointer fields.
  490. .. _ctypes-bit-fields-in-structures-unions:
  491. Bit fields in structures and unions
  492. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  493. It is possible to create structures and unions containing bit fields. Bit fields
  494. are only possible for integer fields, the bit width is specified as the third
  495. item in the :attr:`_fields_` tuples::
  496. >>> class Int(Structure):
  497. ... _fields_ = [("first_16", c_int, 16),
  498. ... ("second_16", c_int, 16)]
  499. ...
  500. >>> print Int.first_16
  501. <Field type=c_long, ofs=0:0, bits=16>
  502. >>> print Int.second_16
  503. <Field type=c_long, ofs=0:16, bits=16>
  504. >>>
  505. .. _ctypes-arrays:
  506. Arrays
  507. ^^^^^^
  508. Arrays are sequences, containing a fixed number of instances of the same type.
  509. The recommended way to create array types is by multiplying a data type with a
  510. positive integer::
  511. TenPointsArrayType = POINT * 10
  512. Here is an example of an somewhat artificial data type, a structure containing 4
  513. POINTs among other stuff::
  514. >>> from ctypes import *
  515. >>> class POINT(Structure):
  516. ... _fields_ = ("x", c_int), ("y", c_int)
  517. ...
  518. >>> class MyStruct(Structure):
  519. ... _fields_ = [("a", c_int),
  520. ... ("b", c_float),
  521. ... ("point_array", POINT * 4)]
  522. >>>
  523. >>> print len(MyStruct().point_array)
  524. 4
  525. >>>
  526. Instances are created in the usual way, by calling the class::
  527. arr = TenPointsArrayType()
  528. for pt in arr:
  529. print pt.x, pt.y
  530. The above code print a series of ``0 0`` lines, because the array contents is
  531. initialized to zeros.
  532. Initializers of the correct type can also be specified::
  533. >>> from ctypes import *
  534. >>> TenIntegers = c_int * 10
  535. >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
  536. >>> print ii
  537. <c_long_Array_10 object at 0x...>
  538. >>> for i in ii: print i,
  539. ...
  540. 1 2 3 4 5 6 7 8 9 10
  541. >>>
  542. .. _ctypes-pointers:
  543. Pointers
  544. ^^^^^^^^
  545. Pointer instances are created by calling the ``pointer`` function on a
  546. ``ctypes`` type::
  547. >>> from ctypes import *
  548. >>> i = c_int(42)
  549. >>> pi = pointer(i)
  550. >>>
  551. Pointer instances have a ``contents`` attribute which returns the object to
  552. which the pointer points, the ``i`` object above::
  553. >>> pi.contents
  554. c_long(42)
  555. >>>
  556. Note that ``ctypes`` does not have OOR (original object return), it constructs a
  557. new, equivalent object each time you retrieve an attribute::
  558. >>> pi.contents is i
  559. False
  560. >>> pi.contents is pi.contents
  561. False
  562. >>>
  563. Assigning another :class:`c_int` instance to the pointer's contents attribute
  564. would cause the pointer to point to the memory location where this is stored::
  565. >>> i = c_int(99)
  566. >>> pi.contents = i
  567. >>> pi.contents
  568. c_long(99)
  569. >>>
  570. .. XXX Document dereferencing pointers, and that it is preferred over the .contents attribute.
  571. Pointer instances can also be indexed with integers::
  572. >>> pi[0]
  573. 99
  574. >>>
  575. Assigning to an integer index changes the pointed to value::
  576. >>> print i
  577. c_long(99)
  578. >>> pi[0] = 22
  579. >>> print i
  580. c_long(22)
  581. >>>
  582. It is also possible to use indexes different from 0, but you must know what
  583. you're doing, just as in C: You can access or change arbitrary memory locations.
  584. Generally you only use this feature if you receive a pointer from a C function,
  585. and you *know* that the pointer actually points to an array instead of a single
  586. item.
  587. Behind the scenes, the ``pointer`` function does more than simply create pointer
  588. instances, it has to create pointer *types* first. This is done with the
  589. ``POINTER`` function, which accepts any ``ctypes`` type, and returns a new
  590. type::
  591. >>> PI = POINTER(c_int)
  592. >>> PI
  593. <class 'ctypes.LP_c_long'>
  594. >>> PI(42)
  595. Traceback (most recent call last):
  596. File "<stdin>", line 1, in ?
  597. TypeError: expected c_long instead of int
  598. >>> PI(c_int(42))
  599. <ctypes.LP_c_long object at 0x...>
  600. >>>
  601. Calling the pointer type without an argument creates a ``NULL`` pointer.
  602. ``NULL`` pointers have a ``False`` boolean value::
  603. >>> null_ptr = POINTER(c_int)()
  604. >>> print bool(null_ptr)
  605. False
  606. >>>
  607. ``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
  608. invalid non-\ ``NULL`` pointers would crash Python)::
  609. >>> null_ptr[0]
  610. Traceback (most recent call last):
  611. ....
  612. ValueError: NULL pointer access
  613. >>>
  614. >>> null_ptr[0] = 1234
  615. Traceback (most recent call last):
  616. ....
  617. ValueError: NULL pointer access
  618. >>>
  619. .. _ctypes-type-conversions:
  620. Type conversions
  621. ^^^^^^^^^^^^^^^^
  622. Usually, ctypes does strict type checking. This means, if you have
  623. ``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
  624. a member field in a structure definition, only instances of exactly the same
  625. type are accepted. There are some exceptions to this rule, where ctypes accepts
  626. other objects. For example, you can pass compatible array instances instead of
  627. pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
  628. >>> class Bar(Structure):
  629. ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
  630. ...
  631. >>> bar = Bar()
  632. >>> bar.values = (c_int * 3)(1, 2, 3)
  633. >>> bar.count = 3
  634. >>> for i in range(bar.count):
  635. ... print bar.values[i]
  636. ...
  637. 1
  638. 2
  639. 3
  640. >>>
  641. To set a POINTER type field to ``NULL``, you can assign ``None``::
  642. >>> bar.values = None
  643. >>>
  644. .. XXX list other conversions...
  645. Sometimes you have instances of incompatible types. In C, you can cast one
  646. type into another type. ``ctypes`` provides a ``cast`` function which can be
  647. used in the same way. The ``Bar`` structure defined above accepts
  648. ``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
  649. but not instances of other types::
  650. >>> bar.values = (c_byte * 4)()
  651. Traceback (most recent call last):
  652. File "<stdin>", line 1, in ?
  653. TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
  654. >>>
  655. For these cases, the ``cast`` function is handy.
  656. The ``cast`` function can be used to cast a ctypes instance into a pointer to a
  657. different ctypes data type. ``cast`` takes two parameters, a ctypes object that
  658. is or can be converted to a pointer of some kind, and a ctypes pointer type. It
  659. returns an instance of the second argument, which references the same memory
  660. block as the first argument::
  661. >>> a = (c_byte * 4)()
  662. >>> cast(a, POINTER(c_int))
  663. <ctypes.LP_c_long object at ...>
  664. >>>
  665. So, ``cast`` can be used to assign to the ``values`` field of ``Bar`` the
  666. structure::
  667. >>> bar = Bar()
  668. >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
  669. >>> print bar.values[0]
  670. 0
  671. >>>
  672. .. _ctypes-incomplete-types:
  673. Incomplete Types
  674. ^^^^^^^^^^^^^^^^
  675. *Incomplete Types* are structures, unions or arrays whose members are not yet
  676. specified. In C, they are specified by forward declarations, which are defined
  677. later::
  678. struct cell; /* forward declaration */
  679. struct {
  680. char *name;
  681. struct cell *next;
  682. } cell;
  683. The straightforward translation into ctypes code would be this, but it does not
  684. work::
  685. >>> class cell(Structure):
  686. ... _fields_ = [("name", c_char_p),
  687. ... ("next", POINTER(cell))]
  688. ...
  689. Traceback (most recent call last):
  690. File "<stdin>", line 1, in ?
  691. File "<stdin>", line 2, in cell
  692. NameError: name 'cell' is not defined
  693. >>>
  694. because the new ``class cell`` is not available in the class statement itself.
  695. In ``ctypes``, we can define the ``cell`` class and set the :attr:`_fields_`
  696. attribute later, after the class statement::
  697. >>> from ctypes import *
  698. >>> class cell(Structure):
  699. ... pass
  700. ...
  701. >>> cell._fields_ = [("name", c_char_p),
  702. ... ("next", POINTER(cell))]
  703. >>>
  704. Lets try it. We create two instances of ``cell``, and let them point to each
  705. other, and finally follow the pointer chain a few times::
  706. >>> c1 = cell()
  707. >>> c1.name = "foo"
  708. >>> c2 = cell()
  709. >>> c2.name = "bar"
  710. >>> c1.next = pointer(c2)
  711. >>> c2.next = pointer(c1)
  712. >>> p = c1
  713. >>> for i in range(8):
  714. ... print p.name,
  715. ... p = p.next[0]
  716. ...
  717. foo bar foo bar foo bar foo bar
  718. >>>
  719. .. _ctypes-callback-functions:
  720. Callback functions
  721. ^^^^^^^^^^^^^^^^^^
  722. ``ctypes`` allows to create C callable function pointers from Python callables.
  723. These are sometimes called *callback functions*.
  724. First, you must create a class for the callback function, the class knows the
  725. calling convention, the return type, and the number and types of arguments this
  726. function will receive.
  727. The CFUNCTYPE factory function creates types for callback functions using the
  728. normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
  729. function creates types for callback functions using the stdcall calling
  730. convention.
  731. Both of these factory functions are called with the result type as first
  732. argument, and the callback functions expected argument types as the remaining
  733. arguments.
  734. I will present an example here which uses the standard C library's :func:`qsort`
  735. function, this is used to sort items with the help of a callback function.
  736. :func:`qsort` will be used to sort an array of integers::
  737. >>> IntArray5 = c_int * 5
  738. >>> ia = IntArray5(5, 1, 7, 33, 99)
  739. >>> qsort = libc.qsort
  740. >>> qsort.restype = None
  741. >>>
  742. :func:`qsort` must be called with a pointer to the data to sort, the number of
  743. items in the data array, the size of one item, and a pointer to the comparison
  744. function, the callback. The callback will then be called with two pointers to
  745. items, and it must return a negative integer if the first item is smaller than
  746. the second, a zero if they are equal, and a positive integer else.
  747. So our callback function receives pointers to integers, and must return an
  748. integer. First we create the ``type`` for the callback function::
  749. >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
  750. >>>
  751. For the first implementation of the callback function, we simply print the
  752. arguments we get, and return 0 (incremental development ;-)::
  753. >>> def py_cmp_func(a, b):
  754. ... print "py_cmp_func", a, b
  755. ... return 0
  756. ...
  757. >>>
  758. Create the C callable callback::
  759. >>> cmp_func = CMPFUNC(py_cmp_func)
  760. >>>
  761. And we're ready to go::
  762. >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
  763. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  764. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  765. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  766. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  767. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  768. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  769. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  770. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  771. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  772. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  773. >>>
  774. We know how to access the contents of a pointer, so lets redefine our callback::
  775. >>> def py_cmp_func(a, b):
  776. ... print "py_cmp_func", a[0], b[0]
  777. ... return 0
  778. ...
  779. >>> cmp_func = CMPFUNC(py_cmp_func)
  780. >>>
  781. Here is what we get on Windows::
  782. >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
  783. py_cmp_func 7 1
  784. py_cmp_func 33 1
  785. py_cmp_func 99 1
  786. py_cmp_func 5 1
  787. py_cmp_func 7 5
  788. py_cmp_func 33 5
  789. py_cmp_func 99 5
  790. py_cmp_func 7 99
  791. py_cmp_func 33 99
  792. py_cmp_func 7 33
  793. >>>
  794. It is funny to see that on linux the sort function seems to work much more
  795. efficient, it is doing less comparisons::
  796. >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
  797. py_cmp_func 5 1
  798. py_cmp_func 33 99
  799. py_cmp_func 7 33
  800. py_cmp_func 5 7
  801. py_cmp_func 1 7
  802. >>>
  803. Ah, we're nearly done! The last step is to actually compare the two items and
  804. return a useful result::
  805. >>> def py_cmp_func(a, b):
  806. ... print "py_cmp_func", a[0], b[0]
  807. ... return a[0] - b[0]
  808. ...
  809. >>>
  810. Final run on Windows::
  811. >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
  812. py_cmp_func 33 7
  813. py_cmp_func 99 33
  814. py_cmp_func 5 99
  815. py_cmp_func 1 99
  816. py_cmp_func 33 7
  817. py_cmp_func 1 33
  818. py_cmp_func 5 33
  819. py_cmp_func 5 7
  820. py_cmp_func 1 7
  821. py_cmp_func 5 1
  822. >>>
  823. and on Linux::
  824. >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
  825. py_cmp_func 5 1
  826. py_cmp_func 33 99
  827. py_cmp_func 7 33
  828. py_cmp_func 1 7
  829. py_cmp_func 5 7
  830. >>>
  831. It is quite interesting to see that the Windows :func:`qsort` function needs
  832. more comparisons than the linux version!
  833. As we can easily check, our array is sorted now::
  834. >>> for i in ia: print i,
  835. ...
  836. 1 5 7 33 99
  837. >>>
  838. **Important note for callback functions:**
  839. Make sure you keep references to CFUNCTYPE objects as long as they are used from
  840. C code. ``ctypes`` doesn't, and if you don't, they may be garbage collected,
  841. crashing your program when a callback is made.
  842. .. _ctypes-accessing-values-exported-from-dlls:
  843. Accessing values exported from dlls
  844. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  845. Some shared libraries not only export functions, they also export variables. An
  846. example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
  847. to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
  848. startup.
  849. ``ctypes`` can access values like this with the :meth:`in_dll` class methods of
  850. the type. *pythonapi* is a predefined symbol giving access to the Python C
  851. api::
  852. >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
  853. >>> print opt_flag
  854. c_long(0)
  855. >>>
  856. If the interpreter would have been started with :option:`-O`, the sample would
  857. have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
  858. specified.
  859. An extended example which also demonstrates the use of pointers accesses the
  860. ``PyImport_FrozenModules`` pointer exported by Python.
  861. Quoting the Python docs: *This pointer is initialized to point to an array of
  862. "struct _frozen" records, terminated by one whose members are all NULL or zero.
  863. When a frozen module is imported, it is searched in this table. Third-party code
  864. could play tricks with this to provide a dynamically created collection of
  865. frozen modules.*
  866. So manipulating this pointer could even prove useful. To restrict the example
  867. size, we show only how this table can be read with ``ctypes``::
  868. >>> from ctypes import *
  869. >>>
  870. >>> class struct_frozen(Structure):
  871. ... _fields_ = [("name", c_char_p),
  872. ... ("code", POINTER(c_ubyte)),
  873. ... ("size", c_int)]
  874. ...
  875. >>>
  876. We have defined the ``struct _frozen`` data type, so we can get the pointer to
  877. the table::
  878. >>> FrozenTable = POINTER(struct_frozen)
  879. >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
  880. >>>
  881. Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
  882. can iterate over it, but we just have to make sure that our loop terminates,
  883. because pointers have no size. Sooner or later it would probably crash with an
  884. access violation or whatever, so it's better to break out of the loop when we
  885. hit the NULL entry::
  886. >>> for item in table:
  887. ... print item.name, item.size
  888. ... if item.name is None:
  889. ... break
  890. ...
  891. __hello__ 104
  892. __phello__ -104
  893. __phello__.spam 104
  894. None 0
  895. >>>
  896. The fact that standard Python has a frozen module and a frozen package
  897. (indicated by the negative size member) is not well known, it is only used for
  898. testing. Try it out with ``import __hello__`` for example.
  899. .. _ctypes-surprises:
  900. Surprises
  901. ^^^^^^^^^
  902. There are some edges in ``ctypes`` where you may be expect something else than
  903. what actually happens.
  904. Consider the following example::
  905. >>> from ctypes import *
  906. >>> class POINT(Structure):
  907. ... _fields_ = ("x", c_int), ("y", c_int)
  908. ...
  909. >>> class RECT(Structure):
  910. ... _fields_ = ("a", POINT), ("b", POINT)
  911. ...
  912. >>> p1 = POINT(1, 2)
  913. >>> p2 = POINT(3, 4)
  914. >>> rc = RECT(p1, p2)
  915. >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
  916. 1 2 3 4
  917. >>> # now swap the two points
  918. >>> rc.a, rc.b = rc.b, rc.a
  919. >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
  920. 3 4 3 4
  921. >>>
  922. Hm. We certainly expected the last statement to print ``3 4 1 2``. What
  923. happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
  924. >>> temp0, temp1 = rc.b, rc.a
  925. >>> rc.a = temp0
  926. >>> rc.b = temp1
  927. >>>
  928. Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
  929. the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
  930. contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
  931. contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
  932. the expected effect.
  933. Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
  934. doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
  935. the root-object's underlying buffer.
  936. Another example that may behave different from what one would expect is this::
  937. >>> s = c_char_p()
  938. >>> s.value = "abc def ghi"
  939. >>> s.value
  940. 'abc def ghi'
  941. >>> s.value is s.value
  942. False
  943. >>>
  944. Why is it printing ``False``? ctypes instances are objects containing a memory
  945. block plus some :term:`descriptor`\s accessing the contents of the memory.
  946. Storing a Python object in the memory block does not store the object itself,
  947. instead the ``contents`` of the object is stored. Accessing the contents again
  948. constructs a new Python object each time!
  949. .. _ctypes-variable-sized-data-types:
  950. Variable-sized data types
  951. ^^^^^^^^^^^^^^^^^^^^^^^^^
  952. ``ctypes`` provides some support for variable-sized arrays and structures (this
  953. was added in version 0.9.9.7).
  954. The ``resize`` function can be used to resize the memory buffer of an existing
  955. ctypes object. The function takes the object as first argument, and the
  956. requested size in bytes as the second argument. The memory block cannot be made
  957. smaller than the natural memory block specified by the objects type, a
  958. ``ValueError`` is raised if this is tried::
  959. >>> short_array = (c_short * 4)()
  960. >>> print sizeof(short_array)
  961. 8
  962. >>> resize(short_array, 4)
  963. Traceback (most recent call last):
  964. ...
  965. ValueError: minimum size is 8
  966. >>> resize(short_array, 32)
  967. >>> sizeof(short_array)
  968. 32
  969. >>> sizeof(type(short_array))
  970. 8
  971. >>>
  972. This is nice and fine, but how would one access the additional elements
  973. contained in this array? Since the type still only knows about 4 elements, we
  974. get errors accessing other elements::
  975. >>> short_array[:]
  976. [0, 0, 0, 0]
  977. >>> short_array[7]
  978. Traceback (most recent call last):
  979. ...
  980. IndexError: invalid index
  981. >>>
  982. Another way to use variable-sized data types with ``ctypes`` is to use the
  983. dynamic nature of Python, and (re-)define the data type after the required size
  984. is already known, on a case by case basis.
  985. .. _ctypes-ctypes-reference:
  986. ctypes reference
  987. ----------------
  988. .. _ctypes-finding-shared-libraries:
  989. Finding shared libraries
  990. ^^^^^^^^^^^^^^^^^^^^^^^^
  991. When programming in a compiled language, shared libraries are accessed when
  992. compiling/linking a program, and when the program is run.
  993. The purpose of the ``find_library`` function is to locate a library in a way
  994. similar to what the compiler does (on platforms with several versions of a
  995. shared library the most recent should be loaded), while the ctypes library
  996. loaders act like when a program is run, and call the runtime loader directly.
  997. The ``ctypes.util`` module provides a function which can help to determine the
  998. library to load.
  999. .. data:: find_library(name)
  1000. :module: ctypes.util
  1001. :noindex:
  1002. Try to find a library and return a pathname. *name* is the library name without
  1003. any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
  1004. is the form used for the posix linker option :option:`-l`). If no library can
  1005. be found, returns ``None``.
  1006. The exact functionality is system dependent.
  1007. On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
  1008. and objdump) to find the library file. It returns the filename of the library
  1009. file. Here are some examples::
  1010. >>> from ctypes.util import find_library
  1011. >>> find_library("m")
  1012. 'libm.so.6'
  1013. >>> find_library("c")
  1014. 'libc.so.6'
  1015. >>> find_library("bz2")
  1016. 'libbz2.so.1.0'
  1017. >>>
  1018. On OS X, ``find_library`` tries several predefined naming schemes and paths to
  1019. locate the library, and returns a full pathname if successful::
  1020. >>> from ctypes.util import find_library
  1021. >>> find_library("c")
  1022. '/usr/lib/libc.dylib'
  1023. >>> find_library("m")
  1024. '/usr/lib/libm.dylib'
  1025. >>> find_library("bz2")
  1026. '/usr/lib/libbz2.dylib'
  1027. >>> find_library("AGL")
  1028. '/System/Library/Frameworks/AGL.framework/AGL'
  1029. >>>
  1030. On Windows, ``find_library`` searches along the system search path, and returns
  1031. the full pathname, but since there is no predefined naming scheme a call like
  1032. ``find_library("c")`` will fail and return ``None``.
  1033. If wrapping a shared library with ``ctypes``, it *may* be better to determine
  1034. the shared library name at development type, and hardcode that into the wrapper
  1035. module instead of using ``find_library`` to locate the library at runtime.
  1036. .. _ctypes-loading-shared-libraries:
  1037. Loading shared libraries
  1038. ^^^^^^^^^^^^^^^^^^^^^^^^
  1039. There are several ways to loaded shared libraries into the Python process. One
  1040. way is to instantiate one of the following classes:
  1041. .. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
  1042. Instances of this class represent loaded shared libraries. Functions in these
  1043. libraries use the standard C calling convention, and are assumed to return
  1044. ``int``.
  1045. .. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
  1046. Windows only: Instances of this class represent loaded shared libraries,
  1047. functions in these libraries use the ``stdcall`` calling convention, and are
  1048. assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
  1049. values contain information specifying whether the function call failed or
  1050. succeeded, together with additional error code. If the return value signals a
  1051. failure, an :class:`WindowsError` is automatically raised.
  1052. .. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
  1053. Windows only: Instances of this class represent loaded shared libraries,
  1054. functions in these libraries use the ``stdcall`` calling convention, and are
  1055. assumed to return ``int`` by default.
  1056. On Windows CE only the standard calling convention is used, for convenience the
  1057. :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
  1058. platform.
  1059. The Python :term:`global interpreter lock` is released before calling any
  1060. function exported by these libraries, and reacquired afterwards.
  1061. .. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
  1062. Instances of this class behave like :class:`CDLL` instances, except that the
  1063. Python GIL is *not* released during the function call, and after the function
  1064. execution the Python error flag is checked. If the error flag is set, a Python
  1065. exception is raised.
  1066. Thus, this is only useful to call Python C api functions directly.
  1067. All these classes can be instantiated by calling them with at least one
  1068. argument, the pathname of the shared library. If you have an existing handle to
  1069. an already loaded shared library, it can be passed as the ``handle`` named
  1070. parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
  1071. function is used to load the library into the process, and to get a handle to
  1072. it.
  1073. The *mode* parameter can be used to specify how the library is loaded. For
  1074. details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
  1075. The *use_errno* parameter, when set to True, enables a ctypes mechanism that
  1076. allows to access the system :data:`errno` error number in a safe way.
  1077. :mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
  1078. variable; if you call foreign functions created with ``use_errno=True`` then the
  1079. :data:`errno` value before the function call is swapped with the ctypes private
  1080. copy, the same happens immediately after the function call.
  1081. The function :func:`ctypes.get_errno` returns the value of the ctypes private
  1082. copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
  1083. to a new value and returns the former value.
  1084. The *use_last_error* parameter, when set to True, enables the same mechanism for
  1085. the Windows error code which is managed by the :func:`GetLastError` and
  1086. :func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
  1087. :func:`ctypes.set_last_error` are used to request and change the ctypes private
  1088. copy of the windows error code.
  1089. .. versionadded:: 2.6
  1090. The ``use_last_error`` and ``use_errno`` optional parameters
  1091. were added.
  1092. .. data:: RTLD_GLOBAL
  1093. :noindex:
  1094. Flag to use as *mode* parameter. On platforms where this flag is not available,
  1095. it is defined as the integer zero.
  1096. .. data:: RTLD_LOCAL
  1097. :noindex:
  1098. Flag to use as *mode* parameter. On platforms where this is not available, it
  1099. is the same as *RTLD_GLOBAL*.
  1100. .. data:: DEFAULT_MODE
  1101. :noindex:
  1102. The default mode which is used to load shared libraries. On OSX 10.3, this is
  1103. *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
  1104. Instances of