From fd5cb64a2b696c405c758f6ff07b24a59f220850 Mon Sep 17 00:00:00 2001 From: Matevz Morato Date: Tue, 17 Dec 2024 17:12:31 +0100 Subject: [PATCH] Acquire the GIL when calling Python callbacks in the MessageQueue --- bindings/python/src/MessageQueueBindings.cpp | 26 ++++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/bindings/python/src/MessageQueueBindings.cpp b/bindings/python/src/MessageQueueBindings.cpp index 54201722e..e819d332a 100644 --- a/bindings/python/src/MessageQueueBindings.cpp +++ b/bindings/python/src/MessageQueueBindings.cpp @@ -40,15 +40,25 @@ void MessageQueueBindings::bind(pybind11::module& m, void* pCallstack) { // Bind DataOutputQueue auto addCallbackLambda = [](MessageQueue& q, py::function cb) -> int { - pybind11::module inspect_module = pybind11::module::import("inspect"); - pybind11::object result = inspect_module.attr("signature")(cb).attr("parameters"); + pybind11::module inspectModule = pybind11::module::import("inspect"); + pybind11::object result = inspectModule.attr("signature")(cb).attr("parameters"); auto numParams = pybind11::len(result); - if(numParams == 2) { - return q.addCallback(cb.cast)>>()); - } else if(numParams == 1) { - return q.addCallback(cb.cast)>>()); - } else if(numParams == 0) { - return q.addCallback(cb.cast>()); + + if (numParams == 2) { + return q.addCallback([cb](std::string msg, std::shared_ptr data) { + pybind11::gil_scoped_acquire gil; + cb(msg, data); + }); + } else if (numParams == 1) { + return q.addCallback([cb](std::shared_ptr data) { + pybind11::gil_scoped_acquire gil; + cb(data); + }); + } else if (numParams == 0) { + return q.addCallback([cb]() { + pybind11::gil_scoped_acquire gil; + cb(); + }); } else { throw py::value_error("Callback must take either zero, one or two arguments"); }