-
I have a example like below: #include <memory>
#include <vector>
#include "nanobind/nanobind.h"
#include "nanobind/stl/shared_ptr.h"
namespace nb = nanobind;
using namespace nb::literals;
struct Time {
Time() noexcept = default;
double value{};
virtual ~Time() = default;
};
struct MyTime: public Time {
MyTime() noexcept {
value = 1.0 * rand() / RAND_MAX;
a = 1.0 * rand() / RAND_MAX;
}
double a{};
};
static std::vector<std::shared_ptr<Time>> times{};
NB_MODULE(test_nanobind_shared_ptr_in_cpp, m) {
nb::class_<Time>(m, "Time", nb::dynamic_attr())
.def(nb::init<>())
.def_prop_rw(
"value", [](Time &self) { return self.value; },
[](Time &self, double value) { self.value = value; });
nb::class_<MyTime, Time>(m, "MyTime")
.def(nb::init<>())
.def_prop_rw("a", [](MyTime &self) { return self.a; },
[](MyTime &self, double value) { self.a = value; });
m.def("push", []() {
// create MyTime and push to queue.
times.emplace_back(std::static_pointer_cast<Time>(std::make_shared<MyTime>()));
});
m.def("pop", []() {
// pop from queue
std::shared_ptr<Time> last = std::move(times.back());
times.pop_back();
return last;
});
} When I call from test_nanobind_shared_ptr_in_cpp import MyTime, Time, push, pop
push()
popped = pop()
print(popped) I get below error msgs:
If I push a few more times and then pop, then I can see a segmentation fault: for i in range(10):
push()
for i in range(10):
popped = pop()
print(f"Popped: {popped}") I checked the document about m.def("pop", []() {
std::shared_ptr<Time> last = std::move(times.back());
times.pop_back();
return std::static_pointer_cast<MyTime>(last);
}); Any suggestion would be appreciated! My environment is: macOS Ventura, Python 3.9.17, with nanobind 1.4.0. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
If I put the nb::class_<Time>(m, "Time")
nb::class_<MyTime, Time>(m, "MyTime", nb::dynamic_attr()) So the issue seems comes from the |
Beta Was this translation helpful? Give feedback.
I just released version 1.5.0. Can you confirm that it fixes your issue?