pyo3_ffi/
lib.rs

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//! use std::ffi::{c_char, c_long};
130//! use std::ptr;
131//!
132//! use pyo3_ffi::*;
133//!
134//! static mut MODULE_DEF: PyModuleDef = PyModuleDef {
135//!     m_base: PyModuleDef_HEAD_INIT,
136//!     m_name: c"string_sum".as_ptr(),
137//!     m_doc: c"A Python module written in Rust.".as_ptr(),
138//!     m_size: 0,
139//!     m_methods: unsafe { METHODS as *const [PyMethodDef] as *mut PyMethodDef },
140//!     m_slots: std::ptr::null_mut(),
141//!     m_traverse: None,
142//!     m_clear: None,
143//!     m_free: None,
144//! };
145//!
146//! static mut METHODS: &[PyMethodDef] = &[
147//!     PyMethodDef {
148//!         ml_name: c"sum_as_string".as_ptr(),
149//!         ml_meth: PyMethodDefPointer {
150//!             PyCFunctionFast: sum_as_string,
151//!         },
152//!         ml_flags: METH_FASTCALL,
153//!         ml_doc: c"returns the sum of two integers as a string".as_ptr(),
154//!     },
155//!     // A zeroed PyMethodDef to mark the end of the array.
156//!     PyMethodDef::zeroed(),
157//! ];
158//!
159//! // The module initialization function.
160//! #[allow(non_snake_case, reason = "must be named `PyInit_<your_module>`")]
161//! #[no_mangle]
162//! pub unsafe extern "C" fn PyInit_string_sum() -> *mut PyObject {
163//!     let module = PyModule_Create(ptr::addr_of_mut!(MODULE_DEF));
164//!     if module.is_null() {
165//!         return module;
166//!     }
167//!     #[cfg(Py_GIL_DISABLED)]
168//!     {
169//!         if PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED) < 0 {
170//!             Py_DECREF(module);
171//!             return std::ptr::null_mut();
172//!         }
173//!     }
174//!     module
175//! }
176//!
177//! /// A helper to parse function arguments
178//! /// If we used PyO3's proc macros they'd handle all of this boilerplate for us :)
179//! unsafe fn parse_arg_as_i32(obj: *mut PyObject, n_arg: usize) -> Option<i32> {
180//!     if PyLong_Check(obj) == 0 {
181//!         let msg = format!(
182//!             "sum_as_string expected an int for positional argument {}\0",
183//!             n_arg
184//!         );
185//!         PyErr_SetString(PyExc_TypeError, msg.as_ptr().cast::<c_char>());
186//!         return None;
187//!     }
188//!
189//!     // Let's keep the behaviour consistent on platforms where `c_long` is bigger than 32 bits.
190//!     // In particular, it is an i32 on Windows but i64 on most Linux systems
191//!     let mut overflow = 0;
192//!     let i_long: c_long = PyLong_AsLongAndOverflow(obj, &mut overflow);
193//!
194//!     #[allow(irrefutable_let_patterns, reason = "some platforms have c_long equal to i32")]
195//!     if overflow != 0 {
196//!         raise_overflowerror(obj);
197//!         None
198//!     } else if let Ok(i) = i_long.try_into() {
199//!         Some(i)
200//!     } else {
201//!         raise_overflowerror(obj);
202//!         None
203//!     }
204//! }
205//!
206//! unsafe fn raise_overflowerror(obj: *mut PyObject) {
207//!     let obj_repr = PyObject_Str(obj);
208//!     if !obj_repr.is_null() {
209//!         let mut size = 0;
210//!         let p = PyUnicode_AsUTF8AndSize(obj_repr, &mut size);
211//!         if !p.is_null() {
212//!             let s = std::str::from_utf8_unchecked(std::slice::from_raw_parts(
213//!                 p.cast::<u8>(),
214//!                 size as usize,
215//!             ));
216//!             let msg = format!("cannot fit {} in 32 bits\0", s);
217//!
218//!             PyErr_SetString(PyExc_OverflowError, msg.as_ptr().cast::<c_char>());
219//!         }
220//!         Py_DECREF(obj_repr);
221//!     }
222//! }
223//!
224//! pub unsafe extern "C" fn sum_as_string(
225//!     _self: *mut PyObject,
226//!     args: *mut *mut PyObject,
227//!     nargs: Py_ssize_t,
228//! ) -> *mut PyObject {
229//!     if nargs != 2 {
230//!         PyErr_SetString(
231//!             PyExc_TypeError,
232//!             c"sum_as_string expected 2 positional arguments".as_ptr(),
233//!         );
234//!         return std::ptr::null_mut();
235//!     }
236//!
237//!     let (first, second) = (*args, *args.add(1));
238//!
239//!     let first = match parse_arg_as_i32(first, 1) {
240//!         Some(x) => x,
241//!         None => return std::ptr::null_mut(),
242//!     };
243//!     let second = match parse_arg_as_i32(second, 2) {
244//!         Some(x) => x,
245//!         None => return std::ptr::null_mut(),
246//!     };
247//!
248//!     match first.checked_add(second) {
249//!         Some(sum) => {
250//!             let string = sum.to_string();
251//!             PyUnicode_FromStringAndSize(string.as_ptr().cast::<c_char>(), string.len() as isize)
252//!         }
253//!         None => {
254//!             PyErr_SetString(
255//!                 PyExc_OverflowError,
256//!                 c"arguments too large to add".as_ptr(),
257//!             );
258//!             std::ptr::null_mut()
259//!         }
260//!     }
261//! }
262//! ```
263//!
264//! With those two files in place, now `maturin` needs to be installed. This can be done using
265//! Python's package manager `pip`. First, load up a new Python `virtualenv`, and install `maturin`
266//! into it:
267//! ```bash
268//! $ cd string_sum
269//! $ python -m venv .env
270//! $ source .env/bin/activate
271//! $ pip install maturin
272//! ```
273//!
274//! Now build and execute the module:
275//! ```bash
276//! $ maturin develop
277//! # lots of progress output as maturin runs the compilation...
278//! $ python
279//! >>> import string_sum
280//! >>> string_sum.sum_as_string(5, 20)
281//! '25'
282//! ```
283//!
284//! As well as with `maturin`, it is possible to build using [setuptools-rust] or
285//! [manually][manual_builds]. Both offer more flexibility than `maturin` but require further
286//! configuration.
287//!
288//! This example stores the module definition statically and uses the `PyModule_Create` function
289//! in the CPython C API to register the module. This is the "old" style for registering modules
290//! and has the limitation that it cannot support subinterpreters. You can also create a module
291//! using the new multi-phase initialization API that does support subinterpreters. See the
292//! `sequential` project located in the `examples` directory at the root of the `pyo3-ffi` crate
293//! for a worked example of how to this using `pyo3-ffi`.
294//!
295//! # Using Python from Rust
296//!
297//! To embed Python into a Rust binary, you need to ensure that your Python installation contains a
298//! shared library. The following steps demonstrate how to ensure this (for Ubuntu).
299//!
300//! To install the Python shared library on Ubuntu:
301//! ```bash
302//! sudo apt install python3-dev
303//! ```
304//!
305//! While most projects use the safe wrapper provided by pyo3,
306//! you can take a look at the [`orjson`] library as an example on how to use `pyo3-ffi` directly.
307//! For those well versed in C and Rust the [tutorials] from the CPython documentation
308//! can be easily converted to rust as well.
309//!
310//! [tutorials]: https://docs.python.org/3/extending/
311//! [`orjson`]: https://github.com/ijl/orjson
312//! [capi]: https://docs.python.org/3/c-api/index.html
313//! [`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"
314//! [`pyo3-build-config`]: https://docs.rs/pyo3-build-config
315//! [feature flags]: https://doc.rust-lang.org/cargo/reference/features.html "Features - The Cargo Book"
316#![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\"")]
317//! [setuptools-rust]: https://github.com/PyO3/setuptools-rust "Setuptools plugin for Rust extensions"
318//! [PEP 384]: https://www.python.org/dev/peps/pep-0384 "PEP 384 -- Defining a Stable ABI"
319#![doc = concat!("[Features chapter of the guide]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/features.html#features-reference \"Features reference - PyO3 user guide\"")]
320#![allow(
321    missing_docs,
322    non_camel_case_types,
323    non_snake_case,
324    non_upper_case_globals,
325    clippy::upper_case_acronyms,
326    clippy::missing_safety_doc,
327    clippy::ptr_eq
328)]
329#![warn(elided_lifetimes_in_paths, unused_lifetimes)]
330// This crate is a hand-maintained translation of CPython's headers, so requiring "unsafe"
331// blocks within those translations increases maintenance burden without providing any
332// additional safety. The safety of the functions in this crate is determined by the
333// original CPython headers
334#![allow(unsafe_op_in_unsafe_fn)]
335
336// Until `extern type` is stabilized, use the recommended approach to
337// model opaque types:
338// https://doc.rust-lang.org/nomicon/ffi.html#representing-opaque-structs
339macro_rules! opaque_struct {
340    ($(#[$attrs:meta])* $pub:vis $name:ident) => {
341        $(#[$attrs])*
342        #[repr(C)]
343        $pub struct $name([u8; 0]);
344    };
345}
346
347/// This is a helper macro to create a `&'static CStr`.
348///
349/// It can be used on all Rust versions supported by PyO3, unlike c"" literals which
350/// were stabilised in Rust 1.77.
351///
352/// Due to the nature of PyO3 making heavy use of C FFI interop with Python, it is
353/// common for PyO3 to use CStr.
354///
355/// Examples:
356///
357/// ```rust,no_run
358/// use std::ffi::CStr;
359///
360/// const HELLO: &CStr = pyo3_ffi::c_str!("hello");
361/// static WORLD: &CStr = pyo3_ffi::c_str!("world");
362/// ```
363#[macro_export]
364macro_rules! c_str {
365    // TODO: deprecate this now MSRV is above 1.77
366    ($s:expr) => {
367        $crate::_cstr_from_utf8_with_nul_checked(concat!($s, "\0"))
368    };
369}
370
371/// Private helper for `c_str!` macro.
372#[doc(hidden)]
373pub const fn _cstr_from_utf8_with_nul_checked(s: &str) -> &std::ffi::CStr {
374    match std::ffi::CStr::from_bytes_with_nul(s.as_bytes()) {
375        Ok(cstr) => cstr,
376        Err(_) => panic!("string contains nul bytes"),
377    }
378}
379
380pub mod compat;
381mod impl_;
382
383pub use self::abstract_::*;
384pub use self::bltinmodule::*;
385pub use self::boolobject::*;
386pub use self::bytearrayobject::*;
387pub use self::bytesobject::*;
388pub use self::ceval::*;
389#[cfg(Py_LIMITED_API)]
390pub use self::code::*;
391pub use self::codecs::*;
392pub use self::compile::*;
393pub use self::complexobject::*;
394#[cfg(all(Py_3_8, not(Py_LIMITED_API)))]
395pub use self::context::*;
396#[cfg(not(Py_LIMITED_API))]
397pub use self::datetime::*;
398pub use self::descrobject::*;
399pub use self::dictobject::*;
400pub use self::enumobject::*;
401pub use self::fileobject::*;
402pub use self::fileutils::*;
403pub use self::floatobject::*;
404#[cfg(Py_3_9)]
405pub use self::genericaliasobject::*;
406pub use self::import::*;
407pub use self::intrcheck::*;
408pub use self::iterobject::*;
409pub use self::listobject::*;
410pub use self::longobject::*;
411#[cfg(not(Py_LIMITED_API))]
412pub use self::marshal::*;
413pub use self::memoryobject::*;
414pub use self::methodobject::*;
415pub use self::modsupport::*;
416pub use self::moduleobject::*;
417pub use self::object::*;
418pub use self::objimpl::*;
419pub use self::osmodule::*;
420#[cfg(not(any(PyPy, Py_LIMITED_API, Py_3_10)))]
421pub use self::pyarena::*;
422#[cfg(Py_3_11)]
423pub use self::pybuffer::*;
424pub use self::pycapsule::*;
425pub use self::pyerrors::*;
426pub use self::pyframe::*;
427pub use self::pyhash::*;
428pub use self::pylifecycle::*;
429pub use self::pymem::*;
430pub use self::pyport::*;
431pub use self::pystate::*;
432pub use self::pystrtod::*;
433pub use self::pythonrun::*;
434pub use self::pytypedefs::*;
435pub use self::rangeobject::*;
436pub use self::refcount::*;
437pub use self::setobject::*;
438pub use self::sliceobject::*;
439pub use self::structseq::*;
440pub use self::sysmodule::*;
441pub use self::traceback::*;
442pub use self::tupleobject::*;
443pub use self::typeslots::*;
444pub use self::unicodeobject::*;
445pub use self::warnings::*;
446pub use self::weakrefobject::*;
447
448mod abstract_;
449// skipped asdl.h
450// skipped ast.h
451mod bltinmodule;
452mod boolobject;
453mod bytearrayobject;
454mod bytesobject;
455// skipped cellobject.h
456mod ceval;
457// skipped classobject.h
458#[cfg(Py_LIMITED_API)]
459mod code;
460mod codecs;
461mod compile;
462mod complexobject;
463#[cfg(all(Py_3_8, not(Py_LIMITED_API)))]
464mod context; // It's actually 3.7.1, but no cfg for patches.
465#[cfg(not(Py_LIMITED_API))]
466pub(crate) mod datetime;
467mod descrobject;
468mod dictobject;
469// skipped dynamic_annotations.h
470mod enumobject;
471// skipped errcode.h
472// skipped exports.h
473mod fileobject;
474mod fileutils;
475mod floatobject;
476// skipped empty frameobject.h
477mod genericaliasobject;
478mod import;
479// skipped interpreteridobject.h
480mod intrcheck;
481mod iterobject;
482mod listobject;
483// skipped longintrepr.h
484mod longobject;
485#[cfg(not(Py_LIMITED_API))]
486pub mod marshal;
487mod memoryobject;
488mod methodobject;
489mod modsupport;
490mod moduleobject;
491// skipped namespaceobject.h
492mod object;
493mod objimpl;
494// skipped odictobject.h
495// skipped opcode.h
496// skipped osdefs.h
497mod osmodule;
498// skipped parser_interface.h
499// skipped patchlevel.h
500// skipped picklebufobject.h
501// skipped pyctype.h
502// skipped py_curses.h
503#[cfg(not(any(PyPy, Py_LIMITED_API, Py_3_10)))]
504mod pyarena;
505#[cfg(Py_3_11)]
506mod pybuffer;
507mod pycapsule;
508// skipped pydtrace.h
509mod pyerrors;
510// skipped pyexpat.h
511// skipped pyfpe.h
512mod pyframe;
513mod pyhash;
514mod pylifecycle;
515// skipped pymacconfig.h
516// skipped pymacro.h
517// skipped pymath.h
518mod pymem;
519mod pyport;
520mod pystate;
521// skipped pystats.h
522mod pythonrun;
523// skipped pystrhex.h
524// skipped pystrcmp.h
525mod pystrtod;
526// skipped pythread.h
527// skipped pytime.h
528mod pytypedefs;
529mod rangeobject;
530mod refcount;
531mod setobject;
532mod sliceobject;
533mod structseq;
534mod sysmodule;
535mod traceback;
536// skipped tracemalloc.h
537mod tupleobject;
538mod typeslots;
539mod unicodeobject;
540mod warnings;
541mod weakrefobject;
542
543// Additional headers that are not exported by Python.h
544#[deprecated(note = "Python 3.12")]
545pub mod structmember;
546
547// "Limited API" definitions matching Python's `include/cpython` directory.
548#[cfg(not(Py_LIMITED_API))]
549mod cpython;
550
551#[cfg(not(Py_LIMITED_API))]
552pub use self::cpython::*;