complex.h revision 12037:d28054ac6ec9
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)
21NAMESPACE_BEGIN(detail)
22
23// The format codes are already in the string in common.h, we just need to provide a specialization
24template <typename T> struct is_fmt_numeric<std::complex<T>> {
25    static constexpr bool value = true;
26    static constexpr int index = is_fmt_numeric<T>::index + 3;
27};
28
29template <typename T> class type_caster<std::complex<T>> {
30public:
31    bool load(handle src, bool convert) {
32        if (!src)
33            return false;
34        if (!convert && !PyComplex_Check(src.ptr()))
35            return false;
36        Py_complex result = PyComplex_AsCComplex(src.ptr());
37        if (result.real == -1.0 && PyErr_Occurred()) {
38            PyErr_Clear();
39            return false;
40        }
41        value = std::complex<T>((T) result.real, (T) result.imag);
42        return true;
43    }
44
45    static handle cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
46        return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
47    }
48
49    PYBIND11_TYPE_CASTER(std::complex<T>, _("complex"));
50};
51NAMESPACE_END(detail)
52NAMESPACE_END(pybind11)
53