@@ -312,7 +312,10 @@ void export_cache(py::module& m) {
312312 return py::cast (
313313 std::unique_ptr<cache_obj_t , CacheObjectDeleter>(dummy_obj));
314314 }
315- return py::cast (obj, py::return_value_policy::reference);
315+ return py::cast (*obj);
316+ // NOTE(haocheng): we return a copy of the object instead of reference
317+ // to avoid dangling reference in Python
318+ // return py::cast(obj, py::return_value_policy::reference);
316319 },
317320 " req" _a, " update_cache" _a = true )
318321 .def (
@@ -324,15 +327,17 @@ void export_cache(py::module& m) {
324327 .def (
325328 " insert" ,
326329 [](cache_t & self,
327- const request_t & req) -> std::optional< cache_obj_t *> {
330+ const request_t & req) -> py::object {
328331 cache_obj_t * inserted = self.insert (&self, &req);
329332 if (inserted == nullptr ) {
330- return std:: nullopt ;
333+ return py::none () ;
331334 }
332- return inserted;
335+ return py::cast (*inserted);
336+ // NOTE(haocheng): we return a copy of the object instead of reference
337+ // to avoid dangling reference in Python
338+ // return inserted;
333339 },
334- " req" _a,
335- py::return_value_policy::reference // optional still respected
340+ " req" _a
336341 )
337342
338343 .def (
@@ -358,7 +363,10 @@ void export_cache(py::module& m) {
358363 " to_evict" ,
359364 [](cache_t & self, const request_t & req) {
360365 cache_obj_t * obj = self.to_evict (&self, &req);
361- return py::cast (obj, py::return_value_policy::reference);
366+ return py::cast (*obj);
367+ // NOTE(haocheng): we return a copy of the object instead of reference
368+ // to avoid dangling reference in Python
369+ // return py::cast(obj, py::return_value_policy::reference);
362370 },
363371 " req" _a)
364372 .def (" get_occupied_byte" ,
0 commit comments