pyo3-ffi
This crate provides Rust FFI declarations for Python 3. It supports both the stable and the unstable component of the ABI through the use of cfg flags. Python Versions 3.7+ are supported. It is meant for advanced users only - regular PyO3 users shouldn't need to interact with this crate at all.
The contents of this crate are not documented here, as it would entail basically copying the documentation from CPython. Consult the Python/C API Reference Manual for up-to-date documentation.
Minimum supported Rust and Python versions
PyO3 supports the following software versions:
- Python 3.7 and up (CPython and PyPy)
- Rust 1.63 and up
Example: Building Python Native modules
PyO3 can be used to generate a native Python module. The easiest way to try this out for the
first time is to use maturin
. maturin
is a tool for building and publishing Rust-based
Python packages with minimal configuration. The following steps set up some files for an example
Python module, install maturin
, and then show how to build and import the Python module.
First, create a new folder (let's call it string_sum
) containing the following two files:
Cargo.toml
[]
= "string_sum"
# "cdylib" is necessary to produce a shared library for Python to import from.
#
# Downstream Rust code (including code in `bin/`, `examples/`, and `tests/`) will not be able
# to `use string_sum;` unless the "rlib" or "lib" crate type is also included, e.g.:
# crate-type = ["cdylib", "rlib"]
= ["cdylib"]
[]
= "*"
= ["extension-module"]
src/lib.rs
use c_char;
use ptr;
use *;
static mut MODULE_DEF: PyModuleDef = PyModuleDef ;
static mut METHODS: = ;
// The module initialization function, which must be named `PyInit_<your_module>`.
pub unsafe extern "C"
pub unsafe extern "C"
With those two files in place, now maturin
needs to be installed. This can be done using
Python's package manager pip
. First, load up a new Python virtualenv
, and install maturin
into it:
Now build and execute the module:
# lots of progress output as maturin runs the compilation...
>>> import
>>> string_sum.sum_as_string()
As well as with maturin
, it is possible to build using setuptools-rust or
manually. Both offer more flexibility than maturin
but require further
configuration.
While most projects use the safe wrapper provided by PyO3,
you can take a look at the orjson
library as an example on how to use pyo3-ffi
directly.
For those well versed in C and Rust the tutorials from the CPython documentation
can be easily converted to rust as well.