Skip to content

Commit fcbaf0f

Browse files
committed
added test for returning a struct of std::vector as a python class of numpy arrays
1 parent 7625503 commit fcbaf0f

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

.vscode/settings.json

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@
2121
"initializer_list": "cpp",
2222
"string_view": "cpp",
2323
"valarray": "cpp",
24-
"stdexcept": "cpp"
24+
"stdexcept": "cpp",
25+
"optional": "cpp",
26+
"istream": "cpp",
27+
"ostream": "cpp",
28+
"system_error": "cpp",
29+
"type_traits": "cpp",
30+
"variant": "cpp"
2531
}
2632
}

src/main.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,24 @@ py::array_t<double> get_ndarray(int n, double value)
4242
return py::array(result.size(), result.data());
4343
}
4444

45+
struct VectorResults
46+
{
47+
const py::array_t<double> temperature;
48+
const py::array_t<double> humidity;
49+
};
50+
51+
VectorResults get_vector_results(int len, double temp_value, double hum_value)
52+
{
53+
auto tmp = std::vector<double>(len, temp_value);
54+
auto hum = std::vector<double>(len, hum_value);
55+
VectorResults results = {
56+
py::array(tmp.size(), tmp.data()), // temperature
57+
py::array(hum.size(), hum.data()), // humidity
58+
};
59+
60+
return results;
61+
}
62+
4563
PYBIND11_MODULE(python_example, m)
4664
{
4765
m.doc() = R"pbdoc(
@@ -80,6 +98,12 @@ PYBIND11_MODULE(python_example, m)
8098
m.def("range_error", &range_error);
8199
m.def("get_ndarray", &get_ndarray);
82100

101+
py::class_<VectorResults>(m, "VectorResults")
102+
.def_readonly("temperature", &VectorResults::temperature)
103+
.def_readonly("humidity", &VectorResults::humidity);
104+
105+
m.def("get_vector_results", &get_vector_results);
106+
83107
#ifdef VERSION_INFO
84108
m.attr("__version__") = VERSION_INFO;
85109
#else

tests/test_python_example.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,14 @@ def test_return_ndarray():
3535
assert isinstance(a, np.ndarray)
3636
np.testing.assert_allclose(a, 5.0)
3737
assert len(a) == 10
38+
39+
40+
def test_get_class_with_vector_results():
41+
n = 10
42+
t = 4.3
43+
h = 88.3
44+
results = m.get_vector_results(n, t, h)
45+
assert len(results.temperature) == n
46+
np.testing.assert_allclose(results.temperature, t)
47+
assert len(results.humidity) == n
48+
np.testing.assert_allclose(results.humidity, h)

0 commit comments

Comments
 (0)