Search code examples
c++pythonboostboost-python

Boost Python binding Vector of a Class


I am trying to create a python binding for a C++ class using Boost Python

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <vector>

using namespace boost::python;

struct World
{
    void set(std::string msg) { this->msg = msg; }

    std::string greet() { return msg; }

    MyList2 getList() {
        MyList v1(5, 1), v2(10, 2);
        MyList2 v;
        v.push_back(v1);
        v.push_back(v2);
        std::cout<<"In C++: "<<v.size()<<std::endl;
        return v;
    }

    std::string msg;
};


BOOST_PYTHON_MODULE(test_ext)
{
    class_< std::vector<World> >("MyList")
        .def(vector_indexing_suite< std::vector<World> >() );

    class_<World>("World")
        .def("greet", &World::greet)
        .def("set", &World::set)
        .def("list", &World::getList)
    ;
}

But i am getting compilation error with vector indexing suite when trying to bind vector of a class.

no match for ‘operator==’ in ‘__first.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = World*, _Container = std::vector<World>, __gnu_cxx::__normal_iterator<_Iterator, _Container>::reference = World&]() == __val’

Solution

  • For why we need to define the operators, I think following can be checked out:

    why do I need comparison operators in boost python vector indexing suite?