example20.cpp 2.15 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
  example/example20.cpp -- Usage of structured numpy dtypes

  Copyright (c) 2016 Ivan Smirnov

  All rights reserved. Use of this source code is governed by a
  BSD-style license that can be found in the LICENSE file.
*/

#include "example.h"

#include <pybind11/numpy.h>
#include <cstdint>
#include <iostream>

namespace py = pybind11;

struct Struct {
    bool x;
    uint32_t y;
    float z;
};

struct PackedStruct {
    bool x;
    uint32_t y;
    float z;
} __attribute__((packed));

struct NestedStruct {
    Struct a;
    PackedStruct b;
Ivan Smirnov's avatar
Ivan Smirnov committed
33
34
35
36
37
38
39
40
} __attribute__((packed));

template <typename T>
py::array mkarray_via_buffer(size_t n) {
    return py::array(py::buffer_info(nullptr, sizeof(T),
                                     py::format_descriptor<T>::value(),
                                     1, { n }, { sizeof(T) }));
}
41
42
43

template <typename S>
py::array_t<S> create_recarray(size_t n) {
Ivan Smirnov's avatar
Ivan Smirnov committed
44
45
46
47
48
49
50
51
52
53
54
    auto arr = mkarray_via_buffer<S>(n);
    auto ptr = static_cast<S*>(arr.request().ptr);
    for (size_t i = 0; i < n; i++) {
        ptr[i].x = i % 2; ptr[i].y = (uint32_t) i; ptr[i].z = (float) i * 1.5f;
    }
    return arr;
}

py::array_t<NestedStruct> create_nested(size_t n) {
    auto arr = mkarray_via_buffer<NestedStruct>(n);
    auto ptr = static_cast<NestedStruct*>(arr.request().ptr);
55
    for (size_t i = 0; i < n; i++) {
Ivan Smirnov's avatar
Ivan Smirnov committed
56
57
        ptr[i].a.x = i % 2; ptr[i].a.y = (uint32_t) i; ptr[i].a.z = (float) i * 1.5f;
        ptr[i].b.x = (i + 1) % 2; ptr[i].b.y = (uint32_t) (i + 1); ptr[i].b.z = (float) (i + 1) * 1.5f;
58
59
    }
    return arr;
60
61
}

Ivan Smirnov's avatar
Ivan Smirnov committed
62

63
64
65
66
void print_format_descriptors() {
    std::cout << py::format_descriptor<Struct>::value() << std::endl;
    std::cout << py::format_descriptor<PackedStruct>::value() << std::endl;
    std::cout << py::format_descriptor<NestedStruct>::value() << std::endl;
67
68
69
70
71
72
73
74
75
}

void init_ex20(py::module &m) {
    PYBIND11_DTYPE(Struct, x, y, z);
    PYBIND11_DTYPE(PackedStruct, x, y, z);
    PYBIND11_DTYPE(NestedStruct, a, b);

    m.def("create_rec_simple", &create_recarray<Struct>);
    m.def("create_rec_packed", &create_recarray<PackedStruct>);
Ivan Smirnov's avatar
Ivan Smirnov committed
76
    m.def("create_rec_nested", &create_nested);
77
    m.def("print_format_descriptors", &print_format_descriptors);
78
}