Add a basic test for recarrays and complex dtypes

This commit is contained in:
Ivan Smirnov 2016-06-19 15:50:31 +01:00
parent 2488b32066
commit bb4015ded3
5 changed files with 79 additions and 1 deletions

View File

@ -26,6 +26,7 @@ set(PYBIND11_EXAMPLES
example-stl-binder-vector.cpp
example-eval.cpp
example-custom-exceptions.cpp
example20.cpp
issues.cpp
)
@ -65,4 +66,3 @@ foreach(VALUE ${PYBIND11_EXAMPLES})
string(REGEX REPLACE "^(.+).cpp$" "\\1" EXAMPLE_NAME "${VALUE}")
add_test(NAME ${EXAMPLE_NAME} COMMAND ${RUN_TEST} ${EXAMPLE_NAME})
endforeach()

View File

@ -29,6 +29,7 @@ void init_ex_inheritance(py::module &);
void init_ex_stl_binder_vector(py::module &);
void init_ex_eval(py::module &);
void init_ex_custom_exceptions(py::module &);
void init_ex20(py::module &);
void init_issues(py::module &);
#if defined(PYBIND11_TEST_EIGEN)
@ -72,6 +73,7 @@ PYBIND11_PLUGIN(example) {
init_ex_stl_binder_vector(m);
init_ex_eval(m);
init_ex_custom_exceptions(m);
init_ex20(m);
init_issues(m);
#if defined(PYBIND11_TEST_EIGEN)

57
example/example20.cpp Normal file
View File

@ -0,0 +1,57 @@
/*
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;
};
template <typename S>
py::array_t<S> create_recarray(size_t n) {
auto arr = py::array(py::buffer_info(nullptr, sizeof(S),
py::format_descriptor<S>::value(),
1, { n }, { sizeof(S) }));
auto buf = arr.request();
auto ptr = static_cast<S*>(buf.ptr);
for (size_t i = 0; i < n; i++) {
ptr[i].x = i % 2;
ptr[i].y = i;
ptr[i].z = i * 1.5;
}
return arr;
}
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>);
}

19
example/example20.py Normal file
View File

@ -0,0 +1,19 @@
#!/usr/bin/env python
from __future__ import print_function
import numpy as np
from example import create_rec_simple
def check_eq(arr, data, dtype):
np.testing.assert_equal(arr, np.array(data, dtype=dtype))
dtype = np.dtype({'names': ['x', 'y', 'z'],
'formats': ['?', 'u4', 'f4'],
'offsets': [0, 4, 8]})
base_dtype = np.dtype([('x', '?'), ('y', 'u4'), ('z', 'f4')])
arr = create_rec_simple(3)
assert arr.dtype == dtype
check_eq(arr, [(False, 0, 0.0), (True, 1, 1.5), (False, 2, 3.0)], dtype)
check_eq(arr, [(False, 0, 0.0), (True, 1, 1.5), (False, 2, 3.0)], base_dtype)

0
example/example20.ref Normal file
View File