[C++-sig] python-list to c++-vector

Lars Kunert lkunert at mpi-sb.mpg.de
Mon Sep 29 18:04:48 CEST 2003


Hi!

Is this here really the easiest and the fastest way to transfer a small 
(<10000) python-list of integers into a std::vector?! 


#include <boost/python.hpp>
#include <vector>
#include <iostream>

class Ints 
{
  private:
    std::vector<int> _ints;

  public:
    void set( boost::python::object o ) 
    {
        boost::python::list list = 
boost::python::extract<boost::python::list>(o);
        try {
            _ints.clear();

            bool is_ok = true;
            while( is_ok ) {
                boost::python::extract<int> x( list.pop( 0 ));

                if( x.check()) {
                    _ints.push_back( x());
                } else {
                    is_ok = false;
                };
            };
        } catch ( ... ) {
            std::cerr << "exception thrown";
        };
    };
};


// Using 
=======================================================================
using namespace boost::python;

// Module 
======================================================================
BOOST_PYTHON_MODULE(Iterator_module)
{
    class_< Ints >("Ints", init<>())
        .def("set", &Ints::set )
        ;
};




More information about the Cplusplus-sig mailing list