complex.h revision 11986:c12e4625ab56
1/*
2    pybind11/complex.h: Complex number support
3
4    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6    All rights reserved. Use of this source code is governed by a
7    BSD-style license that can be found in the LICENSE file.
8*/
9
10#pragma once
11
12#include "pybind11.h"
13#include <complex>
14
15/// glibc defines I as a macro which breaks things, e.g., boost template names
16#ifdef I
17#  undef I
18#endif
19
20NAMESPACE_BEGIN(pybind11)
21
22PYBIND11_DECL_FMT(std::complex<float>, "Zf");
23PYBIND11_DECL_FMT(std::complex<double>, "Zd");
24
25NAMESPACE_BEGIN(detail)
26template <typename T> class type_caster<std::complex<T>> {
27public:
28    bool load(handle src, bool) {
29        if (!src)
30            return false;
31        Py_complex result = PyComplex_AsCComplex(src.ptr());
32        if (result.real == -1.0 && PyErr_Occurred()) {
33            PyErr_Clear();
34            return false;
35        }
36        value = std::complex<T>((T) result.real, (T) result.imag);
37        return true;
38    }
39
40    static handle cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
41        return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
42    }
43
44    PYBIND11_TYPE_CASTER(std::complex<T>, _("complex"));
45};
46NAMESPACE_END(detail)
47NAMESPACE_END(pybind11)
48