ctypes
TLDR
Load a shared library
SYNOPSIS
DESCRIPTION
ctypes is a Python standard library module for calling functions in C shared libraries and DLLs. It provides C-compatible data types and allows calling functions with appropriate argument and return type specifications.
The module enables Python code to interface with native libraries without writing C extension modules. It handles type conversion between Python and C, pointer management, and structure/union definitions.
Common uses include accessing system libraries, using hardware interfaces, integrating legacy C code, and calling platform-specific APIs (Windows DLLs, macOS frameworks).
TYPES
c_int, c_long, c_longlong
Integer types.c_uint, c_ulong
Unsigned integers.c_float, c_double
Floating point types.c_char, c_wchar
Character types.c_char_p, c_wchar_p
String pointers (char*, wchar_t*).c_void_p
Void pointer.POINTER(type)
Pointer to type.Structure, Union
Base classes for C structs/unions.
EXAMPLE
# Load math library
libm = CDLL('libm.so.6') # Linux
# libm = CDLL('libSystem.B.dylib') # macOS
# Configure function
libm.sqrt.argtypes = [c_double]
libm.sqrt.restype = c_double
# Call function
result = libm.sqrt(16.0)
print(result) # 4.0
CAVEATS
Incorrect type specifications can cause crashes or memory corruption. Pointers and memory management require careful handling. Library paths vary by OS; use find_library for portability. Performance overhead exists compared to C extensions. Not suitable for C++ libraries with name mangling.
HISTORY
ctypes was created by Thomas Heller and merged into Python's standard library in version 2.5 (2006). It was based on the earlier ctypes project available on PyPI since 2003. The module provided a crucial capability for Python to interface with native code without compilation, enabling pure-Python access to system libraries.


