-
Hello, I'm trying to return a vector of items, here's the code: #include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <vector>
#include <format>
namespace bt {
using namespace std;
struct item {
ssize_t entry;
double value;
item(const item&) = default;
item(ssize_t _entry = -1, double _value = NAN):
entry(_entry), value(_value)
{}
};
vector<item> run(size_t len, const double *data) {
vector<item> items;
items.reserve(len);
for (size_t i = 0; i < len; ++i) {
items.emplace_back(i, data[i]);
}
return items;
}
};
namespace py = pybind11;
py::list run(const py::array_t<double, py::array::c_style | py::array::forcecast> data) {
if (data.ndim() != 1) {
throw std::invalid_argument("Input must be 1-D array");
}
return py::cast(bt::run(data.size(), data.data()));
}
PYBIND11_MODULE(bt, m) {
m.doc() = "pybind11 demo plugin";
py::class_<bt::item>(m, "item")
.def(
py::init<ssize_t, double>(),
py::arg("entry") = -1, py::arg("value") = NAN,
"constructor with entry and value"
)
.def("__repr__", [](const bt::item& self) {
return std::format(
"<bt.item entry={}, value={}>",
self.entry,
self.value
);
})
.def_readonly("entry", &bt::item::entry)
.def_readonly("value", &bt::item::value);
m.def("run", &run, py::arg("data"), "map elements to items");
} It compiles but fails in the runtime:
The error can be fixed if I do What am I doing wrong and how do I fix this? Thank you. |
Beta Was this translation helpful? Give feedback.
Answered by
naquad
Apr 26, 2024
Replies: 1 comment
-
Ah, what a silly mistake. Adding:
Has solved the error. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
naquad
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ah, what a silly mistake. Adding:
Has solved the error.