RDKit
Open-source cheminformatics and machine learning.
Toggle main menu visibility
Loading...
Searching...
No Matches
python_capsule_nb.h
Go to the documentation of this file.
1
//
2
// Copyright (C) 2026 Greg Landrum and other RDKit contributors
3
//
4
// @@ All Rights Reserved @@
5
// This file is part of the RDKit.
6
// The contents are covered by the terms of the BSD license
7
// which is included in the file license.txt, found at the root
8
// of the RDKit source tree.
9
//
10
// The idea of inserting a capsule into the builtins dictionary
11
// was taken from nanobind, as well as the mechanism to capture
12
// the builtins dict object.
13
//
14
#pragma once
15
16
#include <Python.h>
17
18
#include <nanobind/nanobind.h>
19
20
namespace
nb = nanobind;
21
22
inline
nb::dict
getBuiltinsDict
() {
23
// PyEval_GetBuiltins only gets the builtins for the current thread,
24
// which may not be the main thread.
25
#if defined(PYPY_VERSION)
26
PyObject *dict = PyEval_GetBuiltins();
27
#else
28
PyObject *dict = PyInterpreterState_GetDict(PyInterpreterState_Get());
29
#endif
30
if
(!dict) {
31
throw
std::runtime_error(
"Failed to get Python builtins dictionary"
);
32
}
33
34
return
nb::borrow<nb::dict>(dict);
35
}
36
37
inline
void
installCapsule
(nb::capsule capsule,
const
char
*name) {
38
nb::dict builtins =
getBuiltinsDict
();
39
builtins[name] = capsule;
40
}
41
42
inline
void
*
getCapsulePtr
(
const
char
*name) {
43
nb::dict builtins =
getBuiltinsDict
();
44
if
(!builtins.contains(name)) {
45
return
nullptr
;
46
}
47
48
auto
capsule = nb::borrow<nb::capsule>(builtins[name]);
49
if
(!capsule) {
50
throw
std::runtime_error(std::string(
"Capsule "
) + name +
51
" exists, but we could not retrieve it."
);
52
}
53
return
capsule.data();
54
}
installCapsule
void installCapsule(nb::capsule capsule, const char *name)
Definition
python_capsule_nb.h:37
getCapsulePtr
void * getCapsulePtr(const char *name)
Definition
python_capsule_nb.h:42
getBuiltinsDict
nb::dict getBuiltinsDict()
Definition
python_capsule_nb.h:22
RDBoost
python_capsule_nb.h
Generated on
for RDKit by
1.17.0