Add complex number support to c-api (#7945)

This commit is contained in:
Bas Schoenmaeckers authored and GitHub committed 2026-05-22 20:00:46 +09:00
1 parent f866e0d46d
commit f1572215ef
4 files changed
+55

No files matched your search

Generated
+1
View File
@@ -3231,6 +3231,7 @@ dependencies = [
name = "rustpython-capi"
version = "0.5.0"
dependencies = [
"num-complex",
"pyo3",
"rustpython-stdlib",
"rustpython-vm",
+1
View File
@@ -12,6 +12,7 @@ license.workspace = true
crate-type = ["cdylib", "rlib"]
[dependencies]
num-complex = { workspace = true }
rustpython-vm = { workspace = true, features = ["threading", "compiler"] }
rustpython-stdlib = {workspace = true, features = ["threading"] }
+52
View File
@@ -0,0 +1,52 @@
use crate::object::define_py_check;
use crate::{PyObject, pystate::with_vm};
use core::ffi::c_double;
use num_complex::{Complex, Complex64};
use rustpython_vm::builtins::PyComplex;
use rustpython_vm::{PyResult, VirtualMachine};
define_py_check!(fn PyComplex_Check, types.complex_type);
define_py_check!(exact fn PyComplex_CheckExact, types.complex_type);
#[unsafe(no_mangle)]
pub extern "C" fn PyComplex_FromDoubles(real: c_double, imag: c_double) -> *mut PyObject {
with_vm(|vm| vm.ctx.new_complex(Complex::new(real, imag)))
}
fn try_to_complex(vm: &VirtualMachine, obj: &PyObject) -> PyResult<Complex64> {
obj.try_downcast_ref::<PyComplex>(vm).map_or_else(
|type_err| {
if let Some((complex, _)) = obj.to_owned().try_complex(vm)? {
Ok(complex)
} else {
Err(type_err)
}
},
|complex| Ok(complex.to_complex()),
)
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyComplex_RealAsDouble(obj: *mut PyObject) -> c_double {
with_vm(|vm| try_to_complex(vm, unsafe { &*obj }).map(|complex| complex.re))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyComplex_ImagAsDouble(obj: *mut PyObject) -> c_double {
with_vm(|vm| try_to_complex(vm, unsafe { &*obj }).map(|complex| complex.im))
}
#[cfg(false)]
mod tests {
use pyo3::prelude::*;
use pyo3::types::PyComplex;
#[test]
fn test_py_int() {
Python::attach(|py| {
let number = PyComplex::from_doubles(py, 1.0, 2.0);
assert_eq!(number.real(), 1.0);
assert_eq!(number.imag(), 2.0);
})
}
}
+1
View File
@@ -12,6 +12,7 @@ pub mod abstract_;
pub mod boolobject;
pub mod bytesobject;
pub mod ceval;
pub mod complexobject;
pub mod dictobject;
pub mod floatobject;
pub mod import;