[C++-sig] Re: Wrapping functions with lvalue arguments

Wagner Bruna wbruna at yahoo.com
Wed Jan 19 00:16:11 CET 2005


Hi,

"Baptiste Lepilleur" wrote:

> I believe
> boost::python::implicitly_convertible<...>() is what
> you are looking for. Check the reference doc, it has
> a example very similar to you case.

Thanks for your reply, but it didn't work. Looks like
implicitly_convertible should not be used for
references (at least to int):

boost/python/converter/implicit.hpp(33) :
error C2464: 'int &' : cannot use 'new' to allocate a
reference
(...) while compiling class-template member function
'void __cdecl
boost::python::converter::implicit<struct
implicit_test,int &>::
  construct(struct _object *,
    struct
boost::python::converter::rvalue_from_python_stage1_data
*)'


Well, I found another way. Even uglier than my first
solution, but at least I'm not changing library
headers anymore... Here it goes:

int lvalue(int & i) { return i++; }

struct IntHolder
{
  int obj_;
  IntHolder(int obj) : obj_(obj) { }
  operator int&() { return obj_; }
  operator int() const { return obj_; }
  static int get(int obj) { return obj; }
  static void set(int & obj, int value) { obj = value;
}
};

namespace boost { namespace python { namespace detail
{
  template <>
  inline typeinfo
msvc_typeid<IntHolder>(BOOST_EXPLICIT_TEMPLATE_TYPE_SPEC(IntHolder))
  {
    return
python::detail::msvc_typeid((boost::type<int>*)0);
  }
}}}

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

  def("rvalue", &rvalue);

  class_<IntHolder>("IntHolder", init<int>())
    .add_property("obj", &IntHolder::get,
&IntHolder::set)
    ;
}

>>> a = IntHolder(0)
>>> lvalue(a)
0
>>> a.obj
1

If I understand correctly, what I'm doing here is
registering IntHolder with the int type identifier, so
the type system matches my struct with the lvalue int
parameter.Still a hack, though...

By the way, wrapping a function returning int& using
return_value_policy<reference_existing_object> gets
that same "is_class" assertion failure on
object/make_instance.hpp. Maybe that's intentional -
because Python integers are immutable. But then I
don't understand why wrapping an int& parameter is
accepted.

Thanks,
Wagner



	
		
__________________________________ 
Do you Yahoo!? 
Yahoo! Mail - You care about security. So do we. 
http://promotions.yahoo.com/new_mail



More information about the Cplusplus-sig mailing list