Mercurial > pymonkey
changeset 32:abf14cba9ef5
JS wrapped Python functions can now return floats.
author | Atul Varma <varmaa@toolness.com> |
---|---|
date | Tue, 30 Jun 2009 22:37:00 -0700 |
parents | d0a3f358072a |
children | 3f8a2db496f5 |
files | test_pymonkey.py utils.c |
diffstat | 2 files changed, 27 insertions(+), 10 deletions(-) [+] |
line wrap: on
line diff
--- a/test_pymonkey.py Tue Jun 30 22:28:04 2009 -0700 +++ b/test_pymonkey.py Tue Jun 30 22:37:00 2009 -0700 @@ -28,6 +28,12 @@ self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'), 5) + def testJsWrappedPythonFunctionReturnsFloat(self): + def hai2u(): + return 5.1 + self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'), + 5.1) + def testJsWrappedPythonFunctionReturnsNegativeInt(self): def hai2u(): return -5
--- a/utils.c Tue Jun 30 22:28:04 2009 -0700 +++ b/utils.c Tue Jun 30 22:37:00 2009 -0700 @@ -4,6 +4,20 @@ PyObject *PYM_error; +static PyObject * +PYM_doubleToJsval(JSContext *cx, + double number, + jsval *rval) +{ + jsdouble *numberAsJsdouble = JS_NewDouble(cx, number); + if (numberAsJsdouble == NULL) { + PyErr_SetString(PYM_error, "JS_NewDouble() failed"); + return NULL; + } + *rval = DOUBLE_TO_JSVAL(numberAsJsdouble); + Py_RETURN_NONE; +} + PyObject * PYM_pyObjectToJsval(JSContext *cx, PyObject *object, @@ -26,19 +40,16 @@ if (PyInt_Check(object)) { long number = PyInt_AS_LONG(object); - if (INT_FITS_IN_JSVAL(number)) + if (INT_FITS_IN_JSVAL(number)) { *rval = INT_TO_JSVAL(number); - else { - jsdouble *numberAsJsdouble = JS_NewDouble(cx, number); - if (numberAsJsdouble == NULL) { - PyErr_SetString(PYM_error, "JS_NewDouble() failed"); - return NULL; - } - *rval = DOUBLE_TO_JSVAL(numberAsJsdouble); - } - Py_RETURN_NONE; + Py_RETURN_NONE; + } else + return PYM_doubleToJsval(cx, number, rval); } + if (PyFloat_Check(object)) + return PYM_doubleToJsval(cx, PyFloat_AS_DOUBLE(object), rval); + // TODO: Support more types. PyErr_SetString(PyExc_NotImplementedError, "Data type conversion not implemented.");