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? .. The reduced code below compiles, creating the python function correctly, but I have not successfully defined to_python_value/to_python_converter statement(s), so the python predictably fails with a ".. no to_python .. converter for .. boost::variant .." when run.

I can find lots of helpful references to such converters of classes (eg http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/), but cannot see how I should use the to_python_value functionality to express the "convert the output of this function to a string, int or double as appropriate".

Thanks

Tim "novice, but learning" Couper


-- my_variant.cpp --

#include <sstream>

typedef boost::variant<int, double, std::string> my_variant;

template <class T>

bool from_string(T& t,const std::string& s, std::ios_base& (*f)(std::ios_base&))
    {
        std::istringstream iss(s);
        return !(iss >> f >> t).fail();
     }

namespace var {

    my_variant my_variant_of_string(const std::string& str)
// return a float, int or string depending on input parameter content
      {
        my_variant param;

        double dval; int ival;
        if (str.find(".") != std::string::npos) {
            if (from_string<double>(dval,str,std::dec)) {
                param = dval;
            }
        }
        else if (from_string<int>(ival,str,std::dec) ) {
            param = ival;
        }
        else {
            param= str;
        }
        return param;
     }

}// var

#include <boost/python/def.hpp>
#include <boost/python/module.hpp>

BOOST_PYTHON_MODULE(var)
{
    using namespace boost::python;

    def("my_variant_of_string", &var::my_variant_of_string);

}

_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to