Extended python complex object. Includes `complex`, `numpy.complex64`, `numpy.complex128`.
| 18 | /// |
| 19 | /// Includes `complex`, `numpy.complex64`, `numpy.complex128`. |
| 20 | class Complex : public nanobind::object { |
| 21 | public: |
| 22 | NB_OBJECT_DEFAULT(Complex, nanobind::object, "complex", isComplex_) |
| 23 | |
| 24 | Complex(double real, double imag) |
| 25 | : nanobind::object(nanobind::steal(PyComplex_FromDoubles(real, imag))) { |
| 26 | if (!ptr()) { |
| 27 | throw std::runtime_error("Could not allocate complex object!"); |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // Allow implicit conversion from complex<double>/complex<float>: |
| 32 | // NOLINTNEXTLINE(google-explicit-constructor) |
| 33 | Complex(std::complex<double> value) |
| 34 | : Complex((double)value.real(), (double)value.imag()) {} |
| 35 | |
| 36 | // NOLINTNEXTLINE(google-explicit-constructor) |
| 37 | Complex(std::complex<float> value) |
| 38 | : Complex((double)value.real(), (double)value.imag()) {} |
| 39 | |
| 40 | // NOLINTNEXTLINE(google-explicit-constructor) |
| 41 | operator std::complex<double>() { |
| 42 | auto value = PyComplex_AsCComplex(ptr()); |
| 43 | return std::complex<double>(value.real, value.imag); |
| 44 | } |
| 45 | // NOLINTNEXTLINE(google-explicit-constructor) |
| 46 | operator std::complex<float>() { |
| 47 | auto value = PyComplex_AsCComplex(ptr()); |
| 48 | return std::complex<float>(value.real, value.imag); |
| 49 | } |
| 50 | |
| 51 | static bool isComplex_(PyObject *o) { |
| 52 | if (PyComplex_Check(o)) { |
| 53 | return true; |
| 54 | } |
| 55 | PyTypeObject *type = Py_TYPE(o); |
| 56 | std::string name = std::string(type->tp_name); |
| 57 | if (name == "numpy.complex64" || name == "numpy.complex128") { |
| 58 | return true; |
| 59 | } |
| 60 | return false; |
| 61 | } |
| 62 | }; |
| 63 | |
| 64 | /// Extended python float object. |
| 65 | /// |