changeset 344:9d95f087e5aa

Add a function to extract a scalar map value from a Python dict * oct-py-types.cc, oct-py-types.h (pytave::extract_py_scalar_map): New function.
author Mike Miller <mtmiller@octave.org>
date Tue, 16 Aug 2016 15:29:01 -0700
parents fe6b9e618c98
children baff3b90dcb1
files oct-py-types.cc oct-py-types.h
diffstat 2 files changed, 45 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/oct-py-types.cc	Tue Aug 16 13:54:25 2016 -0700
+++ b/oct-py-types.cc	Tue Aug 16 15:29:01 2016 -0700
@@ -33,6 +33,7 @@
 
 // FIXME: only here to bootstrap nested conversions needed in this file
 #include "octave_to_python.h"
+#include "python_to_octave.h"
 
 namespace pytave
 {
@@ -178,6 +179,43 @@
   return ptr;
 }
 
+inline octave_value
+wrap_pyobj_to_octvalue (PyObject *obj)
+{
+  boost::python::object objref { boost::python::handle<> (boost::python::borrowed (obj)) };
+  octave_value value;
+  pyobj_to_octvalue (value, objref);
+  return value;
+}
+
+octave_scalar_map
+extract_py_scalar_map (PyObject *obj)
+{
+  if (! obj)
+    throw object_convert_exception ("failed to extract map: null object");
+
+  if (! PyDict_Check (obj))
+    throw object_convert_exception ("failed to extract map: wrong type");
+
+  octave_scalar_map map;
+
+  Py_ssize_t pos = 0;
+  PyObject *py_key = 0;
+  PyObject *py_value = 0;
+
+  while (PyDict_Next (obj, &pos, &py_key, &py_value))
+    {
+      if (! PyBytes_Check (py_key) && ! PyUnicode_Check (py_key))
+        throw object_convert_exception ("failed to extract map: bad key type");
+
+      std::string key = extract_py_str (py_key);
+      octave_value value = wrap_pyobj_to_octvalue (py_value);
+      map.setfield (key, value);
+    }
+
+  return map;
+}
+
 PyObject *
 make_py_dict (const octave_scalar_map& map)
 {
--- a/oct-py-types.h	Tue Aug 16 13:54:25 2016 -0700
+++ b/oct-py-types.h	Tue Aug 16 15:29:01 2016 -0700
@@ -76,6 +76,13 @@
 PyObject *
 make_py_float (double value);
 
+//! Extract an Octave scalar map from the given Python dict object.
+//!
+//! @param obj Python dict object
+//! @return Octave scalar map containing the items of @a obj
+octave_scalar_map
+extract_py_scalar_map (PyObject *obj);
+
 //! Create a Python dict object from the given Octave scalar map value.
 //!
 //! The values contained in the map are recursively converted to appropriate