From 11405d1ae27aea5a66792cd6baa9fd3c241c6096 Mon Sep 17 00:00:00 2001 From: jakirkham Date: Wed, 31 Jul 2024 03:32:19 -0700 Subject: [PATCH] Use `py::object` to hold `py::memoryview` As `py::memoryview` must be assigned and we cannot guarantee it will assign without error, declare `py::object` and place the results of `py::memoryview` (if successful) into `py::object`. Can reconstruct the `py::memoryview` later to get the actual object out. --- python/pybind11/cucim_py.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/python/pybind11/cucim_py.cpp b/python/pybind11/cucim_py.cpp index b9675187..66716669 100644 --- a/python/pybind11/cucim_py.cpp +++ b/python/pybind11/cucim_py.cpp @@ -447,20 +447,20 @@ py::object py_read_region(const CuImage& cuimg, { py::gil_scoped_acquire scope_guard; - py::memoryview mv; - bool has_mv = false; + py::object mv_obj(py::none()); try { - mv = py::memoryview(location); - has_mv = true; + mv_obj = py::memoryview(location); } catch (const std::exception& e) { } - if (has_mv) // fast copy + if (!mv_obj.is_none()) // fast copy { - py::buffer_info buf = py::buffer_info(PyMemoryView_GET_BUFFER(mv.ptr()), false); + py::memoryview mv(mv_obj); + py::buffer_info buf(PyMemoryView_GET_BUFFER(mv.ptr()), false); + if (buf.format != py::format_descriptor::format()) { throw std::invalid_argument("Expected int64 array-like");