You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.5 KiB

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