Python's ctypes: The Magic of Calling C Without a Compiler

This article explains how the ctypes module loads shared libraries and calls C functions from Python, how argument and result types, buffers, pointers and callbacks are declared, what each call costs, and which errors can crash the interpreter.

A green snake with white and yellow scales hangs from its coils, its head reaching down into empty space against a blurred background.
Photo by Peter Neumann on Unsplash

A large part of the software available on any operating system is written in C and distributed as shared libraries: files with the extension .so on Linux, .dylib on macOS and .dll on Windows. The present article addresses ctypes, the module of the standard library that loads such libraries and calls their functions directly from Python, without writing or compiling a single line of C. The module translates Python values into C values and back, but it cannot read the declarations of the library, so the program must state the type of every argument and every result. Calling compiled code that already exists, with nothing more than the standard library, is the secret weapon of this module, and the article examines both what it enables and what it costs.

Loading a Shared Library

A library is loaded by creating a CDLL object, whose attributes are the functions that the library exports. The name of the C runtime library differs between systems, so the helper ctypes.util.find_library locates it on Linux and macOS, whereas on Windows, where no naming scheme exists and the helper returns None, the runtime msvcrt is loaded through ctypes.cdll.

import ctypes
import ctypes.util
import sys
import time

if sys.platform == "win32":
    libc = ctypes.cdll.msvcrt
else:
    libc = ctypes.CDLL(ctypes.util.find_library("c"))

libc.time.argtypes = [ctypes.POINTER(ctypes.c_time_t)]
libc.time.restype = ctypes.c_time_t

seconds = libc.time(None)
print(type(seconds).__name__)                 # Output: int
print(abs(seconds - int(time.time())) <= 1)   # Output: True

The C function time returns the seconds elapsed since 1 January 1970, and its result agrees with time.time() of Python. The argument None is translated into a null pointer. The result type c_time_t, added in Python 3.12, matches the width of time_t on each platform; the type c_long, often suggested for the same purpose, has only 32 bits on 64-bit Windows and would fail after January 2038.

Declaring Argument and Result Types

By default, ctypes assumes that every function returns a C int and converts each argument according to its Python type, without checking it against the real signature. The function strtod, which converts text into a double, shows the consequence.

import ctypes
import ctypes.util
import sys

libc = ctypes.cdll.msvcrt if sys.platform == "win32" else ctypes.CDLL(ctypes.util.find_library("c"))

strtod = libc.strtod
print(strtod(b"2.5", None) == 2.5)  # Output: False

strtod.restype = ctypes.c_double
strtod.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_char_p)]
print(strtod(b"2.5", None))         # Output: 2.5

try:
    strtod("2.5", None)
except ctypes.ArgumentError as error:
    print(type(error).__name__)     # Output: ArgumentError

Without a declared restype, the result is read as an integer from the wrong register and has nothing to do with 2.5. Once restype and argtypes are declared, the call returns the correct value, and an argument of the wrong type, here a str where the function expects bytes, is rejected with ctypes.ArgumentError before C receives it. Declaring both attributes for every function is therefore the first rule of the module.

Buffers and Pointers

C functions that write their results receive a pointer to memory owned by the caller. Python strings and bytes are immutable, so the documentation forbids passing them to functions that modify memory; create_string_buffer allocates a mutable block, and byref passes the address of a C variable.

import ctypes
import ctypes.util
import sys

libc = ctypes.cdll.msvcrt if sys.platform == "win32" else ctypes.CDLL(ctypes.util.find_library("c"))

buffer = ctypes.create_string_buffer(32)
libc.sprintf(buffer, b"%d items of %s", 42, b"data")
print(buffer.value)              # Output: b'42 items of data'

first, second = ctypes.c_int(), ctypes.c_int()
matched = libc.sscanf(b"7 9", b"%d %d", ctypes.byref(first), ctypes.byref(second))
print(matched, first.value, second.value)  # Output: 2 7 9

The buffer of 32 bytes receives the formatted text, and its attribute value returns it up to the terminating null byte; a longer result would overflow the buffer, because sprintf does not know its size. The variables first and second are C integers whose addresses sscanf fills. Writing into a buffer is also preferable to calling printf, whose output goes through the buffer of the C library and may appear out of order with respect to the output of Python, as happened during the tests of this article. The same family of objects supports C structures, declared as subclasses of ctypes.Structure, and Python 3.14 added ctypes.memoryview_at, which exposes memory at a given address without copying it, in the manner described in the article devoted to memoryview.

Callbacks: C Calling Back into Python

