Skip to content

Commit

Permalink
added support for complex numbers [thanks to diego]
Browse files Browse the repository at this point in the history
  • Loading branch information
iraikov committed Mar 20, 2021
1 parent 6ca45ca commit 1cc8230
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
28 changes: 16 additions & 12 deletions pyffi.scm
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
(define (py-object-to value)
(cond
((exact-integer? value) (translate-to-foreign value py-int))
((cplxnum? value) (translate-to-foreign value py-complex))
((real? value) (translate-to-foreign value py-float))
((alist? value) (translate-to-foreign value py-dict))
((list? value) (if (eq? 'ascii (car value))
Expand Down Expand Up @@ -200,6 +201,10 @@ int PyDict_SetItem (PyObject *, pyobject, pyobject);
double PyFloat_AsDouble (PyObject *);
PyObject *PyFloat_FromDouble (double);

PyObject* PyComplex_FromDoubles(double real, double imag);
double PyComplex_RealAsDouble(PyObject *op);
double PyComplex_ImagAsDouble(PyObject *op);

pyobject PyImport_GetModuleDict (void);
PyObject *PyImport_Import (pyobject );

Expand Down Expand Up @@ -416,6 +421,16 @@ EOF

(define-pytype py-float PyFloat_FromDouble PyFloat_AsDouble)

(define-pytype py-complex
(lambda (value)
(let* ((r (real-part value))
(i (imag-part value)))
(PyComplex_FromDoubles r i)))
(lambda (value)
(let* ((r (PyComplex_RealAsDouble value))
(i (PyComplex_ImagAsDouble value)))
(make-rectangular r i))))

(define (utf8-string->py-unicode value)
;; Given a Scheme UTF8 string, converts it into Python Unicode string
(let ((res (pyffi_PyUnicode_fromCString value)))
Expand Down Expand Up @@ -488,25 +503,14 @@ EOF
("<class 'bool'>" . ,py-bool)
("<class 'int'>" . ,py-int)
("<class 'float'>" . ,py-float)
("<class 'complex'>" . ,py-complex)
("<class 'list'>" . ,py-list)
("<class 'str'>" . ,py-ascii)
("<class 'unicode'>" . ,py-unicode)
("<class 'dict'>" . ,py-dict)
("<class 'instance'>" . ,py-instance)
("<class 'tuple'>" . ,py-tuple)
("<class 'buffer'>" . ,py-buffer)

("<type 'bool'>" . ,py-bool)
("<type 'bool'>" . ,py-bool)
("<type 'int'>" . ,py-int)
("<type 'float'>" . ,py-float)
("<type 'list'>" . ,py-list)
("<type 'str'>" . ,py-ascii)
("<type 'unicode'>" . ,py-unicode)
("<type 'dict'>" . ,py-dict)
("<type 'instance'>" . ,py-instance)
("<type 'tuple'>" . ,py-tuple)
("<type 'buffer'>" . ,py-buffer)
)
)

Expand Down
1 change: 1 addition & 0 deletions tests/run.scm
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@
(print (py-eval "1"))
(print (py-eval "1.0"))
(print (py-eval "float('-inf')"))
(print (py-eval "complex(1.0, 2.0)"))

0 comments on commit 1cc8230

Please sign in to comment.