[C++-sig] Manual converter numpy.int32 -> double

Bruce Sherwood bruce.sherwood at gmail.com
Wed May 13 03:38:43 CEST 2009


Some time ago I wrote that I was having trouble installing a manual
converter to handle numpy.int32 -> double, something that used to work
automatically but no longer does. I  got crucial help from David Scherer
(the original creator of VPython). Just in case someone might be interested,
here is a routine that works.

struct double_from_int
{
double_from_int()
{
py::converter::registry::push_back(
&convertible,
&construct,
py::type_id<double>());
}

static void* convertible( PyObject* obj)
{
PyObject* newobj = PyNumber_Float(obj);
if (!PyString_Check(obj) && newobj) {
Py_DECREF(newobj);
return obj;
} else {
if (newobj) {
Py_DECREF(newobj);
}
PyErr_Clear();
return 0;
}
}

static void construct(
PyObject* _obj,
py::converter::rvalue_from_python_stage1_data* data)
{
PyObject* newobj = PyNumber_Float(_obj);
//void* storage = (
//            (py::converter::rvalue_from_python_storage<double>*)
//            data)->storage.bytes;
//*(double*)(storage) = py::extract<double>(newobj);

        double* storage = (double*)(
            (py::converter::rvalue_from_python_storage<double>*)
            data)->storage.bytes;
        *storage = py::extract<double>(newobj);
Py_DECREF(newobj);
data->convertible = storage;
}
};

Bruce Sherwood
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20090512/0298008e/attachment.htm>


More information about the Cplusplus-sig mailing list