[C++-sig] Wrapping functions with lvalue arguments
Wagner Bruna
wbruna at yahoo.com
Sun Jan 16 05:23:34 CET 2005
Hello,
I'm trying to wrap some C++ functions that take some
arguments by non-const reference. I didn't want to
return a tuple in this particular case (mainly because
there'll be a lot of variables), so I tried to build a
"holder" object to store the primitive type and pass
it as an lvalue. Something like:
void my_function(int & value);
struct IntHolder {
int obj;
operator int&() {
return obj;
}
};
(in theory, the implicit conversion would allow me to
wrap and use my_function directly)
But I couldn't find a way to wrap the conversion
operator to int&. I also tried a free function
returning int&, and a wrapped int member, without
sucess. What I found really strange was, although I
could wrap my_function(int&) without problems, I
couldn't find any way to actually pass an lvalue int
into it.
Well... The curious part is: after some unfruitful
tries, almost by accident I found a rather bizarre
way. Easier to show than to describe:
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/module.hpp>
int my_function(int & i) { return i++; }
// "member" functions
int get_obj(int obj) { return obj; }
void set_obj(int & obj, int v) { obj = v; }
BOOST_PYTHON_MODULE(holder)
{
using namespace boost::python;
def("my_function", &my_function);
class_<int>("IntHolder", init<int>())
.add_property("obj", &get_obj, &set_obj)
;
}
It is necessary to comment out the is_class static
assertion on boost/python/object/make_instance.hpp -
and I understand this implies I'm *not* doing
something recommended... anyways, it did the job:
>>> from holder import *
>>> a = IntHolder(42)
>>> a
<holder.IntHolder object at 0x01587210>
>>> a.obj
42
>>> my_function(a)
42
>>> a.obj
43
But is there a better (or "less hacking") way to make
this "holder" object? And are there better
alternatives to deal with functions that must return
by reference?
Thanks in advance,
Wagner
pdf: FWIW, I'm using Boost.Python from release 1.32.0,
and Visual C++ 6.
__________________________________
Do you Yahoo!?
Yahoo! Mail - Helps protect you from nasty viruses.
http://promotions.yahoo.com/new_mail
More information about the Cplusplus-sig
mailing list