So, I am trying to create a to_python converter that will allow me to return a boost::optional from an exposed function and have it treated as T if the optional is set and None if not. Based on a post I found on C++Sig, I wrote the following code.
template<typename T>
struct optional_ : private boost::noncopyable {
struct conversion {
static PyObject* convert(boost::optional<T> const& value) {
if (value) {
return boost::python::to_python_value<T>()(*value);
}
Py_INCREF(Py_None);
return Py_None;
}
};
explicit optional_() {
boost::python::to_python_converter<boost::optional<T>, conversion>();
}
};
As far as I can tell, it works for converting the optionals, but python throws the following exception "TypeError: No to_python (by-value) converter found for C++ type: std::string". I know that C++ is able to convert strings to python since most of my exposed functions return strings. Why doesn't boost::python::to_python_value recognize it, and how can I utilize whatever converter it has?
Fixed by changing to the following (based on this article):
template<typename T>
struct optional_ : private boost::noncopyable {
struct conversion {
static PyObject* convert(boost::optional<T> const& value) {
using namespace boost::python;
return incref((value ? object(*value) : object()).ptr());
}
};
explicit optional_() {
boost::python::to_python_converter<boost::optional<T>, conversion>();
}
};
Now to just do the other version so that it is cleaner and works better.