[C++-sig] Simple , , I think .. type conversion question C++ -> python

troy d. straszheim troy at resophonic.com
Wed Jan 13 20:10:26 CET 2010


Tim Couper wrote:
> OK. Here's what I've been stuck with all today .. I have a 3rd party C++ 
> program function which returns a boost::variant  (and its inverse)
> 
> my_variant my_variant_of_string(const std::string& str)
> 
> This one takes a string & returns a variant, and am trying to wrap this 
> in python, so that there I can have
> 
>  >>> my_variant_of_string('hello')
> 'hello'
> 
>  >>> my_variant_of_string('1.2')
> 1.2
> 
>  >>> my_variant_of_string('10')
> 10
> 
> Simple, eh? ...  

How about something like (not tested):

using boost::python::object;

typedef variant<...> variant_t;

variant_t makes_variant_from(string s); // defined elsewhere

//
// visitor for converting contents of visitor to object
//
struct vc : boost::static_visitor<object>
{
   template <typename T>
   object operator()(const T& v) const
   {
      return v;
   }
};

bp::object
thunk(string s)
{
   variant_t v = makes_variant_from(s);
   return boost::apply_visitor(vc(), v);
}

BOOST_PYTHON_MODULE(mod)
{
   def("f", &thunk);
}


You could probably use this to just register a converter from variant to 
vanilla boost::python::object as well, if this is more convenient...

-t





More information about the Cplusplus-sig mailing list