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.
PyO3 supports the following software versions: - Python 3.7 and up (CPython and PyPy) - Rust 1.48 and up
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
```toml [lib] name = "string_sum"
#
bin/
, examples/
, and tests/
) will not be ableuse string_sum;
unless the "rlib" or "lib" crate type is also included, e.g.:crate-type = ["cdylib"]
[dependencies.pyo3-ffi] version = "*" features = ["extension-module"] ```
src/lib.rs
```rust
use std::os::raw::c_char;
use std::ptr;
use pyo3_ffi::*;
static mut MODULEDEF: PyModuleDef = PyModuleDef {
mbase: PyModuleDefHEADINIT,
mname: "stringsum\0".asptr().cast::
static mut METHODS: [PyMethodDef; 2] = [
PyMethodDef {
mlname: "sumasstring\0".asptr().cast::
// The module initialization function, which must be named PyInit_<your_module>
.
pub unsafe extern "C" fn PyInitstringsum() -> *mut PyObject { PyModuleCreate(ptr::addrofmut!(MODULEDEF)) }
pub unsafe extern "C" fn sumasstring(
self: *mut PyObject,
args: *mut *mut PyObject,
nargs: Pyssizet,
) -> *mut PyObject {
if nargs != 2 {
PyErrSetString(
PyExcTypeError,
"sumasstring() expected 2 positional arguments\0"
.asptr()
.cast::
let arg1 = *args;
if PyLong_Check(arg1) == 0 {
PyErr_SetString(
PyExc_TypeError,
"sum_as_string() expected an int for positional argument 1\0"
.as_ptr()
.cast::<c_char>(),
);
return std::ptr::null_mut();
}
let arg1 = PyLong_AsLong(arg1);
if !PyErr_Occurred().is_null() {
return ptr::null_mut();
}
let arg2 = *args.add(1);
if PyLong_Check(arg2) == 0 {
PyErr_SetString(
PyExc_TypeError,
"sum_as_string() expected an int for positional argument 2\0"
.as_ptr()
.cast::<c_char>(),
);
return std::ptr::null_mut();
}
let arg2 = PyLong_AsLong(arg2);
if !PyErr_Occurred().is_null() {
return ptr::null_mut();
}
match arg1.checked_add(arg2) {
Some(sum) => {
let string = sum.to_string();
PyUnicode_FromStringAndSize(string.as_ptr().cast::<c_char>(), string.len() as isize)
}
None => {
PyErr_SetString(
PyExc_OverflowError,
"arguments too large to add\0".as_ptr().cast::<c_char>(),
);
std::ptr::null_mut()
}
}
} ```
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:
bash
$ cd string_sum
$ python -m venv .env
$ source .env/bin/activate
$ pip install maturin
Now build and execute the module: ```bash $ maturin develop
$ python
import stringsum stringsum.sumasstring(5, 20) '25' ```
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.