changeset 95:0701aee1b0cd

JS-wrapped python functions can now return normal strings (not just unicode).
author Atul Varma <varmaa@toolness.com>
date Sat, 15 Aug 2009 00:50:55 -0700
parents c66d7da09c95
children 3570ab12747b
files test_pymonkey.py utils.c
diffstat 2 files changed, 21 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/test_pymonkey.py	Sat Aug 15 00:25:48 2009 -0700
+++ b/test_pymonkey.py	Sat Aug 15 00:50:55 2009 -0700
@@ -245,11 +245,17 @@
                                                    'hai2u("blah\x00 ")'),
                          u"blah\x00 o hai")
 
+    def testJsWrappedPythonFunctionReturnsString(self):
+        def hai2u(cx, this, args):
+            return "o hai"
+        self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),
+                         "o hai")
+
     def testJsWrappedPythonFunctionReturnsUnicode(self):
         def hai2u(cx, this, args):
-            return u"o hai"
+            return u"o hai\u2026"
         self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),
-                         u"o hai")
+                         u"o hai\u2026")
 
     def testJsWrappedPythonFunctionThrowsJsException(self):
         def hai2u(cx, this, args):
--- a/utils.c	Sat Aug 15 00:25:48 2009 -0700
+++ b/utils.c	Sat Aug 15 00:50:55 2009 -0700
@@ -59,8 +59,19 @@
                     PyObject *object,
                     jsval *rval)
 {
-  if (PyUnicode_Check(object)) {
-    PyObject *string = PyUnicode_AsUTF16String(object);
+  if (PyString_Check(object) || PyUnicode_Check(object)) {
+    PyObject *unicode;
+    if (PyString_Check(object)) {
+      unicode = PyUnicode_FromObject(object);
+      if (unicode == NULL)
+        return -1;
+    } else {
+      unicode = object;
+      Py_INCREF(unicode);
+    }
+
+    PyObject *string = PyUnicode_AsUTF16String(unicode);
+    Py_DECREF(unicode);
     if (string == NULL)
       return -1;