ctypes

Foreign Function Library for Python

Chris Church

April 24, 2007

What Is It?

An Example: The Spread Toolkit

Importing the Module

Loading a Library

Loading a Library (continued)

Calling a Function

Integer Types

Equivalent to the Python int type


C Typectypes Type
charc_byte
unsigned charc_ubyte
shortc_short
unsigned shortc_ushort
intc_int
unsigned intc_uint

Integer Types (continued)

Equivalent to the Python int and long types


C Typectypes Type
longc_long
unsigned longc_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 Typectypes Type
floatc_float
doublec_double

String Types

Equivalent to the Python str and unicode types, or None


C Typectypes TypePython Type
charc_charstr (1-character)
wchar_tc_wcharunicode (1-character)
char * (NUL terminated)c_char_pstr or None
wchar_t * (NUL terminated)c_wchar_punicode or None

Pointers

Equivalent to the Python int and long types, or None


C Typectypes 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