Debian Codegraph @

README.md

raw symbols SCIP
1 # pyo3-ffi
2
3 This crate provides [Rust](https://www.rust-lang.org/) FFI declarations for Python 3.
4 It supports both the stable and the unstable component of the ABI through the use of cfg flags.
5 Python Versions 3.7+ are supported.
6 It is meant for advanced users only - regular PyO3 users shouldn't
7 need to interact with this crate at all.
8
9 The contents of this crate are not documented here, as it would entail
10 basically copying the documentation from CPython. Consult the [Python/C API Reference
11 Manual][capi] for up-to-date documentation.
12
13 # Minimum supported Rust and Python versions
14
15 Requires Rust 1.63 or greater.
16
17 `pyo3-ffi` supports the following Python distributions:
18 - CPython 3.7 or greater
19 - PyPy 7.3 (Python 3.9+)
20 - GraalPy 24.0 or greater (Python 3.10+)
21
22 # Example: Building Python Native modules
23
24 PyO3 can be used to generate a native Python module. The easiest way to try this out for the
25 first time is to use [`maturin`]. `maturin` is a tool for building and publishing Rust-based
26 Python packages with minimal configuration. The following steps set up some files for an example
27 Python module, install `maturin`, and then show how to build and import the Python module.
28
29 First, create a new folder (let's call it `string_sum`) containing the following two files:
30
31 **`Cargo.toml`**
32
33 ```toml
34 [lib]
35 name = "string_sum"
36 # "cdylib" is necessary to produce a shared library for Python to import from.
37 #
38 # Downstream Rust code (including code in `bin/`, `examples/`, and `tests/`) will not be able
39 # to `use string_sum;` unless the "rlib" or "lib" crate type is also included, e.g.:
40 # crate-type = ["cdylib", "rlib"]
41 crate-type = ["cdylib"]
42
43 [dependencies]
44 pyo3-ffi = "0.28.2"
45
46 [build-dependencies]
47 # This is only necessary if you need to configure your build based on
48 # the Python version or the compile-time configuration for the interpreter.
49 pyo3_build_config = "0.28.2"
50 ```
51
52 If you need to use conditional compilation based on Python version or how
53 Python was compiled, you need to add `pyo3-build-config` as a
54 `build-dependency` in your `Cargo.toml` as in the example above and either
55 create a new `build.rs` file or modify an existing one so that
56 `pyo3_build_config::use_pyo3_cfgs()` gets called at build time:
57
58 **`build.rs`**
59
60 ```rust,ignore
61 fn main() {
62 pyo3_build_config::use_pyo3_cfgs()
63 }
64 ```
65
66 **`src/lib.rs`**
67 ```rust,no_run
68 #[cfg(Py_3_15)]
69 use std::ffi::c_void;
70 use std::ffi::{c_char, c_long};
71 use std::ptr;
72
73 use pyo3_ffi::*;
74
75 #[cfg(not(Py_3_15))]
76 static mut MODULE_DEF: PyModuleDef = PyModuleDef {
77 m_base: PyModuleDef_HEAD_INIT,
78 m_name: c"string_sum".as_ptr(),
79 m_doc: c"A Python module written in Rust.".as_ptr(),
80 m_size: 0,
81 m_methods: std::ptr::addr_of_mut!(METHODS).cast(),
82 m_slots: std::ptr::addr_of_mut!(SLOTS).cast(),
83 m_traverse: None,
84 m_clear: None,
85 m_free: None,
86 };
87
88 static mut METHODS: [PyMethodDef; 2] = [
89 PyMethodDef {
90 ml_name: c"sum_as_string".as_ptr(),
91 ml_meth: PyMethodDefPointer {
92 PyCFunctionFast: sum_as_string,
93 },
94 ml_flags: METH_FASTCALL,
95 ml_doc: c"returns the sum of two integers as a string".as_ptr(),
96 },
97 // A zeroed PyMethodDef to mark the end of the array.
98 PyMethodDef::zeroed(),
99 ];
100
101 #[cfg(Py_3_15)]
102 PyABIInfo_VAR!(ABI_INFO);
103
104 const SLOTS_LEN: usize =
105 1 + cfg!(Py_3_12) as usize + cfg!(Py_GIL_DISABLED) as usize + 4 * (cfg!(Py_3_15) as usize);
106 static mut SLOTS: [PyModuleDef_Slot; SLOTS_LEN] = [
107 #[cfg(Py_3_15)]
108 PyModuleDef_Slot {
109 slot: Py_mod_abi,
110 value: std::ptr::addr_of_mut!(ABI_INFO).cast(),
111 },
112 #[cfg(Py_3_15)]
113 PyModuleDef_Slot {
114 slot: Py_mod_name,
115 // safety: Python does not write to this field
116 value: c"string_sum".as_ptr() as *mut c_void,
117 },
118 #[cfg(Py_3_15)]
119 PyModuleDef_Slot {
120 slot: Py_mod_doc,
121 // safety: Python does not write to this field
122 value: c"A Python module written in Rust.".as_ptr() as *mut c_void,
123 },
124 #[cfg(Py_3_15)]
125 PyModuleDef_Slot {
126 slot: Py_mod_methods,
127 value: std::ptr::addr_of_mut!(METHODS).cast(),
128 },
129 #[cfg(Py_3_12)]
130 PyModuleDef_Slot {
131 slot: Py_mod_multiple_interpreters,
132 value: Py_MOD_PER_INTERPRETER_GIL_SUPPORTED,
133 },
134 #[cfg(Py_GIL_DISABLED)]
135 PyModuleDef_Slot {
136 slot: Py_mod_gil,
137 value: Py_MOD_GIL_NOT_USED,
138 },
139 PyModuleDef_Slot {
140 slot: 0,
141 value: ptr::null_mut(),
142 },
143 ];
144
145 // The module initialization function
146 #[cfg(not(Py_3_15))]
147 #[allow(non_snake_case, reason = "must be named `PyInit_<your_module>`")]
148 #[no_mangle]
149 pub unsafe extern "C" fn PyInit_string_sum() -> *mut PyObject {
150 PyModuleDef_Init(ptr::addr_of_mut!(MODULE_DEF))
151 }
152
153 #[cfg(Py_3_15)]
154 #[allow(non_snake_case, reason = "must be named `PyModExport_<your_module>`")]
155 #[no_mangle]
156 pub unsafe extern "C" fn PyModExport_string_sum() -> *mut PyModuleDef_Slot {
157 std::ptr::addr_of_mut!(SLOTS).cast()
158 }
159
160 /// A helper to parse function arguments
161 /// If we used PyO3's proc macros they'd handle all of this boilerplate for us :)
162 unsafe fn parse_arg_as_i32(obj: *mut PyObject, n_arg: usize) -> Option<i32> {
163 if PyLong_Check(obj) == 0 {
164 let msg = format!(
165 "sum_as_string expected an int for positional argument {}\0",
166 n_arg
167 );
168 PyErr_SetString(PyExc_TypeError, msg.as_ptr().cast::<c_char>());
169 return None;
170 }
171
172 // Let's keep the behaviour consistent on platforms where `c_long` is bigger than 32 bits.
173 // In particular, it is an i32 on Windows but i64 on most Linux systems
174 let mut overflow = 0;
175 let i_long: c_long = PyLong_AsLongAndOverflow(obj, &mut overflow);
176
177 #[allow(
178 irrefutable_let_patterns,
179 reason = "some platforms have c_long equal to i32"
180 )]
181 if overflow != 0 {
182 raise_overflowerror(obj);
183 None
184 } else if let Ok(i) = i_long.try_into() {
185 Some(i)
186 } else {
187 raise_overflowerror(obj);
188 None
189 }
190 }
191
192 unsafe fn raise_overflowerror(obj: *mut PyObject) {
193 let obj_repr = PyObject_Str(obj);
194 if !obj_repr.is_null() {
195 let mut size = 0;
196 let p = PyUnicode_AsUTF8AndSize(obj_repr, &mut size);
197 if !p.is_null() {
198 let s = std::str::from_utf8_unchecked(std::slice::from_raw_parts(
199 p.cast::<u8>(),
200 size as usize,
201 ));
202 let msg = format!("cannot fit {} in 32 bits\0", s);
203
204 PyErr_SetString(PyExc_OverflowError, msg.as_ptr().cast::<c_char>());
205 }
206 Py_DECREF(obj_repr);
207 }
208 }
209
210 pub unsafe extern "C" fn sum_as_string(
211 _self: *mut PyObject,
212 args: *mut *mut PyObject,
213 nargs: Py_ssize_t,
214 ) -> *mut PyObject {
215 if nargs != 2 {
216 PyErr_SetString(
217 PyExc_TypeError,
218 c"sum_as_string expected 2 positional arguments".as_ptr(),
219 );
220 return std::ptr::null_mut();
221 }
222
223 let (first, second) = (*args, *args.add(1));
224
225 let first = match parse_arg_as_i32(first, 1) {
226 Some(x) => x,
227 None => return std::ptr::null_mut(),
228 };
229 let second = match parse_arg_as_i32(second, 2) {
230 Some(x) => x,
231 None => return std::ptr::null_mut(),
232 };
233
234 match first.checked_add(second) {
235 Some(sum) => {
236 let string = sum.to_string();
237 PyUnicode_FromStringAndSize(string.as_ptr().cast::<c_char>(), string.len() as isize)
238 }
239 None => {
240 PyErr_SetString(PyExc_OverflowError, c"arguments too large to add".as_ptr());
241 std::ptr::null_mut()
242 }
243 }
244 }
245 ```
246
247 With those two files in place, now `maturin` needs to be installed. This can be done using
248 Python's package manager `pip`. First, load up a new Python `virtualenv`, and install `maturin`
249 into it:
250 ```bash
251 $ cd string_sum
252 $ python -m venv .env
253 $ source .env/bin/activate
254 $ pip install maturin
255 ```
256
257 Now build and execute the module:
258 ```bash
259 $ maturin develop
260 # lots of progress output as maturin runs the compilation...
261 $ python
262 >>> import string_sum
263 >>> string_sum.sum_as_string(5, 20)
264 '25'
265 ```
266
267 As well as with `maturin`, it is possible to build using [setuptools-rust] or
268 [manually][manual_builds]. Both offer more flexibility than `maturin` but require further
269 configuration.
270
271
272 While most projects use the safe wrapper provided by PyO3,
273 you can take a look at the [`orjson`] library as an example on how to use `pyo3-ffi` directly.
274 For those well versed in C and Rust the [tutorials] from the CPython documentation
275 can be easily converted to rust as well.
276
277 [tutorials]: https://docs.python.org/3/extending/
278 [`orjson`]: https://github.com/ijl/orjson
279 [capi]: https://docs.python.org/3/c-api/index.html
280 [`maturin`]: https://github.com/PyO3/maturin "Build and publish crates with pyo3, rust-cpython and cffi bindings as well as rust binaries as python packages"
281 [`pyo3-build-config`]: https://docs.rs/pyo3-build-config
282 [feature flags]: https://doc.rust-lang.org/cargo/reference/features.html "Features - The Cargo Book"
283 [manual_builds]: https://pyo3.rs/latest/building-and-distribution.html#manual-builds "Manual builds - Building and Distribution - PyO3 user guide"
284 [setuptools-rust]: https://github.com/PyO3/setuptools-rust "Setuptools plugin for Rust extensions"
285 [PEP 384]: https://www.python.org/dev/peps/pep-0384 "PEP 384 -- Defining a Stable ABI"
286 [Features chapter of the guide]: https://pyo3.rs/latest/features.html#features-reference "Features Reference - PyO3 user guide"