Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 #![cfg_attr(docsrs, feature(doc_cfg))]
2 //! Raw FFI declarations for Python's C API.
3 //!
4 //! PyO3 can be used to write native Python modules or run Python code and modules from Rust.
5 //!
6 //! This crate just provides low level bindings to the Python interpreter.
7 //! It is meant for advanced users only - regular PyO3 users shouldn't
8 //! need to interact with this crate at all.
9 //!
10 //! The contents of this crate are not documented here, as it would entail
11 //! basically copying the documentation from CPython. Consult the [Python/C API Reference
12 //! Manual][capi] for up-to-date documentation.
13 //!
14 //! # Safety
15 //!
16 //! The functions in this crate lack individual safety documentation, but
17 //! generally the following apply:
18 //! - Pointer arguments have to point to a valid Python object of the correct type,
19 //! although null pointers are sometimes valid input.
20 //! - The vast majority can only be used safely while the thread is attached to the Python interpreter.
21 //! - Some functions have additional safety requirements, consult the
22 //! [Python/C API Reference Manual][capi]
23 //! for more information.
24 //!
25 //!
26 //! # Feature flags
27 //!
28 //! PyO3 uses [feature flags] to enable you to opt-in to additional functionality. For a detailed
29 //! description, see the [Features chapter of the guide].
30 //!
31 //! ## Optional feature flags
32 //!
33 //! The following features customize PyO3's behavior:
34 //!
35 //! - `abi3`: Restricts PyO3's API to a subset of the full Python API which is guaranteed by
36 //! [PEP 384] to be forward-compatible with future Python versions.
37 //!
38 //! ## `rustc` environment flags
39 //!
40 //! PyO3 uses `rustc`'s `--cfg` flags to enable or disable code used for different Python versions.
41 //! If you want to do this for your own crate, you can do so with the [`pyo3-build-config`] crate.
42 //!
43 //! - `Py_3_7`, `Py_3_8`, `Py_3_9`, `Py_3_10`, `Py_3_11`, `Py_3_12`, `Py_3_13`: Marks code that is
44 //! only enabled when compiling for a given minimum Python version.
45 //! - `Py_LIMITED_API`: Marks code enabled when the `abi3` feature flag is enabled.
46 //! - `Py_GIL_DISABLED`: Marks code that runs only in the free-threaded build of CPython.
47 //! - `PyPy` - Marks code enabled when compiling for PyPy.
48 //! - `GraalPy` - Marks code enabled when compiling for GraalPy.
49 //!
50 //! Additionally, you can query for the values `Py_DEBUG`, `Py_REF_DEBUG`,
51 //! `Py_TRACE_REFS`, and `COUNT_ALLOCS` from `py_sys_config` to query for the
52 //! corresponding C build-time defines. For example, to conditionally define
53 //! debug code using `Py_DEBUG`, you could do:
54 //!
55 //! ```rust,ignore
56 //! #[cfg(py_sys_config = "Py_DEBUG")]
57 //! println!("only runs if python was compiled with Py_DEBUG")
58 //! ```
59 //!
60 //! To use these attributes, add [`pyo3-build-config`] as a build dependency in
61 //! your `Cargo.toml`:
62 //!
63 //! ```toml
64 //! [build-dependencies]
65 #![doc = concat!("pyo3-build-config =\"", env!("CARGO_PKG_VERSION"), "\"")]
66 //! ```
67 //!
68 //! And then either create a new `build.rs` file in the project root or modify
69 //! the existing `build.rs` file to call `use_pyo3_cfgs()`:
70 //!
71 //! ```rust,ignore
72 //! fn main() {
73 //! pyo3_build_config::use_pyo3_cfgs();
74 //! }
75 //! ```
76 //!
77 //! # Minimum supported Rust and Python versions
78 //!
79 //! `pyo3-ffi` supports the following Python distributions:
80 //! - CPython 3.7 or greater
81 //! - PyPy 7.3 (Python 3.11+)
82 //! - GraalPy 24.0 or greater (Python 3.10+)
83 //!
84 //! # Example: Building Python Native modules
85 //!
86 //! PyO3 can be used to generate a native Python module. The easiest way to try this out for the
87 //! first time is to use [`maturin`]. `maturin` is a tool for building and publishing Rust-based
88 //! Python packages with minimal configuration. The following steps set up some files for an example
89 //! Python module, install `maturin`, and then show how to build and import the Python module.
90 //!
91 //! First, create a new folder (let's call it `string_sum`) containing the following two files:
92 //!
93 //! **`Cargo.toml`**
94 //!
95 //! ```toml
96 //! [lib]
97 //! name = "string_sum"
98 //! # "cdylib" is necessary to produce a shared library for Python to import from.
99 //! #
100 //! # Downstream Rust code (including code in `bin/`, `examples/`, and `tests/`) will not be able
101 //! # to `use string_sum;` unless the "rlib" or "lib" crate type is also included, e.g.:
102 //! # crate-type = ["cdylib", "rlib"]
103 //! crate-type = ["cdylib"]
104 //!
105 //! [dependencies]
106 #![doc = concat!("pyo3-ffi = \"", env!("CARGO_PKG_VERSION"), "\"")]
107 //!
108 //! [build-dependencies]
109 //! # This is only necessary if you need to configure your build based on
110 //! # the Python version or the compile-time configuration for the interpreter.
111 #![doc = concat!("pyo3_build_config = \"", env!("CARGO_PKG_VERSION"), "\"")]
112 //! ```
113 //!
114 //! If you need to use conditional compilation based on Python version or how
115 //! Python was compiled, you need to add `pyo3-build-config` as a
116 //! `build-dependency` in your `Cargo.toml` as in the example above and either
117 //! create a new `build.rs` file or modify an existing one so that
118 //! `pyo3_build_config::use_pyo3_cfgs()` gets called at build time:
119 //!
120 //! **`build.rs`**
121 //! ```rust,ignore
122 //! fn main() {
123 //! pyo3_build_config::use_pyo3_cfgs()
124 //! }
125 //! ```
126 //!
127 //! **`src/lib.rs`**
128 //! ```rust,no_run
129 //! #[cfg(Py_3_15)]
130 //! use std::ffi::c_void;
131 //! use std::ffi::{c_char, c_long};
132 //! use std::ptr;
133 //!
134 //! use pyo3_ffi::*;
135 //!
136 //! #[cfg(not(Py_3_15))]
137 //! static mut MODULE_DEF: PyModuleDef = PyModuleDef {
138 //! m_base: PyModuleDef_HEAD_INIT,
139 //! m_name: c"string_sum".as_ptr(),
140 //! m_doc: c"A Python module written in Rust.".as_ptr(),
141 //! m_size: 0,
142 //! m_methods: std::ptr::addr_of_mut!(METHODS).cast(),
143 //! m_slots: std::ptr::addr_of_mut!(SLOTS).cast(),
144 //! m_traverse: None,
145 //! m_clear: None,
146 //! m_free: None,
147 //! };
148 //!
149 //! static mut METHODS: [PyMethodDef; 2] = [
150 //! PyMethodDef {
151 //! ml_name: c"sum_as_string".as_ptr(),
152 //! ml_meth: PyMethodDefPointer {
153 //! PyCFunctionFast: sum_as_string,
154 //! },
155 //! ml_flags: METH_FASTCALL,
156 //! ml_doc: c"returns the sum of two integers as a string".as_ptr(),
157 //! },
158 //! // A zeroed PyMethodDef to mark the end of the array.
159 //! PyMethodDef::zeroed(),
160 //! ];
161 //!
162 //! #[cfg(Py_3_15)]
163 //! PyABIInfo_VAR!(ABI_INFO);
164 //!
165 //! const SLOTS_LEN: usize =
166 //! 1 + cfg!(Py_3_12) as usize + cfg!(Py_GIL_DISABLED) as usize + 4 * (cfg!(Py_3_15) as usize);
167 //! static mut SLOTS: [PyModuleDef_Slot; SLOTS_LEN] = [
168 //! #[cfg(Py_3_15)]
169 //! PyModuleDef_Slot {
170 //! slot: Py_mod_abi,
171 //! value: std::ptr::addr_of_mut!(ABI_INFO).cast(),
172 //! },
173 //! #[cfg(Py_3_15)]
174 //! PyModuleDef_Slot {
175 //! slot: Py_mod_name,
176 //! // safety: Python does not write to this field
177 //! value: c"string_sum".as_ptr() as *mut c_void,
178 //! },
179 //! #[cfg(Py_3_15)]
180 //! PyModuleDef_Slot {
181 //! slot: Py_mod_doc,
182 //! // safety: Python does not write to this field
183 //! value: c"A Python module written in Rust.".as_ptr() as *mut c_void,
184 //! },
185 //! #[cfg(Py_3_15)]
186 //! PyModuleDef_Slot {
187 //! slot: Py_mod_methods,
188 //! value: std::ptr::addr_of_mut!(METHODS).cast(),
189 //! },
190 //! #[cfg(Py_3_12)]
191 //! PyModuleDef_Slot {
192 //! slot: Py_mod_multiple_interpreters,
193 //! value: Py_MOD_PER_INTERPRETER_GIL_SUPPORTED,
194 //! },
195 //! #[cfg(Py_GIL_DISABLED)]
196 //! PyModuleDef_Slot {
197 //! slot: Py_mod_gil,
198 //! value: Py_MOD_GIL_NOT_USED,
199 //! },
200 //! PyModuleDef_Slot {
201 //! slot: 0,
202 //! value: ptr::null_mut(),
203 //! },
204 //! ];
205 //!
206 //! // The module initialization function
207 //! #[cfg(not(Py_3_15))]
208 //! #[allow(non_snake_case, reason = "must be named `PyInit_<your_module>`")]
209 //! #[no_mangle]
210 //! pub unsafe extern "C" fn PyInit_string_sum() -> *mut PyObject {
211 //! PyModuleDef_Init(ptr::addr_of_mut!(MODULE_DEF))
212 //! }
213 //!
214 //! #[cfg(Py_3_15)]
215 //! #[allow(non_snake_case, reason = "must be named `PyModExport_<your_module>`")]
216 //! #[no_mangle]
217 //! pub unsafe extern "C" fn PyModExport_string_sum() -> *mut PyModuleDef_Slot {
218 //! std::ptr::addr_of_mut!(SLOTS).cast()
219 //! }
220 //!
221 //! /// A helper to parse function arguments
222 //! /// If we used PyO3's proc macros they'd handle all of this boilerplate for us :)
223 //! unsafe fn parse_arg_as_i32(obj: *mut PyObject, n_arg: usize) -> Option<i32> {
224 //! if PyLong_Check(obj) == 0 {
225 //! let msg = format!(
226 //! "sum_as_string expected an int for positional argument {}\0",
227 //! n_arg
228 //! );
229 //! PyErr_SetString(PyExc_TypeError, msg.as_ptr().cast::<c_char>());
230 //! return None;
231 //! }
232 //!
233 //! // Let's keep the behaviour consistent on platforms where `c_long` is bigger than 32 bits.
234 //! // In particular, it is an i32 on Windows but i64 on most Linux systems
235 //! let mut overflow = 0;
236 //! let i_long: c_long = PyLong_AsLongAndOverflow(obj, &mut overflow);
237 //!
238 //! #[allow(
239 //! irrefutable_let_patterns,
240 //! reason = "some platforms have c_long equal to i32"
241 //! )]
242 //! if overflow != 0 {
243 //! raise_overflowerror(obj);
244 //! None
245 //! } else if let Ok(i) = i_long.try_into() {
246 //! Some(i)
247 //! } else {
248 //! raise_overflowerror(obj);
249 //! None
250 //! }
251 //! }
252 //!
253 //! unsafe fn raise_overflowerror(obj: *mut PyObject) {
254 //! let obj_repr = PyObject_Str(obj);
255 //! if !obj_repr.is_null() {
256 //! let mut size = 0;
257 //! let p = PyUnicode_AsUTF8AndSize(obj_repr, &mut size);
258 //! if !p.is_null() {
259 //! let s = std::str::from_utf8_unchecked(std::slice::from_raw_parts(
260 //! p.cast::<u8>(),
261 //! size as usize,
262 //! ));
263 //! let msg = format!("cannot fit {} in 32 bits\0", s);
264 //!
265 //! PyErr_SetString(PyExc_OverflowError, msg.as_ptr().cast::<c_char>());
266 //! }
267 //! Py_DECREF(obj_repr);
268 //! }
269 //! }
270 //!
271 //! pub unsafe extern "C" fn sum_as_string(
272 //! _self: *mut PyObject,
273 //! args: *mut *mut PyObject,
274 //! nargs: Py_ssize_t,
275 //! ) -> *mut PyObject {
276 //! if nargs != 2 {
277 //! PyErr_SetString(
278 //! PyExc_TypeError,
279 //! c"sum_as_string expected 2 positional arguments".as_ptr(),
280 //! );
281 //! return std::ptr::null_mut();
282 //! }
283 //!
284 //! let (first, second) = (*args, *args.add(1));
285 //!
286 //! let first = match parse_arg_as_i32(first, 1) {
287 //! Some(x) => x,
288 //! None => return std::ptr::null_mut(),
289 //! };
290 //! let second = match parse_arg_as_i32(second, 2) {
291 //! Some(x) => x,
292 //! None => return std::ptr::null_mut(),
293 //! };
294 //!
295 //! match first.checked_add(second) {
296 //! Some(sum) => {
297 //! let string = sum.to_string();
298 //! PyUnicode_FromStringAndSize(string.as_ptr().cast::<c_char>(), string.len() as isize)
299 //! }
300 //! None => {
301 //! PyErr_SetString(PyExc_OverflowError, c"arguments too large to add".as_ptr());
302 //! std::ptr::null_mut()
303 //! }
304 //! }
305 //! }
306 //! ```
307 //!
308 //! With those two files in place, now `maturin` needs to be installed. This can be done using
309 //! Python's package manager `pip`. First, load up a new Python `virtualenv`, and install `maturin`
310 //! into it:
311 //! ```bash
312 //! $ cd string_sum
313 //! $ python -m venv .env
314 //! $ source .env/bin/activate
315 //! $ pip install maturin
316 //! ```
317 //!
318 //! Now build and execute the module:
319 //! ```bash
320 //! $ maturin develop
321 //! # lots of progress output as maturin runs the compilation...
322 //! $ python
323 //! >>> import string_sum
324 //! >>> string_sum.sum_as_string(5, 20)
325 //! '25'
326 //! ```
327 //!
328 //! As well as with `maturin`, it is possible to build using [setuptools-rust] or
329 //! [manually][manual_builds]. Both offer more flexibility than `maturin` but require further
330 //! configuration.
331 //!
332 //! This example stores the module definition statically and uses the `PyModule_Create` function
333 //! in the CPython C API to register the module. This is the "old" style for registering modules
334 //! and has the limitation that it cannot support subinterpreters. You can also create a module
335 //! using the new multi-phase initialization API that does support subinterpreters. See the
336 //! `sequential` project located in the `examples` directory at the root of the `pyo3-ffi` crate
337 //! for a worked example of how to this using `pyo3-ffi`.
338 //!
339 //! # Using Python from Rust
340 //!
341 //! To embed Python into a Rust binary, you need to ensure that your Python installation contains a
342 //! shared library. The following steps demonstrate how to ensure this (for Ubuntu).
343 //!
344 //! To install the Python shared library on Ubuntu:
345 //! ```bash
346 //! sudo apt install python3-dev
347 //! ```
348 //!
349 //! While most projects use the safe wrapper provided by pyo3,
350 //! you can take a look at the [`orjson`] library as an example on how to use `pyo3-ffi` directly.
351 //! For those well versed in C and Rust the [tutorials] from the CPython documentation
352 //! can be easily converted to rust as well.
353 //!
354 //! [tutorials]: https://docs.python.org/3/extending/
355 //! [`orjson`]: https://github.com/ijl/orjson
356 //! [capi]: https://docs.python.org/3/c-api/index.html
357 //! [`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"
358 //! [`pyo3-build-config`]: https://docs.rs/pyo3-build-config
359 //! [feature flags]: https://doc.rust-lang.org/cargo/reference/features.html "Features - The Cargo Book"
360 #![doc = concat!("[manual_builds]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/building-and-distribution.html#manual-builds \"Manual builds - Building and Distribution - PyO3 user guide\"")]
361 //! [setuptools-rust]: https://github.com/PyO3/setuptools-rust "Setuptools plugin for Rust extensions"
362 //! [PEP 384]: https://www.python.org/dev/peps/pep-0384 "PEP 384 -- Defining a Stable ABI"
363 #![doc = concat!("[Features chapter of the guide]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/features.html#features-reference \"Features reference - PyO3 user guide\"")]
364 #![allow(
365 missing_docs,
366 non_camel_case_types,
367 non_snake_case,
368 non_upper_case_globals,
369 clippy::upper_case_acronyms,
370 clippy::missing_safety_doc,
371 clippy::ptr_eq
372 )]
373 #![warn(elided_lifetimes_in_paths, unused_lifetimes)]
374 // This crate is a hand-maintained translation of CPython's headers, so requiring "unsafe"
375 // blocks within those translations increases maintenance burden without providing any
376 // additional safety. The safety of the functions in this crate is determined by the
377 // original CPython headers
378 #![allow(unsafe_op_in_unsafe_fn)]
379
380 // Until `extern type` is stabilized, use the recommended approach to
381 // model opaque types:
382 // https://doc.rust-lang.org/nomicon/ffi.html#representing-opaque-structs
383 macro_rules! opaque_struct {
384 ($(#[$attrs:meta])* $pub:vis $name:ident) => {
385 $(#[$attrs])*
386 #[repr(C)]
387 $pub struct $name([u8; 0]);
388 };
389 }
390
391 /// This is a helper macro to create a `&'static CStr`.
392 ///
393 /// It can be used on all Rust versions supported by PyO3, unlike c"" literals which
394 /// were stabilised in Rust 1.77.
395 ///
396 /// Due to the nature of PyO3 making heavy use of C FFI interop with Python, it is
397 /// common for PyO3 to use CStr.
398 ///
399 /// Examples:
400 ///
401 /// ```rust,no_run
402 /// use std::ffi::CStr;
403 ///
404 /// const HELLO: &CStr = pyo3_ffi::c_str!("hello");
405 /// static WORLD: &CStr = pyo3_ffi::c_str!("world");
406 /// ```
407 #[macro_export]
408 macro_rules! c_str {
409 // TODO: deprecate this now MSRV is above 1.77
410 ($s:expr) => {
411 $crate::_cstr_from_utf8_with_nul_checked(concat!($s, "\0"))
412 };
413 }
414
415 /// Private helper for `c_str!` macro.
416 #[doc(hidden)]
417 pub const fn _cstr_from_utf8_with_nul_checked(s: &str) -> &std::ffi::CStr {
418 match std::ffi::CStr::from_bytes_with_nul(s.as_bytes()) {
419 Ok(cstr) => cstr,
420 Err(_) => panic!("string contains nul bytes"),
421 }
422 }
423
424 pub mod compat;
425 mod impl_;
426
427 pub use self::abstract_::*;
428 pub use self::bltinmodule::*;
429 pub use self::boolobject::*;
430 pub use self::bytearrayobject::*;
431 pub use self::bytesobject::*;
432 pub use self::ceval::*;
433 pub use self::codecs::*;
434 pub use self::compile::*;
435 pub use self::complexobject::*;
436 #[cfg(all(Py_3_8, not(Py_LIMITED_API)))]
437 pub use self::context::*;
438 #[cfg(not(Py_LIMITED_API))]
439 pub use self::datetime::*;
440 pub use self::descrobject::*;
441 pub use self::dictobject::*;
442 pub use self::enumobject::*;
443 pub use self::fileobject::*;
444 pub use self::fileutils::*;
445 pub use self::floatobject::*;
446 #[cfg(Py_3_9)]
447 pub use self::genericaliasobject::*;
448 pub use self::import::*;
449 pub use self::intrcheck::*;
450 pub use self::iterobject::*;
451 pub use self::listobject::*;
452 pub use self::longobject::*;
453 #[cfg(not(Py_LIMITED_API))]
454 pub use self::marshal::*;
455 pub use self::memoryobject::*;
456 pub use self::methodobject::*;
457 pub use self::modsupport::*;
458 pub use self::moduleobject::*;
459 pub use self::object::*;
460 pub use self::objimpl::*;
461 pub use self::osmodule::*;
462 #[cfg(not(any(PyPy, Py_LIMITED_API, Py_3_10)))]
463 pub use self::pyarena::*;
464 #[cfg(Py_3_11)]
465 pub use self::pybuffer::*;
466 pub use self::pycapsule::*;
467 pub use self::pyerrors::*;
468 pub use self::pyframe::*;
469 pub use self::pyhash::*;
470 pub use self::pylifecycle::*;
471 pub use self::pymem::*;
472 pub use self::pyport::*;
473 pub use self::pystate::*;
474 pub use self::pystrtod::*;
475 pub use self::pythonrun::*;
476 pub use self::pytypedefs::*;
477 pub use self::rangeobject::*;
478 pub use self::refcount::*;
479 pub use self::setobject::*;
480 pub use self::sliceobject::*;
481 pub use self::structseq::*;
482 pub use self::sysmodule::*;
483 pub use self::traceback::*;
484 pub use self::tupleobject::*;
485 pub use self::typeslots::*;
486 pub use self::unicodeobject::*;
487 pub use self::warnings::*;
488 pub use self::weakrefobject::*;
489
490 mod abstract_;
491 // skipped asdl.h
492 // skipped ast.h
493 mod bltinmodule;
494 mod boolobject;
495 mod bytearrayobject;
496 mod bytesobject;
497 // skipped cellobject.h
498 mod ceval;
499 // skipped classobject.h
500 mod codecs;
501 mod compile;
502 mod complexobject;
503 #[cfg(all(Py_3_8, not(Py_LIMITED_API)))]
504 mod context; // It's actually 3.7.1, but no cfg for patches.
505 #[cfg(not(Py_LIMITED_API))]
506 pub(crate) mod datetime;
507 mod descrobject;
508 mod dictobject;
509 // skipped dynamic_annotations.h
510 mod enumobject;
511 // skipped errcode.h
512 // skipped exports.h
513 mod fileobject;
514 mod fileutils;
515 mod floatobject;
516 // skipped empty frameobject.h
517 mod genericaliasobject;
518 mod import;
519 // skipped interpreteridobject.h
520 mod intrcheck;
521 mod iterobject;
522 mod listobject;
523 // skipped longintrepr.h
524 mod longobject;
525 #[cfg(not(Py_LIMITED_API))]
526 pub mod marshal;
527 mod memoryobject;
528 mod methodobject;
529 mod modsupport;
530 mod moduleobject;
531 // skipped namespaceobject.h
532 mod object;
533 mod objimpl;
534 // skipped odictobject.h
535 // skipped opcode.h
536 // skipped osdefs.h
537 mod osmodule;
538 // skipped parser_interface.h
539 // skipped patchlevel.h
540 // skipped picklebufobject.h
541 // skipped pyctype.h
542 // skipped py_curses.h
543 #[cfg(not(any(PyPy, Py_LIMITED_API, Py_3_10)))]
544 mod pyarena;
545 #[cfg(Py_3_11)]
546 mod pybuffer;
547 mod pycapsule;
548 // skipped pydtrace.h
549 mod pyerrors;
550 // skipped pyexpat.h
551 // skipped pyfpe.h
552 mod pyframe;
553 mod pyhash;
554 mod pylifecycle;
555 // skipped pymacconfig.h
556 // skipped pymacro.h
557 // skipped pymath.h
558 mod pymem;
559 mod pyport;
560 mod pystate;
561 // skipped pystats.h
562 mod pythonrun;
563 // skipped pystrhex.h
564 // skipped pystrcmp.h
565 mod pystrtod;
566 // skipped pythread.h
567 // skipped pytime.h
568 mod pytypedefs;
569 mod rangeobject;
570 mod refcount;
571 mod setobject;
572 mod sliceobject;
573 mod structseq;
574 mod sysmodule;
575 mod traceback;
576 // skipped tracemalloc.h
577 mod tupleobject;
578 mod typeslots;
579 mod unicodeobject;
580 mod warnings;
581 mod weakrefobject;
582
583 // Additional headers that are not exported by Python.h
584 #[deprecated(note = "Python 3.12")]
585 pub mod structmember;
586
587 // "Limited API" definitions matching Python's `include/cpython` directory.
588 #[cfg(not(Py_LIMITED_API))]
589 mod cpython;
590
591 #[cfg(not(Py_LIMITED_API))]
592 pub use self::cpython::*;