1

I have the following C++ code:

const std::string Get(const std::map<std::string, std::string> map) {
    PyObject* module = PyImport_ImportModule("dummy");

    boost::python::dict dict;
    for (auto const& pair : map) {
        dict[pair.first] = pair.second;
    }

    // This is the line
    PyObject* args = PyTuple_Pack(1, &dict);
    /// ^^^^^^^^^^^ 

    PyObject* function = PyObject_GetAttrString(module,"get_something");
    PyObject* pyResult = PyObject_CallObject(function, args);
    std::string result = PyUnicode_AsUTF8(pyResult);

    return result;
}

Calling this python script:

def get_something(map):
   return map['a']

I can pass std::string to python by calling PyUnicode_FromString. The problem is I was not able to find a similar function that takes std::map and returns PyObject*.

  • I tried passing a ref to boost::python::dict but this segfaults on runtime.
  • I tried passing the map itself directly. Segfault again.
  • I know I can encode the map as JSON, pass a string and unpack in python but that's a terrible kludge.
  • I might be able to wrap the map in a class and pass that. I was able to do that elsewhere.

But I really want this code to be as simple as possible. Surely this is possible.

4
  • 1
    Python wants a PyObject*, so use dict.ptr(). Commented Oct 23, 2024 at 18:37
  • Seriously?! I can't believe that worked. Feel free to provide an answer and I'll accept it. Commented Oct 23, 2024 at 18:45
  • I .. just read the documentation and noted that dict inherited from object... Commented Oct 23, 2024 at 18:56
  • Also note that boost::python has nice helpers for calling Python functions, which do the .ptr() conversion for you. Commented Oct 23, 2024 at 19:06

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.