From: William S F. <ws...@fu...> - 2006-10-18 20:27:49
|
ta...@gm... wrote: > I want to use boost::optional for optional values in C++. > Wrapping them with SWIG does not work "out of the box". > Did anyone manage wrapping boost::optional with SWIG? > > There exists a class boost::none which represents an unset value (comparable > to C++'s NULL or Python's None) which I would like to have represented with > None in Python. > > Example: > C++ > --------- > class Test { > public: > void setValue(const boost::optional<int>& v); > const boost::optional<int>& value() const; > private: > boost::optional<int> _value; > }; > > In Python I want to work with this class like this: > > t = Test() > t.setValue(5) # sets the value to 5 > t.setValue(None) # sets the value to boost::none > > Maybe there is a way using typemaps? There is of course a way to do this with typemaps. The typemap for input int parameters could be: %typemap(in) int { long v = PyLong_AsLong($input); $1 = static_cast<int>(v); } The above is a rather simplified version of what is in SWIG's library for int. You'd then modify it slightly for boost::optional: %typemap(in) const boost::optional<int>& (boost::optional<int> tmp) { if ($input == Py_None) { tmp = boost::optional<int>(); } else { long v = PyLong_AsLong($input); tmp = boost::optional<int>(static_cast<int>(v)); } $1 = &tmp; } Of course this could be improved to add in error checking and to take a generic type and to use with %template. The the out typemap needs writing too, but this should be enough for you to get going... William |