Skip to content

Fix build of Pyo3 branch #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jul 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ license-file = "LICENSE"

[dependencies]
libc = "0.2"
cpython = "0.1"
python3-sys = "0.1"
num-complex = "0.1"
ndarray = "0.10"

[dependencies.pyo3]
git = "https://github.com/PyO3/pyo3"
rev = "4169b0317826dc62eafcdd0faab7d009f6808c06"
5 changes: 4 additions & 1 deletion example/extensions/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,8 @@ crate-type = ["cdylib"]

[dependencies]
numpy = { path = "../.." }
cpython = "0.1"
ndarray = "0.10"

[dependencies.pyo3]
version = "*"
features = ["extension-module"]
77 changes: 35 additions & 42 deletions example/extensions/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,48 +1,41 @@
#![feature(proc_macro, proc_macro_path_invoc, specialization)]

#[macro_use]
extern crate cpython;
extern crate numpy;
extern crate ndarray;
extern crate numpy;
extern crate pyo3;

use numpy::*;
use ndarray::*;
use cpython::{PyResult, Python, PyObject};

/* Pure rust-ndarray functions */

// immutable example
fn axpy(a: f64, x: ArrayViewD<f64>, y: ArrayViewD<f64>) -> ArrayD<f64> {
a * &x + &y
}

// mutable example (no return)
fn mult(a: f64, mut x: ArrayViewMutD<f64>) {
x *= a;
}

/* rust-cpython wrappers (to be exposed) */

// wrapper of `axpy`
fn axpy_py(py: Python, a: f64, x: PyArray, y: PyArray) -> PyResult<PyArray> {
let np = PyArrayModule::import(py)?;
let x = x.as_array().into_pyresult(py, "x must be f64 array")?;
let y = y.as_array().into_pyresult(py, "y must be f64 array")?;
Ok(axpy(a, x, y).into_pyarray(py, &np))
}

// wrapper of `mult`
fn mult_py(py: Python, a: f64, x: PyArray) -> PyResult<PyObject> {
let x = x.as_array_mut().into_pyresult(py, "x must be f64 array")?;
mult(a, x);
Ok(py.None()) // Python function must returns
}
use numpy::*;
use pyo3::{py, PyModule, PyObject, PyResult, Python};

#[py::modinit(rust_ext)]
fn init_module(py: Python, m: &PyModule) -> PyResult<()> {
// immutable example
fn axpy(a: f64, x: ArrayViewD<f64>, y: ArrayViewD<f64>) -> ArrayD<f64> {
a * &x + &y
}

// mutable example (no return)
fn mult(a: f64, mut x: ArrayViewMutD<f64>) {
x *= a;
}

// wrapper of `axpy`
#[pyfn(m, "axpy")]
fn axpy_py(py: Python, a: f64, x: PyArray, y: PyArray) -> PyResult<PyArray> {
let np = PyArrayModule::import(py)?;
let x = x.as_array().into_pyresult(py, "x must be f64 array")?;
let y = y.as_array().into_pyresult(py, "y must be f64 array")?;
Ok(axpy(a, x, y).into_pyarray(py, &np))
}

// wrapper of `mult`
#[pyfn(m, "mult")]
fn mult_py(py: Python, a: f64, x: PyArray) -> PyResult<PyObject> {
let x = x.as_array_mut().into_pyresult(py, "x must be f64 array")?;
mult(a, x);
Ok(py.None()) // Python function must returns
}

/* Define module "_rust_ext" */
py_module_initializer!(_rust_ext, init_rust_ext, PyInit__rust_ext, |py, m| {
m.add(py, "__doc__", "Rust extension for NumPy")?;
m.add(py,
"axpy",
py_fn!(py, axpy_py(a: f64, x: PyArray, y: PyArray)))?;
m.add(py, "mult", py_fn!(py, mult_py(a: f64, x: PyArray)))?;
Ok(())
});
}
100 changes: 12 additions & 88 deletions src/array.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
//! Untyped safe interface for NumPy ndarray

use cpython::*;
use ndarray::*;
use npyffi;
use pyffi;
use pyo3::*;

use std::os::raw::c_void;
use std::ptr::null_mut;
Expand All @@ -13,22 +12,19 @@ use super::*;

/// Untyped safe interface for NumPy ndarray.
pub struct PyArray(PyObject);
pyobject_native_type!(PyArray, *npyffi::PyArray_Type_Ptr, npyffi::PyArray_Check);

