[C++-sig] Re: boost::optional from python

Neal D. Becker ndbecker2 at verizon.net
Fri Sep 10 19:38:23 CEST 2004


David Abrahams wrote:

> "Neal D. Becker" <ndbecker2 at verizon.net> writes:
> 
>> I have C++ functions that take boost::optional arguments.  How best to
>> call them from python?
>>
>> Consider:
>>
>> int F (boost::optional<int>& o);
>>
>> It would be most natural to be able to (from python)
>>
>> i = F(None)
>> j = F(2)
>>
>> I'm guessing I could register a converter from T -> boost::optional<T>?
>> Still, how does this handle None?
> 
> This is a bit odd.  You want to get a mutable lvalue from Python when
> you pass None?  What should happens when F writes into o?  Same goes
> for 2, for that matter.  ints are immutable in Python.
> 

No, not mutable, let's say:

int F (boost::optional<int>const &o)

It almost works to do:

---optional_wrap.cc
template<typename T>
inline void set (boost::optional<T>& o, T x) {
  o = x;
}
  

template<typename T>
inline object get (boost::optional<T>& o) {
  return o ? object (o.get()) : object() ;
}

template<typename T>
inline boost::optional<T>* optional_from_object (object& o) {
  return new boost::optional<T>;
}

template<typename T>
static void exposeOptional (const char* name) {
  class_<boost::optional<T> >(name, init<T>())
    .def ("__init__", make_constructor (optional_from_object<T>))
    .def ("set", &set<T>)
    .def ("get", &get<T>)
    .def (!(self))
    ;
}

BOOST_PYTHON_MODULE(optional_wrap)
{

  exposeOptional<int> ("optional_int");
  exposeOptional<double> ("optional_double");
  
}
-------------------another module

int F (boost::optional<int>const& o) { return 2; }

BOOST_PYTHON_MODULE(something)
{
  PyImport_Import (str ("optional_wrap").ptr());

  def ("F", &F, (arg ("i")=boost::optional<int>()));

}

----------------------
>>> F
<Boost.Python.function object at 0x81960d8>
>>> F()
2
>>> F(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
Boost.Python.ArgumentError: Python argument types in
    _burstodemod_wrap.F(int)
did not match C++ signature:
    F(boost::optional<int> i=<optional_wrap.optional_int object at
0xf6f618b4>)






More information about the Cplusplus-sig mailing list