Skip to content

Commit

Permalink
stash nanobind data structures in interpreter state dictionary
Browse files Browse the repository at this point in the history
Previously, nanobind stored its internal data structures in the
``builtins`` dictionary, which was rightfully criticised in issue #96.
This tentative commit instead uses the interpreter state dictionary
exposed via ``PyInterpreterState_GetDict()``.
  • Loading branch information
wjakob committed Oct 27, 2022
1 parent f64d2b9 commit ca23da7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
6 changes: 6 additions & 0 deletions include/nanobind/nb_defs.h
Expand Up @@ -84,6 +84,12 @@
# define NB_VECTORCALL_NARGS(n) ((n) & ~NB_VECTORCALL_ARGUMENTS_OFFSET)
#endif

#if PY_VERSION_HEX < 0x03090000
# define NB_INTERPRETER_STATE_GET _PyInterpreterState_Get
#else
# define NB_INTERPRETER_STATE_GET PyInterpreterState_Get
#endif

#if defined(Py_LIMITED_API)
# if PY_VERSION_HEX < 0x030C0000
# error "nanobind can target Python's limited API, but this requires CPython >= 3.12"
Expand Down
15 changes: 11 additions & 4 deletions src/nb_internals.cpp
Expand Up @@ -374,9 +374,13 @@ static void internals_make() {

internals_p = new nb_internals();

PyObject *dict = PyInterpreterState_GetDict(NB_INTERPRETER_STATE_GET());
if (!dict)
fail("nanobind::detail::internals_make(): PyInterpreterState_GetDict() failed!");

PyObject *capsule = PyCapsule_New(internals_p, nullptr, nullptr);
PyObject *nb_module = PyModule_NewObject(nb_name.ptr());
int rv = PyDict_SetItemString(PyEval_GetBuiltins(), NB_INTERNALS_ID, capsule);
int rv = PyDict_SetItemString(dict, NB_INTERNALS_ID, capsule);
if (rv || !capsule || !nb_module)
fail("nanobind::detail::internals_make(): allocation failed!");
Py_DECREF(capsule);
Expand Down Expand Up @@ -480,13 +484,16 @@ static void internals_make() {
}

static void internals_fetch() {
PyObject *capsule =
PyDict_GetItemString(PyEval_GetBuiltins(), NB_INTERNALS_ID);
PyObject *dict = PyInterpreterState_GetDict(NB_INTERPRETER_STATE_GET());
if (!dict)
fail("nanobind::detail::internals_fetch(): PyInterpreterState_GetDict() failed!");

PyObject *capsule = PyDict_GetItemString(dict, NB_INTERNALS_ID);

if (capsule) {
internals_p = (nb_internals *) PyCapsule_GetPointer(capsule, nullptr);
if (!internals_p)
fail("nanobind::detail::internals_fetch(): internal error!");
fail("nanobind::detail::internals_fetch(): capsule pointer is NULL!");
return;
}

Expand Down

0 comments on commit ca23da7

Please sign in to comment.