Some C functions receive a pointer to another function, which they call during their work. The factory CFUNCTYPE wraps a Python function so that C can call it, as the following example does with qsort, the sorting function of the C library.

import ctypes
import ctypes.util
import sys

libc = ctypes.cdll.msvcrt if sys.platform == "win32" else ctypes.CDLL(ctypes.util.find_library("c"))

COMPARE = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))

def compare(a, b):
    return (a[0] > b[0]) - (a[0] < b[0])

compare_c = COMPARE(compare)
values = (ctypes.c_int * 6)(5, 1, 7, 33, 99, -2)
libc.qsort.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_size_t, COMPARE]
libc.qsort.restype = None
libc.qsort(values, len(values), ctypes.sizeof(ctypes.c_int), compare_c)
print(list(values))  # Output: [-2, 1, 5, 7, 33, 99]

The expression ctypes.c_int * 6 creates a C array type, and qsort sorts that array in place, calling the Python function compare for each comparison. The wrapper compare_c is kept in a variable on purpose: if C stores a callback whose wrapper has been garbage collected, the next call jumps to freed memory.

The Cost of Crossing the Boundary

Each call through ctypes converts the arguments, prepares the call and converts the result, and this work is far larger than the work of a small C function. The following example compares the built-in abs with the function labs of the C library.

import ctypes
import ctypes.util
import sys
import timeit

libc = ctypes.cdll.msvcrt if sys.platform == "win32" else ctypes.CDLL(ctypes.util.find_library("c"))
libc.labs.argtypes = [ctypes.c_long]
libc.labs.restype = ctypes.c_long

print(libc.labs(-5), abs(-5))  # Output: 5 5

native = min(timeit.repeat(lambda: abs(-5), number=200_000, repeat=5))
foreign = min(timeit.repeat(lambda: libc.labs(-5), number=200_000, repeat=5))
print(foreign > 5 * native)   # Output: True

On the test machine, with CPython 3.12 on Windows, the built-in call took about 23 nanoseconds and the call through ctypes about 195, roughly eight times more. Consequently, ctypes does not accelerate small operations; it pays off when each call performs a substantial amount of work in C, such as compressing a block, decoding an image or processing a whole array. One further property matters for concurrency: functions of a CDLL library are called with the global interpreter lock released, so other Python threads keep running while a long C function executes, unlike ordinary Python code, as explained in the article devoted to the GIL.

Friendly Fire: Pitfalls of ctypes

In many games, friendly fire is the damage that a player's own attacks cause to the player's own side; with ctypes, an error in a declaration damages the Python process itself, because no layer stands between the interpreter and the C function. The documentation warns that incorrect arguments "can corrupt memory or crash Python". Six pitfalls are distinguished, which are the following:

  1. Missing declarations. Without restype and argtypes, results are read as int and arguments are not checked, which produces wrong values or crashes.
  2. Platform-dependent widths. Types such as long and time_t change size between systems; c_long has 32 bits on 64-bit Windows.
  3. Writing into immutable objects. Passing bytes to a function that writes corrupts an object that Python considers constant; a buffer from create_string_buffer must be used instead.
  4. Buffer overflows. C functions do not know the size of a Python buffer, so the program must allocate enough space or use functions that receive the size.
  5. Collected callbacks. A CFUNCTYPE wrapper must stay referenced for as long as C may call it.
  6. Platform-specific libraries. Library names, available functions and the C runtime differ between systems; errno through use_errno is reliable only for libraries that share the C runtime of the interpreter.

The second pitfall is easy to check on any machine, since ctypes.sizeof reports the width of each C type of the platform.

Choosing Between ctypes and Its Alternatives

The suitability of ctypes depends on how often the boundary is crossed and on how stable the interface of the library is, as the following table summarizes.

Situation Recommended approach
Calling a few functions of an existing library, without a compiler ctypes, with argtypes and restype declared
Many small calls in a tight loop Pure Python or a library with a native Python interface
Long computations in C that should not block other threads ctypes with a CDLL library, which releases the GIL
Complex APIs with many structures and callbacks A compiled extension or a generated binding
Distributing a package that must work on every platform A compiled extension with wheels for each platform
Functions that write results create_string_buffer and byref, never bytes

Conclusion

It is concluded that ctypes gives Python direct access to the functions of compiled libraries without a compiler, provided that every argument and result type is declared, mutable memory is allocated through ctypes and callbacks are kept alive. This magic has a price at each crossing, about eight times the cost of a built-in call in the measurement above, so it is suited to functions that do substantial work per call, and a mistake in a declaration can crash the interpreter. The compiled alternative, a C extension module that Python imports like any other module, removes much of that cost and is developed in a future article of this series.