liveBook · Manning

Python C API

As explained in Refactoring to Rust

The Python C API is the C-level interface for embedding the Python interpreter and extending Python with native code.

The Python C API provides the interface for embedding the Python interpreter and extending Python with native code. PyO3 exposes this work through Rust types and helpers. section 6.5

Working with the interface requires:

  • Acquiring Python’s GIL with Python::with_gil before using core interpreter data structures. section 6.5
  • Creating a PyDict for locals and importing Python modules through the GIL handle. section 6.5
  • Passing Rust values into Python and executing code with py.run. section 6.5

Benchmarking a Python extension

A Criterion benchmark loads json and a rust_json extension into a Python locals dictionary, supplies JSON input, and compares pure-Python execution with the Rust extension. The measured example reports 25.623 μs for pure Python and 21.987 μs for the extension. section 6.5

How Refactoring to Rust covers it

How deep it goes
Explains GIL handling, interpreter access, locals construction, imports, value passing, and execution, but not lower-level C implementation details.
Examples
Demonstrates a JSON-processing benchmark contrasting pure Python with a Rust extension module.
What you can do after
Apply it via PyO3 and Criterion to execute Python from Rust and measure a native extension against Python code.
How it connects
Connects the Python interpreter, GIL, PyO3, Criterion, Python modules, and native extension modules.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.