[C++-sig] Converting std::vector<T> to Python tuple

Paul F. Kunz Paul_Kunz at SLAC.Stanford.EDU
Thu Nov 21 20:38:25 CET 2002


Took a couple hours off from my VC++ 7 woes this morning to continue
converting to boost.python V2 under Linux.  I needed to expose to
Python member functions of a C++ class that returned a const
vector<double> & and const vector<string> &.   After pouring over the
documentation, FAQ, and mailing list archives, I came up with a
solution that works for me, but would like to receive comment on it.

First, from Ralf's scitbx package, I copied 

template ( typename ContainerType >
struct to_tuple {...} 

into my own code.   Then within my BOOST_PYTHON_MODULE I have ...

  class_ < PyFunctionRep > ( "Function",
			     init < const std::string & > () )
    .def ( "parmNames", &PyFunctionRep::parmNames, // ret vector<string>
	   return_value_policy < copy_const_reference > () )
    .def ( "parameters", &PyFunctionRep::parameters, // ret vector<double>
 	   return_value_policy < copy_const_reference > () )
    ;

and ...

  to_python_converter < 
    const std::vector < double >,
    to_tuple < const std::vector < double > >  > ();

  to_python_converter <
    const std::vector < std::string >,
    to_tuple < const std::vector < std::string > >  > ();

Is this correct?   Suggestion for improvements?

If this is correct, may I suggest that something like it go into the
tutorial and/or FAQ.




More information about the Cplusplus-sig mailing list