Re: [pygccxml-development] How to return a std::vector<std::string> to Python
Brought to you by:
mbaas,
roman_yakovenko
From: Roman Y. <rom...@gm...> - 2008-09-10 19:07:32
|
On Wed, Sep 10, 2008 at 6:08 PM, <bf...@co...> wrote: > Hi, > > also after lengthy search on the net I could not find a working example for the following (probably common) use case: > > I would like to expose a C++ function to Python which has as result type > std::vector<std::string> > > When invoking the exposed function from Python I get the message > > File "test.py", line 15, in <module> > v = a.alias_to_account_list(al) > TypeError: No to_python (by-value) converter found for C++ type: std::vector<std::string, std::allocator<std::string> > > > The function looks as follows: > vector<string> alias_to_account_list(string ali="SAP") { > set<string> accts = _tlib2->alias_to_account_list(ali); > cerr << "alias '" << ali << "' expands to that many accounts::" << accts.size() << endl; > copy(accts.begin(), accts.end(), ostream_iterator<string>(cerr, ",")); > vector<string> res; > copy(accts.begin(), accts.end(), back_inserter(res)); > return res; > } > > What can I do? Is there a way to construct native Python objects? Interestingly my code works when I return > std::vector<int> > > In this case I can access the elements of the vector from python with the [] notation. The object is no native python array, however, which I would prefer. > I am only interested in return by value at this point, so I do not want to change the C++ vector from Python. > > This is what I want to do in Python: > > for al in ["MAN","LHA","SIE25"]: > v = a.alias_to_account_list(al) > print "dir(v)= ",dir(v), len(v),v[0],v[1],v[2] > > Any hints are appreciated, What indexing suite do you use? If you use indexing suite that comes with boost.python than the following code will register your vector correctly: typedef std::vector< std::string > strings_t; inline void do_nothing( const strings_t& ){} inline strings_t get_names(){...} namespace bp = boost::python; typedef bp::class_< std::vector< std::string > > strings_t_exposer_t; strings_t_exposer_t strings_t_exposer = strings_t_exposer_t( "strings_t", "documentation" ); bp::scope strings_t_scope( strings_t_exposer ); strings_t_exposer.def( bp::vector_indexing_suite< ::std::vector< std::string >, true >() ); Py++ should be able to generate the correct code, if not show me your use case - I will improve it. HTH -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ |