complex.h revision 12391:ceeca8b41e4b
15390SN/A/*
25390SN/A    pybind11/complex.h: Complex number support
35390SN/A
45390SN/A    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
55390SN/A
65390SN/A    All rights reserved. Use of this source code is governed by a
75390SN/A    BSD-style license that can be found in the LICENSE file.
85390SN/A*/
95390SN/A
105390SN/A#pragma once
115390SN/A
125390SN/A#include "pybind11.h"
135390SN/A#include <complex>
145390SN/A
155390SN/A/// glibc defines I as a macro which breaks things, e.g., boost template names
165390SN/A#ifdef I
175390SN/A#  undef I
185390SN/A#endif
195390SN/A
205390SN/ANAMESPACE_BEGIN(PYBIND11_NAMESPACE)
215390SN/A
225390SN/Atemplate <typename T> struct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
235390SN/A    static constexpr const char c = format_descriptor<T>::c;
245390SN/A    static constexpr const char value[3] = { 'Z', c, '\0' };
255390SN/A    static std::string format() { return std::string(value); }
265390SN/A};
275390SN/A
285390SN/Atemplate <typename T> constexpr const char format_descriptor<
295390SN/A    std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>>::value[3];
305390SN/A
3111793Sbrandon.potter@amd.comNAMESPACE_BEGIN(detail)
3211793Sbrandon.potter@amd.com
338232Snate@binkert.orgtemplate <typename T> struct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
345634Sgblack@eecs.umich.edu    static constexpr bool value = true;
355390SN/A    static constexpr int index = is_fmt_numeric<T>::index + 3;
365390SN/A};
375632Sgblack@eecs.umich.edu
385632Sgblack@eecs.umich.edutemplate <typename T> class type_caster<std::complex<T>> {
395632Sgblack@eecs.umich.edupublic:
4014290Sgabeblack@google.com    bool load(handle src, bool convert) {
4114290Sgabeblack@google.com        if (!src)
4214290Sgabeblack@google.com            return false;
4314290Sgabeblack@google.com        if (!convert && !PyComplex_Check(src.ptr()))
4414290Sgabeblack@google.com            return false;
455632Sgblack@eecs.umich.edu        Py_complex result = PyComplex_AsCComplex(src.ptr());
465632Sgblack@eecs.umich.edu        if (result.real == -1.0 && PyErr_Occurred()) {
475390SN/A            PyErr_Clear();
485390SN/A            return false;
495390SN/A        }
505390SN/A        value = std::complex<T>((T) result.real, (T) result.imag);
515629Sgblack@eecs.umich.edu        return true;
525390SN/A    }
535390SN/A
5413229Sgabeblack@google.com    static handle cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
555390SN/A        return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
565390SN/A    }
5713229Sgabeblack@google.com
585390SN/A    PYBIND11_TYPE_CASTER(std::complex<T>, _("complex"));
595390SN/A};
605390SN/ANAMESPACE_END(detail)
615390SN/ANAMESPACE_END(PYBIND11_NAMESPACE)
625898Sgblack@eecs.umich.edu