blob: c22eb213eef499e4b9d5413b08dc9709182d6620 [file] [log] [blame]
Ivan Smirnovbb4015d2016-06-19 15:50:31 +01001/*
2 example/example20.cpp -- Usage of structured numpy dtypes
3
4 Copyright (c) 2016 Ivan Smirnov
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
10#include "example.h"
11
12#include <pybind11/numpy.h>
13#include <cstdint>
14#include <iostream>
15
16namespace py = pybind11;
17
18struct Struct {
19 bool x;
20 uint32_t y;
21 float z;
22};
23
24struct PackedStruct {
25 bool x;
26 uint32_t y;
27 float z;
28} __attribute__((packed));
29
30struct NestedStruct {
31 Struct a;
32 PackedStruct b;
33};
34
35template <typename S>
36py::array_t<S> create_recarray(size_t n) {
37 auto arr = py::array(py::buffer_info(nullptr, sizeof(S),
38 py::format_descriptor<S>::value(),
39 1, { n }, { sizeof(S) }));
40 auto buf = arr.request();
41 auto ptr = static_cast<S*>(buf.ptr);
42 for (size_t i = 0; i < n; i++) {
43 ptr[i].x = i % 2;
44 ptr[i].y = i;
45 ptr[i].z = i * 1.5;
46 }
47 return arr;
48}
49
50void init_ex20(py::module &m) {
51 PYBIND11_DTYPE(Struct, x, y, z);
52 PYBIND11_DTYPE(PackedStruct, x, y, z);
53 PYBIND11_DTYPE(NestedStruct, a, b);
54
55 m.def("create_rec_simple", &create_recarray<Struct>);
56 m.def("create_rec_packed", &create_recarray<PackedStruct>);
57}