Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions docs/advanced/pycpp/numpy.rst
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,44 @@ Types whose spelling contains a comma must be wrapped in ``PYBIND11_TYPE``:
``PYBIND11_NUMPY_DTYPE(PYBIND11_TYPE(C<int, double>), x, y)``.
See :ref:`macro_notes`.

Use ``PYBIND11_NUMPY_DTYPE_EX`` to give a field a different name in NumPy. It
takes pairs of field and name:

.. code-block:: cpp

PYBIND11_NUMPY_DTYPE_EX(A, x, "count", y, "value");

These macros read the fields of the registered type, so the fields must be
accessible. If the fields are in a different type with the same layout (for
example, a public data struct that a class keeps as its only private member),
use ``py::register_numpy_dtype`` with a list of field descriptors:

.. code-block:: cpp

struct Data {
int64_t n_;
double v_;
};

class Wrapper {
Data data_;
// ...
};

static_assert(sizeof(Wrapper) == sizeof(Data), "layouts must match");
py::register_numpy_dtype<Wrapper>({
PYBIND11_FIELD_DESCRIPTOR_EX(Data, n_, "count"),
PYBIND11_FIELD_DESCRIPTOR(Data, v_),
});

``PYBIND11_FIELD_DESCRIPTOR(Type, field)`` makes a
``py::numpy_field_descriptor`` with the name of the field, and
``PYBIND11_FIELD_DESCRIPTOR_EX(Type, field, "name")`` sets the name. pybind11
does not check that the field offsets are correct for the registered type.

.. versionadded:: 3.2
``py::register_numpy_dtype`` and ``py::numpy_field_descriptor``.

Scalar types
============

Expand Down
14 changes: 14 additions & 0 deletions include/pybind11/numpy.h
Original file line number Diff line number Diff line change
Expand Up @@ -1884,6 +1884,20 @@ struct npy_format_descriptor {
}
};

PYBIND11_NAMESPACE_END(detail)

/// One field of a structured dtype; make it with ``PYBIND11_FIELD_DESCRIPTOR[_EX]``.
using numpy_field_descriptor = detail::field_descriptor;

/// Register a structured dtype for ``T`` from a list of field descriptors. The fields can
/// come from a different type; the caller must make sure that the layout matches ``T``.
template <typename T>
void register_numpy_dtype(detail::any_container<numpy_field_descriptor> fields) {
detail::npy_format_descriptor<T>::register_dtype(std::move(fields));
}

PYBIND11_NAMESPACE_BEGIN(detail)

#ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
# define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0)
# define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0)
Expand Down
44 changes: 40 additions & 4 deletions tests/test_numpy_dtypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,22 @@ PYBIND11_PACKED(struct StructWithUglyNames {
uint64_t __y__;
});

struct LayoutData {
int64_t n_;
double v_;
};

// Private members; the dtype comes from the layout-compatible LayoutData
class LayoutWrapper {
public:
LayoutWrapper() = default;
LayoutWrapper(int64_t n, double v) : data_{n, v} {}
double value() const { return data_.v_; }

private:
LayoutData data_;
};

template <typename T1, typename T2>
struct TemplatedStruct {
T1 a;
Expand Down Expand Up @@ -383,7 +399,7 @@ TEST_SUBMODULE(numpy_dtypes, m) {

// test_direct_field_descriptor
m.def("direct_field_descriptors", []() {
py::detail::field_descriptor direct[]
py::numpy_field_descriptor direct[]
= {PYBIND11_FIELD_DESCRIPTOR(SimpleStruct, uint_),
PYBIND11_FIELD_DESCRIPTOR_EX(SimpleStruct, float_, "flt"),
PYBIND11_FIELD_DESCRIPTOR(PYBIND11_TYPE(TemplatedStruct<int32_t, float>), b)};
Expand Down Expand Up @@ -411,9 +427,29 @@ TEST_SUBMODULE(numpy_dtypes, m) {

// Check that dtypes can be registered programmatically, both from
// initializer lists of field descriptors and from other containers.
py::detail::npy_format_descriptor<A>::register_dtype({});
py::detail::npy_format_descriptor<B>::register_dtype(
std::vector<py::detail::field_descriptor>{});
py::register_numpy_dtype<A>({});
py::register_numpy_dtype<B>(std::vector<py::numpy_field_descriptor>{});

// test_register_numpy_dtype
static_assert(sizeof(LayoutWrapper) == sizeof(LayoutData), "layouts must match");
py::register_numpy_dtype<LayoutWrapper>(
{PYBIND11_FIELD_DESCRIPTOR_EX(LayoutData, n_, "count"),
PYBIND11_FIELD_DESCRIPTOR_EX(LayoutData, v_, "value")});
m.def("create_layout_wrappers", [](py::ssize_t n) {
py::array_t<LayoutWrapper> arr(n);
auto *ptr = arr.mutable_data();
for (py::ssize_t i = 0; i < n; i++) {
ptr[i] = LayoutWrapper(i, static_cast<double>(i) * 0.5);
}
return arr;
});
m.def("sum_layout_wrappers", [](const py::array_t<LayoutWrapper> &arr) {
double sum = 0;
for (py::ssize_t i = 0; i < arr.size(); i++) {
sum += arr.data()[i].value();
}
return sum;
});

// test_recarray, test_scalar_conversion
m.def("create_rec_simple", &create_recarray<SimpleStruct>);
Expand Down
8 changes: 8 additions & 0 deletions tests/test_numpy_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,14 @@ def test_direct_field_descriptor():
assert m.direct_field_descriptors() == ["uint_", "flt", "b"]


def test_register_numpy_dtype():
arr = m.create_layout_wrappers(3)
assert arr.dtype == np.dtype([("count", "i8"), ("value", "f8")])
assert arr["count"].tolist() == [0, 1, 2]
assert arr["value"].tolist() == [0.0, 0.5, 1.0]
assert m.sum_layout_wrappers(arr) == 1.5


def test_recarray(simple_dtype, packed_dtype):
elements = [(False, 0, 0.0, -0.0), (True, 1, 1.5, -2.5), (False, 2, 3.0, -5.0)]

Expand Down
Loading