您的位置:首页 > 编程语言 > C语言/C++

python-list to c++-vector

2011-09-24 19:09 1256 查看
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<object>( iter_obj.attr( "next" )() ); // Should always work
int val = extract<int>( 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: