Table of Contents


Why extend Python?

When a hot loop must run faster than pure Python, the standard escape hatch is to drop into compiled C code. Python offers several bridges — ctypes is the no-compiler-toolchain one: it talks to any existing shared library (.so / .dll / .dylib) straight from the interpreter.

Loading a shared library with ctypes

Option 1 — hard-coded path

import ctypes
 
libc = ctypes.cdll.LoadLibrary('libc.so.6')

Option 2 — portable lookup

util.find_library resolves the platform-specific name (libc.so.6 on Linux, libc.dylib on macOS) — prefer it in portable code.

from ctypes import util
from ctypes import cdll
 
libc = cdll.LoadLibrary(util.find_library('libc'))

Shared libraries vs Python modules

ctypes.cdll does not import a Python module — it loads a binary library into the process and exposes its exported functions. There is no type information: you must declare argument and return types.

Buffers: raw vs value

create_string_buffer allocates C-compatible, NUL-terminated memory:

spam = ctypes.create_string_buffer(b'spam')
ctypes.sizeof(spam)

Output:

5
spam.raw

Output:

b'spam\x00'
spam.value

Output:

b'spam'

raw vs value

.raw returns the whole allocated buffer including the NUL terminator (5 bytes); .value returns the C string up to the first NUL (4 bytes). Sizeof is the allocation — that is what C functions will see.

Calling libc functions

libc.printf(spam)

Output:

spam
4
print(libc.rand())

Output:

1025202362

printf returns the character count

The 4 is printf’s return value — the number of characters written, not spam (which is printed as a side effect on the C stdout). Two gotchas in one example:

  1. C-side output bypasses Python’s sys.stdout buffering — output can appear interleaved or out of order.
  2. By default ctypes assumes the return type is int. If the C function actually returns a pointer or a long, use libc.func.restype = ... — see the exercise below.

Exercise — your own C library

1. Write the C source

// mathlib.c
long long factorial(int n) {
    long long r = 1;
    for (int i = 2; i <= n; i++)
        r *= i;
    return r;              // careful: overflows past n = 20
}
 
double mean(int *values, int count) {
    double total = 0.0;
    for (int i = 0; i < count; i++)
        total += values[i];
    return total / count;
}

2. Compile to a shared library

gcc -shared -fPIC -O2 mathlib.c -o libmathlib.so

3. Call it from Python

import ctypes
 
lib = ctypes.CDLL('./libmathlib.so')
 
# Declare the real signatures — the single most important ctypes step
lib.factorial.argtypes = [ctypes.c_int]
lib.factorial.restype = ctypes.c_longlong
 
lib.factorial(20)

Output:

2432902008176640000

Arrays pass as typed buffers:

import ctypes
 
lib.mean.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int]
lib.mean.restype = ctypes.c_double
 
data = (ctypes.c_int * 5)(2, 4, 4, 4, 5)   # the StatsList data
lib.mean(data, len(data))

Output:

3.8

4. Restype matters!

lib2 = ctypes.CDLL('./libmathlib.so')
# without restype, ctypes assumes c_int:
lib2.factorial(20)

Output:

-2102132736

A silent truncation, not an error

factorial(20) = 2432902008176640000 fits in 8 bytes, but without restype ctypes reads only the low 4 bytes (c_int) — the x86-64 EAX register, so -2102132736. Always declare argtypes and restype. A missing declaration fails silently — the worst kind of bug.

Benchmark: ctypes vs pure Python

import ctypes
import timeit
 
def py_factorial(n):
    r = 1
    for i in range(2, n + 1):
        r *= i
    return r
 
for fn, label in [(py_factorial, 'python'), (lib.factorial, 'ctypes ')]:
    t = timeit.timeit(lambda: fn(1_000), number=1_000)
    print(f'{label}: {t:.4f}s / 1000 calls')

Output:

python: 0.0412s / 1000 calls
ctypes : 0.0003s / 1000 calls

Where the win is

The speed-up here is not because C is faster per se — it is because the entire loop runs in C without touching the interpreter. But ctypes calls carry a fixed per-call overhead (~µs) for argument conversion: calling a trivial C function millions of times can be slower than Python. Move whole computations across the border, not single calls.

Beyond ctypes

ToolContractBest for
ctypesnone — works with any prebuilt .sogluing existing C libraries, no toolchain
CFFIC declarations written in Pythoncleaner API, better for new C code
Cythonannotate Python code with C typesnumerically heavy code, libraries like pandas
pybind11C++ headers, RAII bindingsexposing C++ classes to Python
maturin/PyO3Rust + Cargosafe, high-performance extensions

Same result, different ergonomics

All five produce a native extension importable from Python. ctypes stays the right first tool for this course: it teaches the Python↔C boundary (types, buffers, calling conventions) with zero build infrastructure — everything above it automates those same steps.

Bytecode disassembly with dis

Every function you define in Python is first compiled to bytecode — a list of simple instructions executed by the CPython virtual machine. The dis module (the “disassembler”) shows you exactly what the interpreter will run.

import dis
 
def py_factorial(n):
    r = 1
    for i in range(2, n + 1):
        r *= i
    return r
 
