On this page
  1. ctypes
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Declaring Explicit argtypes & restype on a Native C Function
  7. 2. Defining a C Struct Layout (ctypes.Structure)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

ctypes

Prev: csv | Up: stdlib_module | Next: curses
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — ctypes
Tags: #public #python3 #stdlib


Import

import ctypes

Overview

Foreign Function Interface (FFI) for calling C shared libraries (.dylib, .so, .dll) and manipulating raw C structs, pointers, and buffers directly from pure Python with zero compiler toolchain. Essential for native OS integrations (macOS CoreGraphics/Foundation, Win32, libc) when you want zero-dependency bindings.

Quick Start

import ctypes

buf = ctypes.create_string_buffer(b"hello", 16)
assert buf.value == b"hello"
assert ctypes.sizeof(ctypes.c_uint32) == 4

Implementation Walkthrough

1. Declaring Explicit argtypes & restype on a Native C Function

Always declare argtypes and restype on every C function you call—without them, ctypes assumes C int returns, which silently truncates 64-bit pointers and causes segfaults:

import ctypes
from ctypes.util import find_library

libc_name = find_library("c")
if libc_name:
    libc = ctypes.CDLL(libc_name)
    libc.strlen.argtypes = [ctypes.c_char_p]
    libc.strlen.restype = ctypes.c_size_t
    assert libc.strlen(b"wispsy") == 6

2. Defining a C Struct Layout (ctypes.Structure)

import ctypes

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

pt = Point(3.0, 4.0)
assert ctypes.sizeof(pt) == 16 and pt.x == 3.0

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes