1
1
#pragma once
2
+ #include " ./../pyref.hpp"
2
3
#include " ./complex.hpp"
3
4
5
+ #include < numpy/arrayobject.h>
6
+
4
7
namespace cpp2py {
5
8
6
9
// PyObject *
@@ -28,17 +31,26 @@ namespace cpp2py {
28
31
29
32
// --- long
30
33
31
- namespace details {
34
+ namespace details {
32
35
template <typename I> struct py_converter_impl {
33
36
static PyObject *c2py (I i) { return PyLong_FromLong (long (i)); }
34
- static I py2c (PyObject *ob) { return I (PyLong_AsLong (ob)); }
37
+ static I py2c (PyObject *ob) {
38
+ if (PyLong_Check (ob)) { return I (PyLong_AsLong (ob)); }
39
+ // Convert NPY Scalar Type to Builtin Type
40
+ pyref py_builtin = PyObject_CallMethod (ob, " item" , NULL );
41
+ return I (PyLong_AsLong (py_builtin));
42
+ }
35
43
static bool is_convertible (PyObject *ob, bool raise_exception) {
36
44
if (PyLong_Check (ob)) return true ;
45
+ if (PyArray_CheckScalar (ob)) {
46
+ pyref py_arr = PyArray_FromScalar (ob, NULL );
47
+ if (PyArray_ISINTEGER ((PyObject *)py_arr)) return true ;
48
+ }
37
49
if (raise_exception) { PyErr_SetString (PyExc_TypeError, " Cannot convert to integer type" ); }
38
50
return false ;
39
51
}
40
52
};
41
- }
53
+ } // namespace details
42
54
43
55
template <> struct py_converter <long > : details::py_converter_impl<long > {};
44
56
template <> struct py_converter <int > : details::py_converter_impl<int > {};
@@ -50,9 +62,18 @@ namespace cpp2py {
50
62
51
63
template <> struct py_converter <double > {
52
64
static PyObject *c2py (double x) { return PyFloat_FromDouble (x); }
53
- static double py2c (PyObject *ob) { return PyFloat_AsDouble (ob); }
65
+ static double py2c (PyObject *ob) {
66
+ if (PyFloat_Check (ob) || PyLong_Check (ob)) { return PyFloat_AsDouble (ob); }
67
+ // Convert NPY Scalar Type to Builtin Type
68
+ pyref py_builtin = PyObject_CallMethod (ob, " item" , NULL );
69
+ return PyFloat_AsDouble (py_builtin);
70
+ }
54
71
static bool is_convertible (PyObject *ob, bool raise_exception) {
55
72
if (PyFloat_Check (ob) || PyLong_Check (ob)) return true ;
73
+ if (PyArray_CheckScalar (ob)) {
74
+ pyref py_arr = PyArray_FromScalar (ob, NULL );
75
+ if (PyArray_ISINTEGER ((PyObject*)py_arr) or PyArray_ISFLOAT ((PyObject*)py_arr)) return true ;
76
+ }
56
77
if (raise_exception) { PyErr_SetString (PyExc_TypeError, " Cannot convert to double" ); }
57
78
return false ;
58
79
}
0 commit comments