On this page
  1. Foreign Function Interfaces
  2. Contents
  3. Calling C Libraries with ctypes
  4. C Structs, Pointers & Arrays
  5. Python Callbacks into C (CFUNCTYPE)
  6. Binary Layouts (struct & memoryview)

Foreign Function Interfaces

Prev: Python Object, MRO & Initialization Dunder Flow | Up: Advanced Python Internals | Next: Popular Application Domains
Rel: ctypes, struct, array, memoryview, C Shared Library with Python ctypes, Rust & Python (PyO3 + Maturin)
Ref: docs.python.org โ€” ctypes | docs.python.org โ€” struct
Tags: #public #python3 #tutorials #internals #ffi #ctypes


Contents


Calling C Libraries with ctypes

[[stdlib_module/ctypes|ctypes]] loads shared libraries (.dylib on macOS, .so on Linux, .dll on Windows) and calls C functions directly from Python without writing a C extension. Always declare argtypes and restype for type safety and correct ABI marshalling.

import ctypes
import ctypes.util

libc_path = ctypes.util.find_library("c")
libc = ctypes.CDLL(libc_path)

# Declare int abs(int)
libc.abs.argtypes = [ctypes.c_int]
libc.abs.restype = ctypes.c_int

print("libc.abs(-42) =", libc.abs(-42))  # 42

C Structs, Pointers & Arrays

Subclass ctypes.Structure with _fields_ to mirror C struct memory layouts, and use ctypes.byref() or ctypes.pointer() when C expects a pointer.

import ctypes

class Point(ctypes.Structure):
    _fields_ = [
        ("x", ctypes.c_double),
        ("y", ctypes.c_double),
    ]

pt = Point(3.0, 4.0)
IntArray3 = ctypes.c_int * 3
arr = IntArray3(10, 20, 30)

print(pt.x, pt.y, list(arr), "sizeof(Point) =", ctypes.sizeof(Point))

Python Callbacks into C (CFUNCTYPE)

ctypes.CFUNCTYPE wraps a Python callable as a C function pointer โ€” for example, passing a Python comparator into libc's qsort:

import ctypes
import ctypes.util

libc = ctypes.CDLL(ctypes.util.find_library("c"))

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

@CMPFUNC
def py_cmp(a, b) -> int:
    return (a[0] > b[0]) - (a[0] < b[0])

values = (ctypes.c_int * 5)(42, 7, 19, 1, 25)
libc.qsort(values, len(values), ctypes.sizeof(ctypes.c_int), py_cmp)
print("Sorted via libc qsort:", list(values))  # [1, 7, 19, 25, 42]

Binary Layouts (struct & memoryview)

When exchanging packed binary buffers with C code, files, or network protocols, combine [[stdlib_module/struct|struct]] with zero-copy [[__builtins__/memoryview|memoryview]] slices.

import struct

# Pack network-order (big-endian): unsigned short, unsigned int, float
packet = struct.pack("!HIf", 200, 1024, 3.5)
view = memoryview(packet)
code, length, ratio = struct.unpack("!HIf", view)
print(code, length, ratio)  # 200 1024 3.5

Linked from

Related notes