Search code examples
c++boosttuplesboost-python

How to access elements of boost::python::tuple in C++?


I have a C++ code called from Python. I have list of tuples passed from python:

boost::python::list<boost::python::tuple>

How do I access the elements of boost::python::tuple?

Any example would be handy. From the documentation, I can't find the accessor methods.


Solution

  • I was able to use the boost::python::extract<int>( ) method.

    For example for a python tuple containing an integer and a string:

    Python side:

    t = (123, 'some string')
    

    C++ side:

    void work_with_tuple(boost::python::tuple t)
    {
       if (boost::python::len(t) != 2) throw std::invalid_argument("bad");
    
       int extracted_int = boost::python::extract<int>(t[0]);
       std::string extracted_string = boost::python::extract<std::string>(t[1]);
    }