0Pricing
Python Academy · Lesson

ctypes: Calling C Libraries from Python

Load shared libraries and call C functions using ctypes.

What Is ctypes?

ctypes is a standard-library module for loading shared C libraries and calling their functions from Python — no compilation required.

import ctypes

# Load the C standard library
libc = ctypes.CDLL("libc.so.6")   # Linux
# libc = ctypes.CDLL("libSystem.dylib")  # macOS

libc.puts(b"Hello from C!")

Loading Libraries

Use ctypes.CDLL for cdecl calling convention (most C libraries) and WinDLL for Windows stdcall APIs.

import ctypes

# Platform-independent approach:
import ctypes.util
libm_name = ctypes.util.find_library("m")
libm = ctypes.CDLL(libm_name)

result = libm.sqrt
result.restype = ctypes.c_double
result.argtypes = [ctypes.c_double]
print(result(2.0))   # 1.4142...

All lessons in this course

  1. Why C Extensions? Use Cases and Trade-offs
  2. ctypes: Calling C Libraries from Python
  3. cffi: C Foreign Function Interface
  4. Writing a Python C Extension Module
← Back to Python Academy