[C++-sig] Double arrays from python to c++

Geir Arne Evjen g-evjen at online.no
Fri Jun 13 10:02:00 CEST 2003


I've started to test this superb boost::python package . However, I have
problems getting the following code to work.


#include <iostream>
#include <boost/python.hpp>

struct EatDoubleArray {
  EatDoubleArray(const double * const parray, const int size) :
m_parray(parray), m_size(size) { }
  const double * const m_parray;
  const int m_size;
};

std::ostream& operator<<(std::ostream& in, const EatDoubleArray& obj) {
  for (int i = 0; i < obj.m_size; ++i) in << obj.m_parray[i];

  in << std::endl;
  return in;
}

using namespace boost::python;

struct ListToArrayConverter {


  ListToArrayConverter() {
    converter::registry::insert(&ListToArray_convertible,
&ListToArray_construct, boost::python::type_id<const double * const>());

  }

  static void ListToArray_construct(PyObject* obj,
boost::python::converter::rvalue_from_python_stage1_data* data)
  {
    boost::python::list l;

    if  (PyList_Check(obj)) {
      l = extract<boost::python::list>(obj);
    } else return;

    // Allocate the bytes
    void* storage =
((converter::rvalue_from_python_storage<double>*)data)->storage.bytes;
    int n = extract<int>(l.attr("__len__"));
    new (storage) double[n];


    for (int i = 0; i < n; ++i)  {
      *((double*)storage + i) = extract<double>(l[i]);
    }

    data->convertible = storage;
  }

  static void *ListToArray_convertible(PyObject *p) {
    return p;
  }
};

// Python requires an exported function called init<module-name> in
every
// extension module. This is where we build the module contents.
BOOST_PYTHON_MODULE(pydoubletest)
{
  ListToArrayConverter();

  class_<EatDoubleArray>("EatDoubleArray", init<const double * const,
const int>())
    .def(self_ns::str(self))
    ;

}

When I'm testing this from python I get the following message: 

Traceback (most recent call last):
  File "doubletest.py", line 4, in ?
    a = EatDoubleArray(A, 4)
TypeError: bad argument type for built-in operation

Basically I just want to create an array in Python and use it in C++ . 
Any ideas what I have done wrong, or misunderstood.

Thanks in advance


Geir Arne Evjen







More information about the Cplusplus-sig mailing list