Skip to main content

rustpython_capi/
lib.rs

1#![allow(clippy::missing_safety_doc)]
2
3use crate::pyerrors::init_exception_statics;
4use crate::pylifecycle::{MAIN_INTERP, MAIN_INTERP_PTR};
5use core::sync::atomic::Ordering;
6pub use rustpython_vm::PyObject;
7use rustpython_vm::{Context, Interpreter};
8use std::sync::MutexGuard;
9
10extern crate alloc;
11
12pub mod abstract_;
13pub mod boolobject;
14pub mod bytearrayobject;
15pub mod bytesobject;
16pub mod ceval;
17pub mod codecs;
18pub mod complexobject;
19pub mod critical_section;
20pub mod descrobject;
21pub mod dictobject;
22pub mod floatobject;
23pub mod genericaliasobject;
24pub mod import;
25pub mod iterobject;
26pub mod listobject;
27pub mod longobject;
28pub mod memoryobject;
29pub mod methodobject;
30pub mod moduleobject;
31pub mod object;
32pub mod objimpl;
33pub mod osmodule;
34pub mod pycapsule;
35pub mod pyerrors;
36pub mod pyframe;
37pub mod pylifecycle;
38pub mod pymem;
39pub mod pystate;
40pub mod pystrcmp;
41pub mod refcount;
42pub mod setobject;
43pub mod sliceobject;
44pub mod traceback;
45pub mod tupleobject;
46pub mod unicodeobject;
47mod util;
48pub mod warnings;
49pub mod weakrefobject;
50
51/// Get main interpreter of this process. Will be None if it has not been initialized yet.
52pub fn get_main_interpreter() -> MutexGuard<'static, Option<Interpreter>> {
53    MAIN_INTERP
54        .lock()
55        .expect("Failed to lock interpreter mutex")
56}
57
58/// Set the main interpreter of this process. This method will panic when there is already an
59/// interpreter set.
60pub fn init_main_interpreter(interpreter: Interpreter) {
61    let mut interp = get_main_interpreter();
62    assert!(interp.is_none(), "Main interpreter is already set");
63    // Safety: Interpreter was not initialized before, so we can safely assume the statics are not used
64    unsafe { init_exception_statics(&Context::genesis().exceptions) };
65    *interp = Some(interpreter);
66    MAIN_INTERP_PTR.store(
67        interp.as_ref().unwrap() as *const _ as *mut _,
68        Ordering::Release,
69    );
70}