python-list to c++-vector

Mmmm ... if you really want to only have list, you may use
boost::python::list as argument : simpler, clearer and boost.python does
the verification job for you !


But if you want to be able to extract every sequence, I would suggest
the use of python iterator as it's more general. For that, you should
use the PyObject_GetIter function (or there is a boost object ???) and
then use the "next" attribute like this :

void set( boost::python::object o ) 
{
  try
    {
      object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ) );
      while( 1 )
	{
	  object obj = extract( iter_obj.attr( "next" )() ); // Should always work
	  int val = extract( obj ); // Should launch an exception if you wannot extract an int ...
	  _ints.push_back(val);
	}
    }
  catch( error_already_set )
    {
      PyErr_Clear(); // If there is an exception (no iterator, extract failed or end of the list reached), clear it and exit the function
      return;
    }
} 
  




The only pb I have with my function is you cannot make the difference
between the various exceptions.


Le lun 29/09/2003 à 18:04, Lars Kunert a écrit :
> Hi!

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




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

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

> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig
-- 
Pierre Barbier de Reuille


INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France


tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68 

你可能感兴趣的:(Python)