dis.dis(py_factorial)

Output:

  3           RESUME                   0

  4           LOAD_CONST               1 (1)
              STORE_FAST               1 (r)

  5           LOAD_GLOBAL              1 (range)
              LOAD_CONST               2 (2)
              LOAD_FAST                1 (n)
              LOAD_CONST               3 (1)
              BINARY_OP                1 (+)
              CALL                     2
              GET_ITER
      >>      FOR_ITER                 4 (to 25)
              STORE_FAST               2 (i)

  6           LOAD_FAST                1 (r)
              LOAD_FAST                2 (i)
              BINARY_OP                5 (*)
              STORE_FAST               1 (r)

  5      >>   JUMP_BACKWARD            5 (to 8)

  7           LOAD_FAST                1 (r)
              RETURN_VALUE

Reading a dis listing

  • LOAD_FAST / STORE_FAST — read/write a local variable (r, i, n).
  • LOAD_GLOBAL / LOAD_CONST — fetch a global name or a constant (range, 2, 1).
  • BINARY_OP — an arithmetic operation (+, *).
  • FOR_ITER / JUMP_BACKWARD — the loop machinery; everything between them runs once per iteration.
  • CALL — call a function; each call re-enters the interpreter dispatch loop.

Bytecode vs machine code

Bytecode is not machine code — it is a portable instruction set for the CPython VM. A ctypes call skips all of these instructions on the Python side (see the benchmark above); that is why the whole loop moved to C is faster than the bytecode version.

Why it matters for C extensions

Disassembly makes the interpreter boundary visible:

dis.dis(lib.factorial)   # ctypes function

Output:

TypeError: not a function

A ctypes _FuncPtr holds a raw C function pointer — there is no Python bytecode to disassemble. Comparing dis output for the pure-Python version against “nothing” for the C version is a concrete way to see where the interpreter work disappears.

Useful dis API

dis.bytecode(py_factorial)        # a bytecode object you can inspect
dis.dis(py_factorial, depth=0)    # limit nesting (default depth=1 shows nested comprehensions)
dis.get_instructions(py_factorial)  # iterate Instruction objects programmatically
for ins in dis.get_instructions(py_factorial):
    if ins.opname == 'BINARY_OP':
        print(ins.offset, ins.opname, ins.argrepr)

Output:

10 BINARY_OP +
64 BINARY_OP *

Use dis when profiling is not enough

A profiler tells you which function is slow; dis tells you why — e.g. how many LOAD_GLOBAL lookups or CALLs happen per iteration. It is also invaluable when teaching, debugging odd SyntaxWarnings, or comparing CPython versions (bytecode changes between releases, so never depend on it programmatically).

Debugging with pdb

pdb is Python’s built-in interactive debugger — the standard library’s answer to gdb for C. It lets you pause execution, inspect variables, and step through code line by line.

Starting the debugger

Three common entry points:

# 1. From the interpreter or a script — the modern way
breakpoint()          # Python 3.7+: drops into pdb at this line
# 2. Explicit import — equivalent, more control
import pdb
pdb.set_trace()       # hard-coded trace point
# 3. Run the whole script under the debugger
python -m pdb myscript.py

breakpoint() is not tied to pdb

breakpoint() honours the PYTHONBREAKPOINT environment variable: PYTHONBREAKPOINT=0 disables all breakpoints, and PYTHONBREAKPOINT=ipdb.set_trace swaps in a third-party debugger. Prefer it over pdb.set_trace() in course code.

Essential commands

CommandShortcutEffect
helphlist commands
nextnstep over the current line
stepsstep into a function call
returnrrun until the current function returns
continuecrun until the next breakpoint
listlshow the source around the current line
print expr / pp exprp / ppevaluate an expression / pretty-print it
wherewprint the call stack (bottom-up)
up / downu / dmove up/down the call stack
break linenobset a breakpoint (at a line or function)
quitqabort the program

Any other input is evaluated as Python in the current frame — r, lib, data all work as variable names directly at the (Pdb) prompt.

Worked example — debugging the ctypes call

Recall the silent truncation from the exercise above. Here is how you would catch it live:

import pdb
import ctypes
 
lib2 = ctypes.CDLL('./libmathlib.so')
lib2.factorial.argtypes = [ctypes.c_int]
# restype deliberately forgotten — bug!
 
result = lib2.factorial(20)
breakpoint()             # execution pauses here
print(result)

At the (Pdb) prompt:

(Pdb) p result
-2102132736
(Pdb) p lib2.factorial.restype
<class 'ctypes.c_int'>
(Pdb) q

Inspecting restype in the debugger shows it defaulted to c_int — the missing restype declaration is exposed in seconds, instead of after an hour of guessing.

breakpoint() in production code

A forgotten breakpoint() freezes a running program waiting for terminal input. Remove tracepoints before committing, or guard them:

if os.getenv('DEBUG'):
    breakpoint()

Post-mortem debugging

Run a crashing script with python -m pdb -c continue myscript.py: when the exception is raised, pdb stops in the frame where it happened, with all locals available — the fastest way to debug a traceback you cannot reproduce interactively.