impl PyArray {
pub fn as_ptr(&self) -> *mut npyffi::PyArrayObject {
self.0.as_ptr() as *mut npyffi::PyArrayObject
pub fn as_array_ptr(&self) -> *mut npyffi::PyArrayObject {
self.as_ptr() as _
}

pub fn steal_ptr(self) -> *mut npyffi::PyArrayObject {
self.0.steal_ptr() as *mut npyffi::PyArrayObject
}

pub unsafe fn from_owned_ptr(py: Python, ptr: *mut pyffi::PyObject) -> Self {
pub unsafe fn from_owned_ptr(py: Python, ptr: *mut pyo3::ffi::PyObject) -> Self {
let obj = PyObject::from_owned_ptr(py, ptr);
PyArray(obj)
}

pub unsafe fn from_borrowed_ptr(py: Python, ptr: *mut pyffi::PyObject) -> Self {
pub unsafe fn from_borrowed_ptr(py: Python, ptr: *mut pyo3::ffi::PyObject) -> Self {
let obj = PyObject::from_borrowed_ptr(py, ptr);
PyArray(obj)
}
Expand All @@ -37,7 +33,7 @@ impl PyArray {
///
/// https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_NDIM
pub fn ndim(&self) -> usize {
let ptr = self.as_ptr();
let ptr = self.as_array_ptr();
unsafe { (*ptr).nd as usize }
}

Expand All @@ -46,7 +42,7 @@ impl PyArray {
/// https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_DIMS
pub fn dims(&self) -> Vec<usize> {
let n = self.ndim();
let ptr = self.as_ptr();
let ptr = self.as_array_ptr();
let dims = unsafe {
let p = (*ptr).dimensions;
::std::slice::from_raw_parts(p, n)
Expand All @@ -69,7 +65,7 @@ impl PyArray {
/// - https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html#numpy.ndarray.strides
pub fn strides(&self) -> Vec<isize> {
let n = self.ndim();
let ptr = self.as_ptr();
let ptr = self.as_array_ptr();
let dims = unsafe {
let p = (*ptr).strides;
::std::slice::from_raw_parts(p, n)
Expand All @@ -78,7 +74,7 @@ impl PyArray {
}

unsafe fn data<T>(&self) -> *mut T {
let ptr = self.as_ptr();
let ptr = self.as_array_ptr();
(*ptr).data as *mut T
}

Expand All @@ -94,7 +90,7 @@ impl PyArray {

pub fn typenum(&self) -> i32 {
unsafe {
let descr = (*self.as_ptr()).descr;
let descr = (*self.as_array_ptr()).descr;
(*descr).type_num
}
}
Expand Down Expand Up @@ -143,7 +139,7 @@ impl PyArray {
unsafe { Ok(::std::slice::from_raw_parts_mut(self.data(), self.len())) }
}

pub unsafe fn new_<T: TypeNum>(
pub unsafe fn new_<T: types::TypeNum>(
py: Python,
np: &PyArrayModule,
dims: &[usize],
Expand Down Expand Up @@ -204,75 +200,3 @@ impl PyArray {
}
}
}

impl<'source> FromPyObject<'source> for PyArray {
fn extract(py: Python, obj: &'source PyObject) -> PyResult<Self> {
Ok(obj.clone_ref(py).cast_into::<PyArray>(py)?)
}
}

impl<'source> FromPyObject<'source> for &'source PyArray {
fn extract(py: Python, obj: &'source PyObject) -> PyResult<Self> {
Ok(obj.cast_as::<PyArray>(py)?)
}
}

impl ToPyObject for PyArray {
type ObjectType = Self;

fn to_py_object(&self, py: Python) -> Self {
PyClone::clone_ref(self, py)
}
}

impl PythonObject for PyArray {
#[inline]
fn as_object(&self) -> &PyObject {
&self.0
}

#[inline]
fn into_object(self) -> PyObject {
self.0
}

#[inline]
unsafe fn unchecked_downcast_from(obj: PyObject) -> Self {
PyArray(obj)
}

#[inline]
unsafe fn unchecked_downcast_borrow_from<'a>(obj: &'a PyObject) -> &'a Self {
::std::mem::transmute(obj)
}
}

impl PythonObjectWithCheckedDowncast for PyArray {
fn downcast_from<'p>(
py: Python<'p>,
obj: PyObject,
) -> Result<PyArray, PythonObjectDowncastError<'p>> {
let np = PyArrayModule::import(py).unwrap();
unsafe {
if npyffi::PyArray_Check(&np, obj.as_ptr()) != 0 {
Ok(PyArray(obj))
} else {
Err(PythonObjectDowncastError(py))
}
}
}

fn downcast_borrow_from<'a, 'p>(
py: Python<'p>,
obj: &'a PyObject,
) -> Result<&'a PyArray, PythonObjectDowncastError<'p>> {
let np = PyArrayModule::import(py).unwrap();
unsafe {
if npyffi::PyArray_Check(&np, obj.as_ptr()) != 0 {
Ok(::std::mem::transmute(obj))
} else {
Err(PythonObjectDowncastError(py))
}
}
}
}
2 changes: 1 addition & 1 deletion src/convert.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use cpython::Python;
use ndarray::*;
use pyo3::Python;

use std::iter::Iterator;
use std::mem::size_of;
Expand Down
14 changes: 7 additions & 7 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
//! Define Errors

use cpython::*;
use pyo3::*;
use std::error;
use std::fmt;

pub trait IntoPyErr {
fn into_pyerr(self, py: Python, msg: &str) -> PyErr;
fn into_pyerr(self, msg: &str) -> PyErr;
}

pub trait IntoPyResult {
type ValueType;
fn into_pyresult(self, py: Python, message: &str) -> PyResult<Self::ValueType>;
fn into_pyresult(self, msg: &str) -> PyResult<Self::ValueType>;
}

impl<T, E: IntoPyErr> IntoPyResult for Result<T, E> {
type ValueType = T;
fn into_pyresult(self, py: Python, msg: &str) -> PyResult<T> {
self.map_err(|e| e.into_pyerr(py, msg))
fn into_pyresult(self, msg: &str) -> PyResult<T> {
self.map_err(|e| e.into_pyerr(msg))
}
}

Expand Down Expand Up @@ -49,8 +49,8 @@ impl error::Error for ArrayCastError {
}

impl IntoPyErr for ArrayCastError {
fn into_pyerr(self, py: Python, msg: &str) -> PyErr {
fn into_pyerr(self, msg: &str) -> PyErr {
let msg = format!("rust_numpy::ArrayCastError: {}", msg);
PyErr::new::<exc::TypeError, _>(py, msg)
PyErr::new::<exc::TypeError, _>(msg)
}
}
6 changes: 4 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
extern crate cpython;
#![feature(specialization)]

extern crate libc;
extern crate ndarray;
extern crate num_complex;
extern crate python3_sys as pyffi;
#[macro_use]
extern crate pyo3;

pub mod array;
pub mod convert;
Expand Down
Loading