Typing Stubs for cffi

2.0.0.20260402 · active · verified Sun Apr 05

types-cffi is a type stub package providing external type annotations for the popular `cffi` library, which allows Python to call C code. It enables static type checkers like MyPy and PyRight to analyze code that uses `cffi` for improved development experience and bug detection. This package is part of the broader typeshed project and is regularly updated, with releases potentially occurring daily, to maintain compatibility with `cffi` itself.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic usage of `cffi` to call a C standard library function, `puts`. When `types-cffi` is installed, a static type checker will provide type hints for `ffi`, `lib`, and other `cffi` objects, helping to catch type-related errors at development time. The example intentionally avoids platform-specific library loading to be more general, using `ffi.dlopen(None)` for Unix-like systems to access the standard C library.

import os
from cffi import FFI

# Initialize FFI
ffi = FFI()

# Declare C functions (e.g., from the standard C library)
ffi.cdef("""int puts(const char* s);""")

# Load the C library (None on Unix-like systems typically opens libc)
try:
    libc = ffi.dlopen(None) # type: ignore
except OSError:
    print("Could not load libc. This example might not run on all systems.\n"\
          "Ensure a C standard library is available and discoverable.")
    exit(1)

# Call a C function with type checking (implicitly using types-cffi)
message = ffi.new("char[]", b"Hello from C via CFFI and types-cffi!")
return_code = libc.puts(message)

print(f"C puts() returned: {return_code}")

# Example of type checking at development time:
# If you misspelled 'puts' or passed an int instead of bytes, 
# a type checker (like MyPy) would flag it due to types-cffi.

view raw JSON →