74#ifndef snicholls_core_adapters_nanobind_gil_hpp
75#define snicholls_core_adapters_nanobind_gil_hpp
77#include <nanobind/nanobind.h>
83static_assert(NB_VERSION_MAJOR >= 3,
"snicholls::python: the nanobind helpers need nanobind 3 or newer");
85namespace snicholls::python {
92using release_gil = ::nanobind::call_guard<::nanobind::gil_scoped_release>;
104 ::nanobind::gil_scoped_release released;
105 return std::invoke(std::forward<F>(f));
117 ::nanobind::gil_scoped_acquire acquired;
118 return std::invoke(std::forward<F>(f));
124template <
class Signature>
131template <
class R,
class... A>
154 with_gil([&] { f_ = std::move(o.f_); });
172 ::nanobind::object out = f_(std::forward<A>(a)...);
173 if constexpr (!std::is_void_v<R>) {
174 std::remove_cvref_t<R> value{};
175 if (!::nanobind::try_cast(out, value))
176 throw ::nanobind::type_error(
"snicholls::python::python_function: the callable's result does not "
177 "convert to the declared result type");
184 [[nodiscard]] const ::nanobind::object&
object() const noexcept {
return f_; }
187 ::nanobind::object f_;
python_function(const python_function &o)
Copies, taking the GIL.
python_function & operator=(const python_function &o)
Copy-assigns, taking the GIL.
R operator()(A... a) const
Calls the Python callable with the GIL held.
const ::nanobind::object & object() const noexcept
The callable.
python_function & operator=(python_function &&o) noexcept
Move-assigns, taking the GIL to drop the old reference.
~python_function()
Drops the reference, taking the GIL.
python_function(::nanobind::object f) noexcept
Wraps f.
python_function(python_function &&o) noexcept=default
Moves (no reference count changes, no GIL needed).
A Python callable as a C++ callable of a fixed signature, safe to copy, call and destroy on any threa...
decltype(auto) with_gil(F &&f)
Runs f() holding the GIL (taking it if this thread does not hold it) and returns its result.
::nanobind::call_guard<::nanobind::gil_scoped_release > release_gil
nanobind's call guard that releases the GIL for the duration of a bound call.
decltype(auto) without_gil(F &&f)
Runs f() with the GIL released and returns its result.