Boost logo

Boost :

From: morandini_at_[hidden]
Date: 2001-08-31 04:30:51


Dear all,

I don't cleary understand the reason why a
double& from_python(PyObject* p, boost::python::type<double&>)
function is dangerous.

I tried something like

#include <boost/python/class_builder.hpp>
namespace boost { namespace python {

namespace detail {

void expect_float(PyObject* p) {
        if (!PyFloat_Check(p)) {
                PyErr_SetString(PyExc_TypeError, "expected a float
number");
                throw boost::python::argument_error();
        }
}

} // namespace boost::python::detail
} //namespace boost::python
} //namespace boost

double& from_python(PyObject* p, boost::python::type<double&>) {
        boost::python::detail::expect_float(p);
// return reinterpret_cast<PyFloatObject *>(p)->ob_fval;
        return PyFloat_AS_DOUBLE(p)
};

and it seems to work for me:

double dummy(double& b) {
double a;
a=b;
b+=1;
return a*2;
};
BOOST_PYTHON_MODULE_INIT(p)
{
        try {
                python::module_builder this_module("p");
                this_module.def(pippo, "pippo");
        }
        catch(...) {
                python::handle_exception();
        }
}

and then, in python:

>>> from p import *
>>> a=float(6)
>>> pippo(a)
12.0
>>> a
7.0

Apologize if this is a silly c++ or python question.
Thanks in advance,

Marco Morandini


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk