Skip to content

Commit d0c873e

Browse files
authored
Merge pull request #31 from kngwyu/pyo3-fix
Fix build of Pyo3 branch
2 parents 1f6b31a + 076e2d8 commit d0c873e

File tree

13 files changed

+124
-188
lines changed

13 files changed

+124
-188
lines changed

Cargo.toml

+4-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ license-file = "LICENSE"
1111

1212
[dependencies]
1313
libc = "0.2"
14-
cpython = "0.1"
15-
python3-sys = "0.1"
1614
num-complex = "0.1"
1715
ndarray = "0.10"
16+
17+
[dependencies.pyo3]
18+
git = "https://github.com/PyO3/pyo3"
19+
rev = "4169b0317826dc62eafcdd0faab7d009f6808c06"

example/extensions/Cargo.toml

+4-1
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,8 @@ crate-type = ["cdylib"]
99

1010
[dependencies]
1111
numpy = { path = "../.." }
12-
cpython = "0.1"
1312
ndarray = "0.10"
13+
14+
[dependencies.pyo3]
15+
version = "*"
16+
features = ["extension-module"]

example/extensions/src/lib.rs

+35-42
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,41 @@
1+
#![feature(proc_macro, proc_macro_path_invoc, specialization)]
12

2-
#[macro_use]
3-
extern crate cpython;
4-
extern crate numpy;
53
extern crate ndarray;
4+
extern crate numpy;
5+
extern crate pyo3;
66

7-
use numpy::*;
87
use ndarray::*;
9-
use cpython::{PyResult, Python, PyObject};
10-
11-
/* Pure rust-ndarray functions */
12-
13-
// immutable example
14-
fn axpy(a: f64, x: ArrayViewD<f64>, y: ArrayViewD<f64>) -> ArrayD<f64> {
15-
a * &x + &y
16-
}
17-
18-
// mutable example (no return)
19-
fn mult(a: f64, mut x: ArrayViewMutD<f64>) {
20-
x *= a;
21-
}
22-
23-
/* rust-cpython wrappers (to be exposed) */
24-
25-
// wrapper of `axpy`
26-
fn axpy_py(py: Python, a: f64, x: PyArray, y: PyArray) -> PyResult<PyArray> {
27-
let np = PyArrayModule::import(py)?;
28-
let x = x.as_array().into_pyresult(py, "x must be f64 array")?;
29-
let y = y.as_array().into_pyresult(py, "y must be f64 array")?;
30-
Ok(axpy(a, x, y).into_pyarray(py, &np))
31-
}
32-
33-
// wrapper of `mult`
34-
fn mult_py(py: Python, a: f64, x: PyArray) -> PyResult<PyObject> {
35-
let x = x.as_array_mut().into_pyresult(py, "x must be f64 array")?;
36-
mult(a, x);
37-
Ok(py.None()) // Python function must returns
38-
}
8+
use numpy::*;
9+
use pyo3::{py, PyModule, PyObject, PyResult, Python};
10+
11+
#[py::modinit(rust_ext)]
12+
fn init_module(py: Python, m: &PyModule) -> PyResult<()> {
13+
// immutable example
14+
fn axpy(a: f64, x: ArrayViewD<f64>, y: ArrayViewD<f64>) -> ArrayD<f64> {
15+
a * &x + &y
16+
}
17+
18+
// mutable example (no return)
19+
fn mult(a: f64, mut x: ArrayViewMutD<f64>) {
20+
x *= a;
21+
}
22+
23+
// wrapper of `axpy`
24+
#[pyfn(m, "axpy")]
25+
fn axpy_py(py: Python, a: f64, x: PyArray, y: PyArray) -> PyResult<PyArray> {
26+
let np = PyArrayModule::import(py)?;
27+
let x = x.as_array().into_pyresult(py, "x must be f64 array")?;
28+
let y = y.as_array().into_pyresult(py, "y must be f64 array")?;
29+
Ok(axpy(a, x, y).into_pyarray(py, &np))
30+
}
31+
32+
// wrapper of `mult`
33+
#[pyfn(m, "mult")]
34+
fn mult_py(py: Python, a: f64, x: PyArray) -> PyResult<PyObject> {
35+
let x = x.as_array_mut().into_pyresult(py, "x must be f64 array")?;
36+
mult(a, x);
37+
Ok(py.None()) // Python function must returns
38+
}
3939

40-
/* Define module "_rust_ext" */
41-
py_module_initializer!(_rust_ext, init_rust_ext, PyInit__rust_ext, |py, m| {
42-
m.add(py, "__doc__", "Rust extension for NumPy")?;
43-
m.add(py,
44-
"axpy",
45-
py_fn!(py, axpy_py(a: f64, x: PyArray, y: PyArray)))?;
46-
m.add(py, "mult", py_fn!(py, mult_py(a: f64, x: PyArray)))?;
4740
Ok(())
48-
});
41+
}

