3

I'm calling Python from C++, and trying to perform some data conversions.

For example, if I call the following Python function

def getAMap():
   data = {}
   data["AnItem 1"] = "Item value 1"
   data["AnItem 2"] = "Item value 2"
   return data

from C++ as:

PyObject *pValue= PyObject_CallObject(pFunc, NULL);

where pFunc is a PyObject* that points to the getAMap python function. Code for setting up pFunc omitted for clarity.

The returned pointer, pValue is a pointer to a (among other things) Python dictionary. Question is, how to get thh dictionary into a std::map on the C++ side as smoothly as possible?

I'm using C++ Builder bcc32 compiler that can't handle any fancy template code, like boost python, or C++11 syntax.

(Changed question as the python object is a dictionary, not a tuple)

9
  • Just found a library that makes it easy to convert Python objects (Python C API) to standard C++ datatypes as it says here. Looks like it might help you due to it also supports std::map. Commented Apr 23, 2018 at 20:09
  • Also, consider swig. Commented Apr 23, 2018 at 20:09
  • Rob, I'm using swig in fact. Commented Apr 23, 2018 at 20:12
  • David; that library looks great, but I can't use it with this compiler unfortunately. Commented Apr 23, 2018 at 20:44
  • i would use PyTuple_GetItem and copy the values into a map. Or write a swig typemap that does it for you. Commented Apr 23, 2018 at 20:49

1 Answer 1

1

It's pretty ugly, but I came up with this:

std::map<std::string, std::string> my_map;

// Python Dictionary object
PyObject *pDict = PyObject_CallObject(pFunc, NULL);

// Both are Python List objects
PyObject *pKeys = PyDict_Keys(pDict);
PyObject *pValues = PyDict_Values(pDict);

for (Py_ssize_t i = 0; i < PyDict_Size(pDict); ++i) {
    // PyString_AsString returns a char*
    my_map.insert( std::pair<std::string, std::string>(
            *PyString_AsString( PyList_GetItem(pKeys,   i) ),
            *PyString_AsString( PyList_GetItem(pValues, i) ) );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.