[C++-sig] Re: Accessing string vector in Python

Raoul Gough RaoulGough at yahoo.co.uk
Tue Mar 9 23:05:05 CET 2004

"Ron Clarke" <ron.clarke at hp.com> writes:

> I am trying to wrap a class method (using Boost.Python 1.31, MS VS.NET2003,
> Python 2.3) that returns a vector of std::string objects. Here is the C++
> definition:
> typedef std :: vector<std::string> StringVector;
> ...
> StringVector* myClass::getOwners()
> {...
> }

Returning the vector via a plain pointer? I guess you've omitted the
return policy that this would require.

> When wrapping this method for Python use, I thought I could use the
> vector_indexing_suite like so:
> {
> ...
> class_<StringVector>("StringVector")
>     .def(vector_indexing_suite<StringVector>() )
>     ;
>  ...
> }
> This builds OK, and the StringVector is accessible in Python. However,
> Python does not understand the individual elements within the vector. When I
> try to access StringVector elements, Python complains:
> sv = img.pubDict.getOwners()
> for i in range(len(sv)):
>     print sv[i]
> TypeError: No Python class registered for C++ class class
> std::basic_string<char,struct std::char_traits<char>,class
> std::allocator<char> >
> How do I get Python to understand/convert to string objects it can handle? I
> tried registering a converter, but that wasn't the answer
> (implicitly_convertible<std::string, boost::python::str>(); ).
> I cannot make the StringVector contents boost::python::str objects, since
> the code being wrapped must also be callable by C++ users. Any suggestions
> are greatly appreciated.
> Thanks in advance.

Sounds weird to me. Have you tried a very simple function that returns
a std::string? The vector indexing suite provides a __getitem__ method
that (in this case) will return a string, and that should all just
work automatically. Actually, maybe it returns a proxy object for the
string - can't exactly remember how the original indexing suite does

Does something like the following work?

std::string get_string () { return std::string ("hello world"); }

  boost::python::def ("get_string", get_string);

# in python
s = get_string
print s

This should work, of course.

Raoul Gough.
export LESS='-X'

More information about the Cplusplus-sig mailing list