src/array.rs

+12-88
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
//! Untyped safe interface for NumPy ndarray
22
3-
use cpython::*;
43
use ndarray::*;
54
use npyffi;
6-
use pyffi;
5+
use pyo3::*;
76

87
use std::os::raw::c_void;
98
use std::ptr::null_mut;
@@ -13,22 +12,19 @@ use super::*;
1312

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

1717
impl PyArray {
18-
pub fn as_ptr(&self) -> *mut npyffi::PyArrayObject {
19-
self.0.as_ptr() as *mut npyffi::PyArrayObject
18+
pub fn as_array_ptr(&self) -> *mut npyffi::PyArrayObject {
19+
self.as_ptr() as _
2020
}
2121

22-
pub fn steal_ptr(self) -> *mut npyffi::PyArrayObject {
23-
self.0.steal_ptr() as *mut npyffi::PyArrayObject
24-
}
25-
26-
pub unsafe fn from_owned_ptr(py: Python, ptr: *mut pyffi::PyObject) -> Self {
22+
pub unsafe fn from_owned_ptr(py: Python, ptr: *mut pyo3::ffi::PyObject) -> Self {
2723
let obj = PyObject::from_owned_ptr(py, ptr);
2824
PyArray(obj)
2925
}
3026

31-
pub unsafe fn from_borrowed_ptr(py: Python, ptr: *mut pyffi::PyObject) -> Self {
27+
pub unsafe fn from_borrowed_ptr(py: Python, ptr: *mut pyo3::ffi::PyObject) -> Self {
3228
let obj = PyObject::from_borrowed_ptr(py, ptr);
3329
PyArray(obj)
3430
}
@@ -37,7 +33,7 @@ impl PyArray {
3733
///
3834
/// https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_NDIM
3935
pub fn ndim(&self) -> usize {
40-
let ptr = self.as_ptr();
36+
let ptr = self.as_array_ptr();
4137
unsafe { (*ptr).nd as usize }
4238
}
4339

@@ -46,7 +42,7 @@ impl PyArray {
4642
/// https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_DIMS
4743
pub fn dims(&self) -> Vec<usize> {
4844
let n = self.ndim();
49-
let ptr = self.as_ptr();
45+
let ptr = self.as_array_ptr();
5046
let dims = unsafe {
5147
let p = (*ptr).dimensions;
5248
::std::slice::from_raw_parts(p, n)
@@ -69,7 +65,7 @@ impl PyArray {
6965
/// - https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html#numpy.ndarray.strides
7066
pub fn strides(&self) -> Vec<isize> {
7167
let n = self.ndim();
72-
let ptr = self.as_ptr();
68+
let ptr = self.as_array_ptr();
7369
let dims = unsafe {
7470
let p = (*ptr).strides;
7571
::std::slice::from_raw_parts(p, n)
@@ -78,7 +74,7 @@ impl PyArray {
7874
}
7975

8076
unsafe fn data<T>(&self) -> *mut T {
81-
let ptr = self.as_ptr();
77+
let ptr = self.as_array_ptr();
8278
(*ptr).data as *mut T
8379
}
8480

@@ -94,7 +90,7 @@ impl PyArray {
9490

9591
pub fn typenum(&self) -> i32 {
9692
unsafe {
97-
let descr = (*self.as_ptr()).descr;
93+
let descr = (*self.as_array_ptr()).descr;
9894
(*descr).type_num
9995
}
10096
}
@@ -143,7 +139,7 @@ impl PyArray {
143139
unsafe { Ok(::std::slice::from_raw_parts_mut(self.data(), self.len())) }
144140
}
145141

146-
pub unsafe fn new_<T: TypeNum>(
142+
pub unsafe fn new_<T: types::TypeNum>(
147143
py: Python,
148144
np: &PyArrayModule,
149145
dims: &[usize],
@@ -204,75 +200,3 @@ impl PyArray {
204200
}
205201
}
206202
}
207-
208-
impl<'source> FromPyObject<'source> for PyArray {
209-
fn extract(py: Python, obj: &'source PyObject) -> PyResult<Self> {
210-
Ok(obj.clone_ref(py).cast_into::<PyArray>(py)?)
211-
}
212-
}
213-
214-
impl<'source> FromPyObject<'source> for &'source PyArray {
215-
fn extract(py: Python, obj: &'source PyObject) -> PyResult<Self> {
216-
Ok(obj.cast_as::<PyArray>(py)?)
217-
}
218-
}
219-
220-
impl ToPyObject for PyArray {
221-
type ObjectType = Self;
222-
223-
fn to_py_object(&self, py: Python) -> Self {
224-
PyClone::clone_ref(self, py)
225-
}
226-
}
227-
228-
impl PythonObject for PyArray {
229-
#[inline]
230-
fn as_object(&self) -> &PyObject {
231-
&self.0
232-
}
233-
234-
#[inline]
235-
fn into_object(self) -> PyObject {
236-
self.0
237-
}
238-
239-
#[inline]
240-
unsafe fn unchecked_downcast_from(obj: PyObject) -> Self {
241-
PyArray(obj)
242-
}
243-
244-
#[inline]
245-
unsafe fn unchecked_downcast_borrow_from<'a>(obj: &'a PyObject) -> &'a Self {
246-
::std::mem::transmute(obj)
247-
}
248-
}
249-
250-
impl PythonObjectWithCheckedDowncast for PyArray {
251-
fn downcast_from<'p>(
252-
py: Python<'p>,
253-
obj: PyObject,
254-
) -> Result<PyArray, PythonObjectDowncastError<'p>> {
255-
let np = PyArrayModule::import(py).unwrap();
256-
unsafe {
257-
if npyffi::PyArray_Check(&np, obj.as_ptr()) != 0 {
258-
Ok(PyArray(obj))
259-
} else {
260-
Err(PythonObjectDowncastError(py))
261-
}
262-
}
263-
}
264-
265-
fn downcast_borrow_from<'a, 'p>(
266-
py: Python<'p>,
267-
obj: &'a PyObject,
268-
) -> Result<&'a PyArray, PythonObjectDowncastError<'p>> {
269-
let np = PyArrayModule::import(py).unwrap();
270-
unsafe {
271-
if npyffi::PyArray_Check(&np, obj.as_ptr()) != 0 {
272-
Ok(::std::mem::transmute(obj))
273-
} else {
274-
Err(PythonObjectDowncastError(py))
275-
}
276-
}
277-
}
278-
}

src/convert.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
use cpython::Python;
21
use ndarray::*;
2+
use pyo3::Python;
33

44
use std::iter::Iterator;
55
use std::mem::size_of;

src/error.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
11
//! Define Errors
22
3-
use cpython::*;
3+
use pyo3::*;
44
use std::error;
55
use std::fmt;
66

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

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

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

@@ -49,8 +49,8 @@ impl error::Error for ArrayCastError {
4949
}
5050

5151
impl IntoPyErr for ArrayCastError {
52-
fn into_pyerr(self, py: Python, msg: &str) -> PyErr {
52+
fn into_pyerr(self, msg: &str) -> PyErr {
5353
let msg = format!("rust_numpy::ArrayCastError: {}", msg);
54-
PyErr::new::<exc::TypeError, _>(py, msg)
54+
PyErr::new::<exc::TypeError, _>(msg)
5555
}
5656
}

src/lib.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
extern crate cpython;
1+
#![feature(specialization)]
2+
23
extern crate libc;
34
extern crate ndarray;
45
extern crate num_complex;
5-
extern crate python3_sys as pyffi;
6+
#[macro_use]
7+
extern crate pyo3;
68

79
pub mod array;
810
pub mod convert;

0 commit comments

Comments
 (0)