Merge pull request #434 from ijl/pyfloat-macro

PyFloat_AS_DOUBLE()
This commit is contained in:
Yuji Kanagawa 2019-04-17 11:21:12 +09:00 committed by GitHub
commit f5c7b92c2d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 2 deletions

View file

@ -1,6 +1,13 @@
use crate::ffi3::object::*;
use std::os::raw::{c_double, c_int};
#[cfg(not(Py_LIMITED_API))]
#[repr(C)]
pub struct PyFloatObject {
pub ob_base: PyObject,
pub ob_fval: c_double,
}
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub static mut PyFloat_Type: PyTypeObject;
@ -16,6 +23,12 @@ pub unsafe fn PyFloat_CheckExact(op: *mut PyObject) -> c_int {
(Py_TYPE(op) == &mut PyFloat_Type) as c_int
}
#[cfg(not(Py_LIMITED_API))]
#[inline]
pub unsafe fn PyFloat_AS_DOUBLE(op: *mut PyObject) -> c_double {
(*(op as *mut PyFloatObject)).ob_fval
}
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub fn PyFloat_GetMax() -> c_double;

View file

@ -84,8 +84,8 @@ impl<'source> FromPyObject<'source> for f32 {
#[cfg(test)]
mod test {
use crate::Python;
use crate::ToPyObject;
use crate::ffi::PyFloat_AS_DOUBLE;
use crate::{AsPyPointer, Python, ToPyObject};
macro_rules! num_to_py_object_and_back (
($func_name:ident, $t1:ty, $t2:ty) => (
@ -103,4 +103,13 @@ mod test {
num_to_py_object_and_back!(to_from_f64, f64, f64);
num_to_py_object_and_back!(to_from_f32, f32, f32);
num_to_py_object_and_back!(int_to_float, i32, f64);
#[test]
fn test_as_double_macro() {
let gil = Python::acquire_gil();
let py = gil.python();
let v = 1.23f64;
let obj = v.to_object(py);
assert_eq!(v, unsafe { PyFloat_AS_DOUBLE(obj.as_ptr()) });
}
}