[C++-sig] Re: to_python_converter
Raoul Gough
RaoulGough at yahoo.co.uk
Wed Jan 21 03:33:27 CET 2004
"aashish" <aashish at vrac.iastate.edu> writes:
> Hi,
>
> I am sorry about asking so many question but I have to as I am new to the
> world of C++/Python and couldn't find my answers on Google.
>
>
> I need to do something like this so that on the python side I will get the
> object of type std::vector (I now that I might need to use
> to_python_converter but I couldn't understand the documentation)
>
Usually, you don't have to mess around with to_python_converter. What
you should do is "expose" the C++ class to Python via an instance of
the boost::python::class_ template. Probably the tutorial is the right
place to start for this kind of stuff.
>
> std::vector <int> make_vector(bp::list vlist)
> {
> std::vector<int> vector_list;
>
> int list_length = extract<int>(vlist.attr("__len__")());
>
> for ( int i = 0; i < list_length; i++ )
> {
>
>
> vector_list.push_back(extract<int>(vlist.attr("__getitem__")(list_length)));
> }
>
>
> return vector_list;
>
>
> }
>
> And it compiled fine but whenI did something like this on python side I got
> the error
>
> L = [1,2,3]
> a = make_vector(L)
> print a
>
> saying that "No to_python (by value) converter found for C++ class
> std""vector<int, class std::allocator<int> >
>
> Can someone tell how to solve this problem...I know what the problem might
> be but I don't know the solution.
In this case, you want to expose the vector instance via something like this:
// in your BOOST_PYTHON_MODULE function
boost::python::class_<std::vector<int> > ("int_vector")
.def (/* ... */)
// ...
.def (/* ... */);
AFAIK, the super-duper container support stuff is currently only in
the CVS (i.e. wasn't in the 1.30.x releases). If you can upgrade to
the CVS code (see downloading info from the boost home page) then you
would be able to use the "indexing suite" to do something like
boost::python::class_<std::vector<int> > ("int_vector")
.def (boost::python::indexing<std::vector<int> >());
or something along those lines, to get all the useful Python support
functions for your vector (like __getitem__ and so on). See link to
the indexing suite documentation right at the bottom of the Boost
Python reference page (once you've got the files from CVS, of course).
--
Raoul Gough.
export LESS='-X'
More information about the Cplusplus-sig
mailing list