complex.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. pybind11/complex.h: Complex number support
  3. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #pragma once
  8. #include "pybind11.h"
  9. #include <complex>
  10. /// glibc defines I as a macro which breaks things, e.g., boost template names
  11. #ifdef I
  12. # undef I
  13. #endif
  14. NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  15. template <typename T> struct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
  16. static constexpr const char c = format_descriptor<T>::c;
  17. static constexpr const char value[3] = { 'Z', c, '\0' };
  18. static std::string format() { return std::string(value); }
  19. };
  20. #ifndef PYBIND11_CPP17
  21. template <typename T> constexpr const char format_descriptor<
  22. std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>>::value[3];
  23. #endif
  24. NAMESPACE_BEGIN(detail)
  25. template <typename T> struct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
  26. static constexpr bool value = true;
  27. static constexpr int index = is_fmt_numeric<T>::index + 3;
  28. };
  29. template <typename T> class type_caster<std::complex<T>> {
  30. public:
  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. static handle cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
  45. return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
  46. }
  47. PYBIND11_TYPE_CASTER(std::complex<T>, _("complex"));
  48. };
  49. NAMESPACE_END(detail)
  50. NAMESPACE_END(PYBIND11_NAMESPACE)