diff --git a/include/pybind11/detail/common.h b/include/pybind11/detail/common.h index 19ebc8532e..4225042879 100644 --- a/include/pybind11/detail/common.h +++ b/include/pybind11/detail/common.h @@ -214,6 +214,10 @@ # define PYBIND11_HAS_STRING_VIEW 1 #endif +#if defined(PYBIND11_CPP20) && defined(__has_include) && __has_include() +# define PYBIND11_HAS_SPAN 1 +#endif + #if (defined(PYPY_VERSION) || defined(GRAALVM_PYTHON)) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT) # define PYBIND11_SIMPLE_GIL_MANAGEMENT #endif diff --git a/include/pybind11/numpy.h b/include/pybind11/numpy.h index 6fa6c772b9..408d1699cf 100644 --- a/include/pybind11/numpy.h +++ b/include/pybind11/numpy.h @@ -29,6 +29,10 @@ #include #include +#ifdef PYBIND11_HAS_SPAN +# include +#endif + #if defined(PYBIND11_NUMPY_1_ONLY) # error "PYBIND11_NUMPY_1_ONLY is no longer supported (see PR #5595)." #endif @@ -1143,6 +1147,13 @@ class array : public buffer { /// Dimensions of the array const ssize_t *shape() const { return detail::array_proxy(m_ptr)->dimensions; } +#ifdef PYBIND11_HAS_SPAN + /// Dimensions of the array as a span + std::span shape_span() const { + return std::span(shape(), static_cast(ndim())); + } +#endif + /// Dimension along a given axis ssize_t shape(ssize_t dim) const { if (dim >= ndim()) { @@ -1154,6 +1165,13 @@ class array : public buffer { /// Strides of the array const ssize_t *strides() const { return detail::array_proxy(m_ptr)->strides; } +#ifdef PYBIND11_HAS_SPAN + /// Strides of the array as a span + std::span strides_span() const { + return std::span(strides(), static_cast(ndim())); + } +#endif + /// Stride along a given axis ssize_t strides(ssize_t dim) const { if (dim >= ndim()) {