On this page
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
- ALWAYS set both
.argtypesand.restype: Missingrestype = ctypes.c_void_ptruncates 64-bit pointers to 32-bitintand crashes. - Keep strong Python references to callbacks (
CFUNCTYPE) and buffers: If Python garbage-collects a callback while C still holds its pointer, the process will segfault. - Use
use_errno=TrueonCDLL(..., use_errno=True)and readctypes.get_errno()instead of inspecting raw Cerrno.
Common Functions
- ctypes.addressof() —
addressof(obj, /)— Return the address of the C instance internal buffer - ctypes.alignment() —
alignment(object, /)— alignment(C instance) -> integer Return the alignment requirements of a C instance - ctypes.byref() —
byref(obj, offset=0, /)— Return a pointer lookalike to a C instance, only usable as function argument. - ctypes.c_buffer() —
c_buffer(init, size=None)— create_string_buffer(anInteger) -> character array create_string_buffer(aBytes, anInteger) -> character array - ctypes.cast() —
cast(obj, typ)—ctypes.cast()function. - ctypes.create_string_buffer() —
create_string_buffer(init, size=None)— create_string_buffer(anInteger) -> character array create_string_buffer(aBytes, anInteger) -> character array - ctypes.create_unicode_buffer() —
create_unicode_buffer(init, size=None)— create_unicode_buffer(anInteger) -> character array create_unicode_buffer(aString, anInteger) -> character array - ctypes.get_errno() —
get_errno()—ctypes.get_errno()function. - ctypes.memmove() —
memmove(*args, **kwargs)—ctypes.memmove()function. - ctypes.memoryview_at() —
memoryview_at(ptr, size, readonly=False)— Return a memoryview representing the memory at void *ptr. - ctypes.memset() —
memset(*args, **kwargs)—ctypes.memset()function. - ctypes.pointer() —
pointer(obj)— Create a new pointer instance, pointing to 'obj'. - ctypes.resize() —
resize(obj, size, /)—ctypes.resize()function. - ctypes.set_errno() —
set_errno(...)—ctypes.set_errno()function. - ctypes.SetPointerType() —
SetPointerType(pointer, cls)—ctypes.SetPointerType()function. - ctypes.sizeof() —
sizeof(obj, /)— Return the size in bytes of a C instance. - ctypes.string_at() —
string_at(ptr, size=-1)— Return the byte string at void *ptr. - ctypes.wstring_at() —
wstring_at(ptr, size=-1)— Return the wide-character string at void *ptr.
Classes & Objects
- ctypes.ArgumentError —
ctypes.ArgumentErrorclass. (Methods:.add_note(),.with_traceback()) - ctypes.Array — Abstract base class for arrays.
- ctypes.BigEndianStructure — Structure with big endian byte order
- ctypes.BigEndianUnion — Union with big endian byte order
- ctypes.c_bool —
ctypes.c_boolclass. - ctypes.c_byte —
ctypes.c_byteclass. - ctypes.c_char —
ctypes.c_charclass. - ctypes.c_char_p —
ctypes.c_char_pclass. (Methods:.from_param()) - ctypes.c_double —
ctypes.c_doubleclass. - ctypes.c_double_complex —
ctypes.c_double_complexclass. - ctypes.c_float —
ctypes.c_floatclass. - ctypes.c_float_complex —
ctypes.c_float_complexclass. - ctypes.c_int —
ctypes.c_intclass. - ctypes.c_int16 —
ctypes.c_int16class. - ctypes.c_int32 —
ctypes.c_int32class. - ctypes.c_int64 —
ctypes.c_int64class. - ctypes.c_int8 —
ctypes.c_int8class. - ctypes.c_long —
ctypes.c_longclass. - ctypes.c_longdouble —
ctypes.c_longdoubleclass. - ctypes.c_longdouble_complex —
ctypes.c_longdouble_complexclass.
Constants & Attributes
ctypes.DEFAULT_MODE(int) =4ctypes.RTLD_GLOBAL(int) =8ctypes.RTLD_LOCAL(int) =4ctypes.SIZEOF_TIME_T(int) =8ctypes.cdll(LibraryLoader) =<ctypes.LibraryLoader object at 0x109c497f0>ctypes.pydll(LibraryLoader) =<ctypes.LibraryLoader object at 0x109c38410>ctypes.pythonapi(PyDLL) =<PyDLL 'None', handle fffffffffffffffe at 0x109c49940>
Linked from
- tuts/c/tutorials/c_shared_library_with_python_ctypes
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/csv
- tuts/python3/stdlib_module/ctypes/addressof
- tuts/python3/stdlib_module/ctypes/alignment
- tuts/python3/stdlib_module/ctypes/ArgumentError
- tuts/python3/stdlib_module/ctypes/Array
- tuts/python3/stdlib_module/ctypes/BigEndianStructure
- tuts/python3/stdlib_module/ctypes/BigEndianUnion
- tuts/python3/stdlib_module/ctypes/byref
- tuts/python3/stdlib_module/ctypes/c_bool
- tuts/python3/stdlib_module/ctypes/c_buffer
- tuts/python3/stdlib_module/ctypes/c_byte
- tuts/python3/stdlib_module/ctypes/c_char
- tuts/python3/stdlib_module/ctypes/c_char_p
- tuts/python3/stdlib_module/ctypes/c_double
- tuts/python3/stdlib_module/ctypes/c_double_complex
- tuts/python3/stdlib_module/ctypes/c_float
- tuts/python3/stdlib_module/ctypes/c_float_complex
- tuts/python3/stdlib_module/ctypes/c_int
- tuts/python3/stdlib_module/ctypes/c_int16
- tuts/python3/stdlib_module/ctypes/c_int32
- tuts/python3/stdlib_module/ctypes/c_int64
- tuts/python3/stdlib_module/ctypes/c_int8
- tuts/python3/stdlib_module/ctypes/c_long
- tuts/python3/stdlib_module/ctypes/c_longdouble
- tuts/python3/stdlib_module/ctypes/c_longdouble_complex
- tuts/python3/stdlib_module/ctypes/cast
- tuts/python3/stdlib_module/ctypes/create_string_buffer
- tuts/python3/stdlib_module/ctypes/create_unicode_buffer
- tuts/python3/stdlib_module/ctypes/get_errno
- tuts/python3/stdlib_module/ctypes/memmove
- tuts/python3/stdlib_module/ctypes/memoryview_at
- tuts/python3/stdlib_module/ctypes/memset
- tuts/python3/stdlib_module/ctypes/pointer
- tuts/python3/stdlib_module/ctypes/resize
- tuts/python3/stdlib_module/ctypes/set_errno
- tuts/python3/stdlib_module/ctypes/SetPointerType
- tuts/python3/stdlib_module/ctypes/sizeof
- tuts/python3/stdlib_module/ctypes/string_at
- tuts/python3/stdlib_module/ctypes/wstring_at
- tuts/python3/stdlib_module/curses
- tuts/python3/stdlib_module/faulthandler
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/advanced_python_internals
- tuts/python3/tutorials/advanced_python_internals/foreign_function_interfaces
Related notes
- tuts/python3/stdlib_module/csv Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ctypes/addressof Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ctypes/alignment Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ctypes/ArgumentError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ctypes/Array Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ctypes/BigEndianStructure Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ctypes/BigEndianUnion Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ctypes/byref Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ctypes/c_bool Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ctypes/c_buffer Linked here; links to this page; shared tags: #stdlib