ctypes
Foreign Function Library for Python
Chris Church
April 24, 2007
What Is It?
- A Python module for calling C code in shared libraries
- Included in the standard distribution for Python 2.5
An Example: The Spread Toolkit
- Spread is an open source toolkit that provides a high performance messaging service...
- SpreadModule is a C extension for version 3.x.
- Nothing currently exists for Python to use Spread 4.0...
- ...so let's write something in
ctypes
Loading a Library (continued)
-
Linux
>>> libspread = CDLL('libspread.so')
-
Mac OS X
>>> libspread = CDLL('libspread.dylib')
-
Finding a Library
>>> from ctypes.util import find_library
>>> find_library('spread')
'/usr/local/lib/libspread.dylib'
Integer Types
Equivalent to the Python int type
| C Type | ctypes Type |
| char | c_byte |
| unsigned char | c_ubyte |
| short | c_short |
| unsigned short | c_ushort |
| int | c_int |
| unsigned int | c_uint |
Integer Types (continued)
Equivalent to the Python int and long types
| C Type | ctypes Type |
| long | c_long |
| unsigned long | c_ulong |
| long long (or __int64) | c_longong |
| unsigned long long (or unsigned __int64) | c_ulonglong |
Floating Point Types
Equivalent to the Python float type
| C Type | ctypes Type |
| float | c_float |
| double | c_double |
String Types
Equivalent to the Python str and unicode types, or None
| C Type | ctypes Type | Python Type |
| char | c_char | str (1-character) |
| wchar_t | c_wchar | unicode (1-character) |
| char * (NUL terminated) | c_char_p | str or None |
| wchar_t * (NUL terminated) | c_wchar_p | unicode or None |
Pointers
Equivalent to the Python int and long types, or None
| C Type | ctypes Type |
| void * | c_void_p |
To create pointer to another type, use POINTER():
>>> POINTER(c_int)
<class 'ctypes.LP_c_long'>
Function Prototypes
_FuncPtr instances have three special attributes:
restype -> Return type
argtypes -> Sequence of argument types
errcheck -> Python function to check result
- Add these special attributes to
SP_error
>>> libspread.SP_error.argtypes = [c_int]
>>> libspread.SP_error.restype = None
>>> libspread.SP_error(-2)
SP_error: (-2) Could not connect. Is Spread running?
>>> libspread.SP_error("blah")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ctypes.ArgumentError: argument 1: exceptions.TypeError: wrong type
Function Prototypes (continued)
More Function Prototypes
Checking Return Values
Structures
Unions
Arrays
Casting
Callbacks