From 3cc2fa9adaf16d3d655d4240d363f2cab2f16671 Mon Sep 17 00:00:00 2001 From: Michael Simacek Date: Thu, 3 Oct 2024 15:17:23 +0200 Subject: [PATCH] Factor out setting function docstrings into a macro --- include/pybind11/detail/common.h | 14 ++++++++++++++ include/pybind11/pybind11.h | 13 +++---------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/include/pybind11/detail/common.h b/include/pybind11/detail/common.h index e1d675535b..fa47199221 100644 --- a/include/pybind11/detail/common.h +++ b/include/pybind11/detail/common.h @@ -387,6 +387,20 @@ PYBIND11_WARNING_POP #define PYBIND11_CONCAT(first, second) first##second #define PYBIND11_ENSURE_INTERNALS_READY pybind11::detail::get_internals(); +#if !defined(GRAALVM_PYTHON) +# define PYBIND11_PYCFUNCTION_GET_DOC(func) ((func)->m_ml->ml_doc) +# define PYBIND11_PYCFUNCTION_SET_DOC(func, doc) \ + do { \ + (func)->m_ml->ml_doc = (doc); \ + } while (0) +#else +# define PYBIND11_PYCFUNCTION_GET_DOC(func) (GraalPyCFunction_GetDoc((PyObject *) (func))) +# define PYBIND11_PYCFUNCTION_SET_DOC(func, doc) \ + do { \ + GraalPyCFunction_SetDoc((PyObject *) (func), (doc)); \ + } while (0) +#endif + #define PYBIND11_CHECK_PYTHON_VERSION \ { \ const char *compiled_ver \ diff --git a/include/pybind11/pybind11.h b/include/pybind11/pybind11.h index 411ba22b62..2527d25faf 100644 --- a/include/pybind11/pybind11.h +++ b/include/pybind11/pybind11.h @@ -633,18 +633,11 @@ class cpp_function : public function { } } - /* Install docstring */ auto *func = (PyCFunctionObject *) m_ptr; -#if !defined(GRAALVM_PYTHON) - std::free(const_cast(func->m_ml->ml_doc)); // Install docstring if it's non-empty (when at least one option is enabled) - func->m_ml->ml_doc - = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str()); -#else - std::free(const_cast(GraalPyCFunction_GetDoc(m_ptr))); - GraalPyCFunction_SetDoc( - m_ptr, signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str())); -#endif + auto *doc = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str()); + std::free(const_cast(PYBIND11_PYCFUNCTION_GET_DOC(func))); + PYBIND11_PYCFUNCTION_SET_DOC(func, doc); if (rec->is_method) { m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());