[C++-sig] Re: std::complex<double>?

Neal D. Becker nbecker at hns.com
Fri Jan 9 18:47:21 CET 2004


Raoul Gough wrote:

> David Abrahams <dave at boost-consulting.com> writes:
> 
>> "Neal D. Becker" <nbecker at hns.com> writes:
> [snip]
>>> z=CDoubleVec(2)
>>>>>> z
>>> <hello.CDoubleVec object at 0x8446a54>
>>>>>> z[0]
>>> Traceback (most recent call last):
>>>   File "<stdin>", line 1, in ?
>>> TypeError: No Python class registered for C++ class std::complex<double>
>>
>> That's because the vector_indexing_suite is trying to treat
>> std::complex like any other class, instead of like an int (i.e. a
>> type with an immutable Python counterpart).  I don't know what the
>> answer to that is, though.  Joel/Raoul?
>>
>>> I also will need std::complex<int>.  What would I need for this?
>>
>> complex<int> isn't even guaranteed to work by the C++ standard.  You'd
>> need to explicitly register to/from-python converters for it.
> 
> I think what Jonathan Brandmeyer was suggesting would do the
> trick. The indexing suite(s) just assume that the contained type is
> already known to Python, and the easiest way to do that is to create a
> boost::python::class_ instance for it.
> 

>From reading the docs, I got the idea that to_python_converter should work. 
I tried:

using namespace boost::python;


struct whatever {
  static PyObject* convert (std::complex<double> const& x) {
    return PyComplex_FromCComplex(*reinterpret_cast<const Py_complex*>
(&x));
  }
};

BOOST_PYTHON_MODULE(hello)
{    

    class_<std::vector<double> >("DoubleVec")
      .def(init<size_t>())
      .def(vector_indexing_suite<std::vector<double> >())
    ;

    to_python_converter<std::complex<double>, whatever>();

    class_<std::vector<std::complex<double> > >("CDoubleVec")
      .def(init<size_t>())
      .def(vector_indexing_suite<std::vector<std::complex<double> > >())
    ;
    
}
from hello import *
>>> v=CDoubleVec(2)
>>> v
<hello.CDoubleVec object at 0x9a7f85c>
>>> v[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: No Python class registered for C++ class std::complex<double>

1. I don't know why this doesn't work.
2. I don't know if this has the right semantics.  I want the python complex
value to be a reference to the c++ one.

Am I on the correct track here?  Can anyone give me a clue?





More information about the Cplusplus-sig mailing list