# HG changeset patch # User Mike Miller # Date 1471386541 25200 # Node ID 9d95f087e5aaec860c25c65a6c70b3d704a456a3 # Parent fe6b9e618c98d165eeb31463c0e24df417d4cbaa 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. diff -r fe6b9e618c98 -r 9d95f087e5aa oct-py-types.cc --- 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) { diff -r fe6b9e618c98 -r 9d95f087e5aa oct-py-types.h --- 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