Techt3o commited on
Commit
58527da
·
verified ·
1 Parent(s): 2a81102

9fa4f7f5acf17ea4cc4e1f2f846e3dd97ae86778bb17d4836851b112fc253051

Browse files
Files changed (50) hide show
  1. third-party/DPVO/DPRetrieval/pybind11/docs/Doxyfile +22 -0
  2. third-party/DPVO/DPRetrieval/pybind11/docs/advanced/pycpp/utilities.rst +155 -0
  3. third-party/DPVO/DPRetrieval/pybind11/docs/advanced/smart_ptrs.rst +174 -0
  4. third-party/DPVO/DPRetrieval/pybind11/docs/basics.rst +308 -0
  5. third-party/DPVO/DPRetrieval/pybind11/docs/benchmark.py +91 -0
  6. third-party/DPVO/DPRetrieval/pybind11/docs/benchmark.rst +95 -0
  7. third-party/DPVO/DPRetrieval/pybind11/docs/changelog.rst +0 -0
  8. third-party/DPVO/DPRetrieval/pybind11/docs/classes.rst +542 -0
  9. third-party/DPVO/DPRetrieval/pybind11/docs/cmake/index.rst +8 -0
  10. third-party/DPVO/DPRetrieval/pybind11/docs/compiling.rst +648 -0
  11. third-party/DPVO/DPRetrieval/pybind11/docs/conf.py +381 -0
  12. third-party/DPVO/DPRetrieval/pybind11/docs/faq.rst +343 -0
  13. third-party/DPVO/DPRetrieval/pybind11/docs/index.rst +48 -0
  14. third-party/DPVO/DPRetrieval/pybind11/docs/installing.rst +105 -0
  15. third-party/DPVO/DPRetrieval/pybind11/docs/limitations.rst +72 -0
  16. third-party/DPVO/DPRetrieval/pybind11/docs/pybind11-logo.png +0 -0
  17. third-party/DPVO/DPRetrieval/pybind11/docs/pybind11_vs_boost_python1.png +0 -0
  18. third-party/DPVO/DPRetrieval/pybind11/docs/pybind11_vs_boost_python1.svg +427 -0
  19. third-party/DPVO/DPRetrieval/pybind11/docs/pybind11_vs_boost_python2.png +0 -0
  20. third-party/DPVO/DPRetrieval/pybind11/docs/pybind11_vs_boost_python2.svg +427 -0
  21. third-party/DPVO/DPRetrieval/pybind11/docs/reference.rst +130 -0
  22. third-party/DPVO/DPRetrieval/pybind11/docs/release.rst +97 -0
  23. third-party/DPVO/DPRetrieval/pybind11/docs/requirements.txt +5 -0
  24. third-party/DPVO/DPRetrieval/pybind11/docs/upgrade.rst +552 -0
  25. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/attr.h +675 -0
  26. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/buffer_info.h +193 -0
  27. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/cast.h +1663 -0
  28. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/chrono.h +236 -0
  29. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/common.h +2 -0
  30. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/complex.h +74 -0
  31. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/class.h +748 -0
  32. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/common.h +1210 -0
  33. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/descr.h +158 -0
  34. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/init.h +428 -0
  35. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/internals.h +572 -0
  36. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/type_caster_base.h +1083 -0
  37. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/typeid.h +59 -0
  38. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/eigen.h +699 -0
  39. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/embed.h +302 -0
  40. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/eval.h +178 -0
  41. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/functional.h +131 -0
  42. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/gil.h +202 -0
  43. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/iostream.h +265 -0
  44. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/numpy.h +1958 -0
  45. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/operators.h +220 -0
  46. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/options.h +76 -0
  47. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/pybind11.h +0 -0
  48. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/pytypes.h +2153 -0
  49. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/stl.h +422 -0
  50. third-party/DPVO/DPRetrieval/pybind11/include/pybind11/stl/filesystem.h +103 -0
third-party/DPVO/DPRetrieval/pybind11/docs/Doxyfile ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PROJECT_NAME = pybind11
2
+ INPUT = ../include/pybind11/
3
+ RECURSIVE = YES
4
+
5
+ GENERATE_HTML = NO
6
+ GENERATE_LATEX = NO
7
+ GENERATE_XML = YES
8
+ XML_OUTPUT = .build/doxygenxml
9
+ XML_PROGRAMLISTING = YES
10
+
11
+ MACRO_EXPANSION = YES
12
+ EXPAND_ONLY_PREDEF = YES
13
+ EXPAND_AS_DEFINED = PYBIND11_RUNTIME_EXCEPTION
14
+
15
+ ALIASES = "rst=\verbatim embed:rst"
16
+ ALIASES += "endrst=\endverbatim"
17
+
18
+ QUIET = YES
19
+ WARNINGS = YES
20
+ WARN_IF_UNDOCUMENTED = NO
21
+ PREDEFINED = PY_MAJOR_VERSION=3 \
22
+ PYBIND11_NOINLINE
third-party/DPVO/DPRetrieval/pybind11/docs/advanced/pycpp/utilities.rst ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Utilities
2
+ #########
3
+
4
+ Using Python's print function in C++
5
+ ====================================
6
+
7
+ The usual way to write output in C++ is using ``std::cout`` while in Python one
8
+ would use ``print``. Since these methods use different buffers, mixing them can
9
+ lead to output order issues. To resolve this, pybind11 modules can use the
10
+ :func:`py::print` function which writes to Python's ``sys.stdout`` for consistency.
11
+
12
+ Python's ``print`` function is replicated in the C++ API including optional
13
+ keyword arguments ``sep``, ``end``, ``file``, ``flush``. Everything works as
14
+ expected in Python:
15
+
16
+ .. code-block:: cpp
17
+
18
+ py::print(1, 2.0, "three"); // 1 2.0 three
19
+ py::print(1, 2.0, "three", "sep"_a="-"); // 1-2.0-three
20
+
21
+ auto args = py::make_tuple("unpacked", true);
22
+ py::print("->", *args, "end"_a="<-"); // -> unpacked True <-
23
+
24
+ .. _ostream_redirect:
25
+
26
+ Capturing standard output from ostream
27
+ ======================================
28
+
29
+ Often, a library will use the streams ``std::cout`` and ``std::cerr`` to print,
30
+ but this does not play well with Python's standard ``sys.stdout`` and ``sys.stderr``
31
+ redirection. Replacing a library's printing with ``py::print <print>`` may not
32
+ be feasible. This can be fixed using a guard around the library function that
33
+ redirects output to the corresponding Python streams:
34
+
35
+ .. code-block:: cpp
36
+
37
+ #include <pybind11/iostream.h>
38
+
39
+ ...
40
+
41
+ // Add a scoped redirect for your noisy code
42
+ m.def("noisy_func", []() {
43
+ py::scoped_ostream_redirect stream(
44
+ std::cout, // std::ostream&
45
+ py::module_::import("sys").attr("stdout") // Python output
46
+ );
47
+ call_noisy_func();
48
+ });
49
+
50
+ .. warning::
51
+
52
+ The implementation in ``pybind11/iostream.h`` is NOT thread safe. Multiple
53
+ threads writing to a redirected ostream concurrently cause data races
54
+ and potentially buffer overflows. Therefore it is currently a requirement
55
+ that all (possibly) concurrent redirected ostream writes are protected by
56
+ a mutex. #HelpAppreciated: Work on iostream.h thread safety. For more
57
+ background see the discussions under
58
+ `PR #2982 <https://github.com/pybind/pybind11/pull/2982>`_ and
59
+ `PR #2995 <https://github.com/pybind/pybind11/pull/2995>`_.
60
+
61
+ This method respects flushes on the output streams and will flush if needed
62
+ when the scoped guard is destroyed. This allows the output to be redirected in
63
+ real time, such as to a Jupyter notebook. The two arguments, the C++ stream and
64
+ the Python output, are optional, and default to standard output if not given. An
65
+ extra type, ``py::scoped_estream_redirect <scoped_estream_redirect>``, is identical
66
+ except for defaulting to ``std::cerr`` and ``sys.stderr``; this can be useful with
67
+ ``py::call_guard``, which allows multiple items, but uses the default constructor:
68
+
69
+ .. code-block:: cpp
70
+
71
+ // Alternative: Call single function using call guard
72
+ m.def("noisy_func", &call_noisy_function,
73
+ py::call_guard<py::scoped_ostream_redirect,
74
+ py::scoped_estream_redirect>());
75
+
76
+ The redirection can also be done in Python with the addition of a context
77
+ manager, using the ``py::add_ostream_redirect() <add_ostream_redirect>`` function:
78
+
79
+ .. code-block:: cpp
80
+
81
+ py::add_ostream_redirect(m, "ostream_redirect");
82
+
83
+ The name in Python defaults to ``ostream_redirect`` if no name is passed. This
84
+ creates the following context manager in Python:
85
+
86
+ .. code-block:: python
87
+
88
+ with ostream_redirect(stdout=True, stderr=True):
89
+ noisy_function()
90
+
91
+ It defaults to redirecting both streams, though you can use the keyword
92
+ arguments to disable one of the streams if needed.
93
+
94
+ .. note::
95
+
96
+ The above methods will not redirect C-level output to file descriptors, such
97
+ as ``fprintf``. For those cases, you'll need to redirect the file
98
+ descriptors either directly in C or with Python's ``os.dup2`` function
99
+ in an operating-system dependent way.
100
+
101
+ .. _eval:
102
+
103
+ Evaluating Python expressions from strings and files
104
+ ====================================================
105
+
106
+ pybind11 provides the ``eval``, ``exec`` and ``eval_file`` functions to evaluate
107
+ Python expressions and statements. The following example illustrates how they
108
+ can be used.
109
+
110
+ .. code-block:: cpp
111
+
112
+ // At beginning of file
113
+ #include <pybind11/eval.h>
114
+
115
+ ...
116
+
117
+ // Evaluate in scope of main module
118
+ py::object scope = py::module_::import("__main__").attr("__dict__");
119
+
120
+ // Evaluate an isolated expression
121
+ int result = py::eval("my_variable + 10", scope).cast<int>();
122
+
123
+ // Evaluate a sequence of statements
124
+ py::exec(
125
+ "print('Hello')\n"
126
+ "print('world!');",
127
+ scope);
128
+
129
+ // Evaluate the statements in an separate Python file on disk
130
+ py::eval_file("script.py", scope);
131
+
132
+ C++11 raw string literals are also supported and quite handy for this purpose.
133
+ The only requirement is that the first statement must be on a new line following
134
+ the raw string delimiter ``R"(``, ensuring all lines have common leading indent:
135
+
136
+ .. code-block:: cpp
137
+
138
+ py::exec(R"(
139
+ x = get_answer()
140
+ if x == 42:
141
+ print('Hello World!')
142
+ else:
143
+ print('Bye!')
144
+ )", scope
145
+ );
146
+
147
+ .. note::
148
+
149
+ `eval` and `eval_file` accept a template parameter that describes how the
150
+ string/file should be interpreted. Possible choices include ``eval_expr``
151
+ (isolated expression), ``eval_single_statement`` (a single statement, return
152
+ value is always ``none``), and ``eval_statements`` (sequence of statements,
153
+ return value is always ``none``). `eval` defaults to ``eval_expr``,
154
+ `eval_file` defaults to ``eval_statements`` and `exec` is just a shortcut
155
+ for ``eval<eval_statements>``.
third-party/DPVO/DPRetrieval/pybind11/docs/advanced/smart_ptrs.rst ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Smart pointers
2
+ ##############
3
+
4
+ std::unique_ptr
5
+ ===============
6
+
7
+ Given a class ``Example`` with Python bindings, it's possible to return
8
+ instances wrapped in C++11 unique pointers, like so
9
+
10
+ .. code-block:: cpp
11
+
12
+ std::unique_ptr<Example> create_example() { return std::unique_ptr<Example>(new Example()); }
13
+
14
+ .. code-block:: cpp
15
+
16
+ m.def("create_example", &create_example);
17
+
18
+ In other words, there is nothing special that needs to be done. While returning
19
+ unique pointers in this way is allowed, it is *illegal* to use them as function
20
+ arguments. For instance, the following function signature cannot be processed
21
+ by pybind11.
22
+
23
+ .. code-block:: cpp
24
+
25
+ void do_something_with_example(std::unique_ptr<Example> ex) { ... }
26
+
27
+ The above signature would imply that Python needs to give up ownership of an
28
+ object that is passed to this function, which is generally not possible (for
29
+ instance, the object might be referenced elsewhere).
30
+
31
+ std::shared_ptr
32
+ ===============
33
+
34
+ The binding generator for classes, :class:`class_`, can be passed a template
35
+ type that denotes a special *holder* type that is used to manage references to
36
+ the object. If no such holder type template argument is given, the default for
37
+ a type named ``Type`` is ``std::unique_ptr<Type>``, which means that the object
38
+ is deallocated when Python's reference count goes to zero.
39
+
40
+ It is possible to switch to other types of reference counting wrappers or smart
41
+ pointers, which is useful in codebases that rely on them. For instance, the
42
+ following snippet causes ``std::shared_ptr`` to be used instead.
43
+
44
+ .. code-block:: cpp
45
+
46
+ py::class_<Example, std::shared_ptr<Example> /* <- holder type */> obj(m, "Example");
47
+
48
+ Note that any particular class can only be associated with a single holder type.
49
+
50
+ One potential stumbling block when using holder types is that they need to be
51
+ applied consistently. Can you guess what's broken about the following binding
52
+ code?
53
+
54
+ .. code-block:: cpp
55
+
56
+ class Child { };
57
+
58
+ class Parent {
59
+ public:
60
+ Parent() : child(std::make_shared<Child>()) { }
61
+ Child *get_child() { return child.get(); } /* Hint: ** DON'T DO THIS ** */
62
+ private:
63
+ std::shared_ptr<Child> child;
64
+ };
65
+
66
+ PYBIND11_MODULE(example, m) {
67
+ py::class_<Child, std::shared_ptr<Child>>(m, "Child");
68
+
69
+ py::class_<Parent, std::shared_ptr<Parent>>(m, "Parent")
70
+ .def(py::init<>())
71
+ .def("get_child", &Parent::get_child);
72
+ }
73
+
74
+ The following Python code will cause undefined behavior (and likely a
75
+ segmentation fault).
76
+
77
+ .. code-block:: python
78
+
79
+ from example import Parent
80
+
81
+ print(Parent().get_child())
82
+
83
+ The problem is that ``Parent::get_child()`` returns a pointer to an instance of
84
+ ``Child``, but the fact that this instance is already managed by
85
+ ``std::shared_ptr<...>`` is lost when passing raw pointers. In this case,
86
+ pybind11 will create a second independent ``std::shared_ptr<...>`` that also
87
+ claims ownership of the pointer. In the end, the object will be freed **twice**
88
+ since these shared pointers have no way of knowing about each other.
89
+
90
+ There are two ways to resolve this issue:
91
+
92
+ 1. For types that are managed by a smart pointer class, never use raw pointers
93
+ in function arguments or return values. In other words: always consistently
94
+ wrap pointers into their designated holder types (such as
95
+ ``std::shared_ptr<...>``). In this case, the signature of ``get_child()``
96
+ should be modified as follows:
97
+
98
+ .. code-block:: cpp
99
+
100
+ std::shared_ptr<Child> get_child() { return child; }
101
+
102
+ 2. Adjust the definition of ``Child`` by specifying
103
+ ``std::enable_shared_from_this<T>`` (see cppreference_ for details) as a
104
+ base class. This adds a small bit of information to ``Child`` that allows
105
+ pybind11 to realize that there is already an existing
106
+ ``std::shared_ptr<...>`` and communicate with it. In this case, the
107
+ declaration of ``Child`` should look as follows:
108
+
109
+ .. _cppreference: http://en.cppreference.com/w/cpp/memory/enable_shared_from_this
110
+
111
+ .. code-block:: cpp
112
+
113
+ class Child : public std::enable_shared_from_this<Child> { };
114
+
115
+ .. _smart_pointers:
116
+
117
+ Custom smart pointers
118
+ =====================
119
+
120
+ pybind11 supports ``std::unique_ptr`` and ``std::shared_ptr`` right out of the
121
+ box. For any other custom smart pointer, transparent conversions can be enabled
122
+ using a macro invocation similar to the following. It must be declared at the
123
+ top namespace level before any binding code:
124
+
125
+ .. code-block:: cpp
126
+
127
+ PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>);
128
+
129
+ The first argument of :func:`PYBIND11_DECLARE_HOLDER_TYPE` should be a
130
+ placeholder name that is used as a template parameter of the second argument.
131
+ Thus, feel free to use any identifier, but use it consistently on both sides;
132
+ also, don't use the name of a type that already exists in your codebase.
133
+
134
+ The macro also accepts a third optional boolean parameter that is set to false
135
+ by default. Specify
136
+
137
+ .. code-block:: cpp
138
+
139
+ PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>, true);
140
+
141
+ if ``SmartPtr<T>`` can always be initialized from a ``T*`` pointer without the
142
+ risk of inconsistencies (such as multiple independent ``SmartPtr`` instances
143
+ believing that they are the sole owner of the ``T*`` pointer). A common
144
+ situation where ``true`` should be passed is when the ``T`` instances use
145
+ *intrusive* reference counting.
146
+
147
+ Please take a look at the :ref:`macro_notes` before using this feature.
148
+
149
+ By default, pybind11 assumes that your custom smart pointer has a standard
150
+ interface, i.e. provides a ``.get()`` member function to access the underlying
151
+ raw pointer. If this is not the case, pybind11's ``holder_helper`` must be
152
+ specialized:
153
+
154
+ .. code-block:: cpp
155
+
156
+ // Always needed for custom holder types
157
+ PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>);
158
+
159
+ // Only needed if the type's `.get()` goes by another name
160
+ namespace pybind11 { namespace detail {
161
+ template <typename T>
162
+ struct holder_helper<SmartPtr<T>> { // <-- specialization
163
+ static const T *get(const SmartPtr<T> &p) { return p.getPointer(); }
164
+ };
165
+ }}
166
+
167
+ The above specialization informs pybind11 that the custom ``SmartPtr`` class
168
+ provides ``.get()`` functionality via ``.getPointer()``.
169
+
170
+ .. seealso::
171
+
172
+ The file :file:`tests/test_smart_ptr.cpp` contains a complete example
173
+ that demonstrates how to work with custom reference-counting holder types
174
+ in more detail.
third-party/DPVO/DPRetrieval/pybind11/docs/basics.rst ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _basics:
2
+
3
+ First steps
4
+ ###########
5
+
6
+ This sections demonstrates the basic features of pybind11. Before getting
7
+ started, make sure that development environment is set up to compile the
8
+ included set of test cases.
9
+
10
+
11
+ Compiling the test cases
12
+ ========================
13
+
14
+ Linux/macOS
15
+ -----------
16
+
17
+ On Linux you'll need to install the **python-dev** or **python3-dev** packages as
18
+ well as **cmake**. On macOS, the included python version works out of the box,
19
+ but **cmake** must still be installed.
20
+
21
+ After installing the prerequisites, run
22
+
23
+ .. code-block:: bash
24
+
25
+ mkdir build
26
+ cd build
27
+ cmake ..
28
+ make check -j 4
29
+
30
+ The last line will both compile and run the tests.
31
+
32
+ Windows
33
+ -------
34
+
35
+ On Windows, only **Visual Studio 2015** and newer are supported since pybind11 relies
36
+ on various C++11 language features that break older versions of Visual Studio.
37
+
38
+ .. Note::
39
+
40
+ To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag
41
+ ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When
42
+ building with Visual Studio 2019, this is not strictly necessary, but still advised.
43
+
44
+ .. _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017
45
+
46
+ To compile and run the tests:
47
+
48
+ .. code-block:: batch
49
+
50
+ mkdir build
51
+ cd build
52
+ cmake ..
53
+ cmake --build . --config Release --target check
54
+
55
+ This will create a Visual Studio project, compile and run the target, all from the
56
+ command line.
57
+
58
+ .. Note::
59
+
60
+ If all tests fail, make sure that the Python binary and the testcases are compiled
61
+ for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
62
+ can specify **x86_64** as the target architecture for the generated Visual Studio
63
+ project using ``cmake -A x64 ..``.
64
+
65
+ .. seealso::
66
+
67
+ Advanced users who are already familiar with Boost.Python may want to skip
68
+ the tutorial and look at the test cases in the :file:`tests` directory,
69
+ which exercise all features of pybind11.
70
+
71
+ Header and namespace conventions
72
+ ================================
73
+
74
+ For brevity, all code examples assume that the following two lines are present:
75
+
76
+ .. code-block:: cpp
77
+
78
+ #include <pybind11/pybind11.h>
79
+
80
+ namespace py = pybind11;
81
+
82
+ Some features may require additional headers, but those will be specified as needed.
83
+
84
+ .. _simple_example:
85
+
86
+ Creating bindings for a simple function
87
+ =======================================
88
+
89
+ Let's start by creating Python bindings for an extremely simple function, which
90
+ adds two numbers and returns their result:
91
+
92
+ .. code-block:: cpp
93
+
94
+ int add(int i, int j) {
95
+ return i + j;
96
+ }
97
+
98
+ For simplicity [#f1]_, we'll put both this function and the binding code into
99
+ a file named :file:`example.cpp` with the following contents:
100
+
101
+ .. code-block:: cpp
102
+
103
+ #include <pybind11/pybind11.h>
104
+
105
+ int add(int i, int j) {
106
+ return i + j;
107
+ }
108
+
109
+ PYBIND11_MODULE(example, m) {
110
+ m.doc() = "pybind11 example plugin"; // optional module docstring
111
+
112
+ m.def("add", &add, "A function that adds two numbers");
113
+ }
114
+
115
+ .. [#f1] In practice, implementation and binding code will generally be located
116
+ in separate files.
117
+
118
+ The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
119
+ ``import`` statement is issued from within Python. The module name (``example``)
120
+ is given as the first macro argument (it should not be in quotes). The second
121
+ argument (``m``) defines a variable of type :class:`py::module_ <module>` which
122
+ is the main interface for creating bindings. The method :func:`module_::def`
123
+ generates binding code that exposes the ``add()`` function to Python.
124
+
125
+ .. note::
126
+
127
+ Notice how little code was needed to expose our function to Python: all
128
+ details regarding the function's parameters and return value were
129
+ automatically inferred using template metaprogramming. This overall
130
+ approach and the used syntax are borrowed from Boost.Python, though the
131
+ underlying implementation is very different.
132
+
133
+ pybind11 is a header-only library, hence it is not necessary to link against
134
+ any special libraries and there are no intermediate (magic) translation steps.
135
+ On Linux, the above example can be compiled using the following command:
136
+
137
+ .. code-block:: bash
138
+
139
+ $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
140
+
141
+ .. note::
142
+
143
+ If you used :ref:`include_as_a_submodule` to get the pybind11 source, then
144
+ use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of
145
+ ``$(python3 -m pybind11 --includes)`` in the above compilation, as
146
+ explained in :ref:`building_manually`.
147
+
148
+ For more details on the required compiler flags on Linux and macOS, see
149
+ :ref:`building_manually`. For complete cross-platform compilation instructions,
150
+ refer to the :ref:`compiling` page.
151
+
152
+ The `python_example`_ and `cmake_example`_ repositories are also a good place
153
+ to start. They are both complete project examples with cross-platform build
154
+ systems. The only difference between the two is that `python_example`_ uses
155
+ Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
156
+ (which may be preferable for existing C++ projects).
157
+
158
+ .. _python_example: https://github.com/pybind/python_example
159
+ .. _cmake_example: https://github.com/pybind/cmake_example
160
+
161
+ Building the above C++ code will produce a binary module file that can be
162
+ imported to Python. Assuming that the compiled module is located in the
163
+ current directory, the following interactive Python session shows how to
164
+ load and execute the example:
165
+
166
+ .. code-block:: pycon
167
+
168
+ $ python
169
+ Python 2.7.10 (default, Aug 22 2015, 20:33:39)
170
+ [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
171
+ Type "help", "copyright", "credits" or "license" for more information.
172
+ >>> import example
173
+ >>> example.add(1, 2)
174
+ 3L
175
+ >>>
176
+
177
+ .. _keyword_args:
178
+
179
+ Keyword arguments
180
+ =================
181
+
182
+ With a simple code modification, it is possible to inform Python about the
183
+ names of the arguments ("i" and "j" in this case).
184
+
185
+ .. code-block:: cpp
186
+
187
+ m.def("add", &add, "A function which adds two numbers",
188
+ py::arg("i"), py::arg("j"));
189
+
190
+ :class:`arg` is one of several special tag classes which can be used to pass
191
+ metadata into :func:`module_::def`. With this modified binding code, we can now
192
+ call the function using keyword arguments, which is a more readable alternative
193
+ particularly for functions taking many parameters:
194
+
195
+ .. code-block:: pycon
196
+
197
+ >>> import example
198
+ >>> example.add(i=1, j=2)
199
+ 3L
200
+
201
+ The keyword names also appear in the function signatures within the documentation.
202
+
203
+ .. code-block:: pycon
204
+
205
+ >>> help(example)
206
+
207
+ ....
208
+
209
+ FUNCTIONS
210
+ add(...)
211
+ Signature : (i: int, j: int) -> int
212
+
213
+ A function which adds two numbers
214
+
215
+ A shorter notation for named arguments is also available:
216
+
217
+ .. code-block:: cpp
218
+
219
+ // regular notation
220
+ m.def("add1", &add, py::arg("i"), py::arg("j"));
221
+ // shorthand
222
+ using namespace pybind11::literals;
223
+ m.def("add2", &add, "i"_a, "j"_a);
224
+
225
+ The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
226
+ Note that the literal operator must first be made visible with the directive
227
+ ``using namespace pybind11::literals``. This does not bring in anything else
228
+ from the ``pybind11`` namespace except for literals.
229
+
230
+ .. _default_args:
231
+
232
+ Default arguments
233
+ =================
234
+
235
+ Suppose now that the function to be bound has default arguments, e.g.:
236
+
237
+ .. code-block:: cpp
238
+
239
+ int add(int i = 1, int j = 2) {
240
+ return i + j;
241
+ }
242
+
243
+ Unfortunately, pybind11 cannot automatically extract these parameters, since they
244
+ are not part of the function's type information. However, they are simple to specify
245
+ using an extension of :class:`arg`:
246
+
247
+ .. code-block:: cpp
248
+
249
+ m.def("add", &add, "A function which adds two numbers",
250
+ py::arg("i") = 1, py::arg("j") = 2);
251
+
252
+ The default values also appear within the documentation.
253
+
254
+ .. code-block:: pycon
255
+
256
+ >>> help(example)
257
+
258
+ ....
259
+
260
+ FUNCTIONS
261
+ add(...)
262
+ Signature : (i: int = 1, j: int = 2) -> int
263
+
264
+ A function which adds two numbers
265
+
266
+ The shorthand notation is also available for default arguments:
267
+
268
+ .. code-block:: cpp
269
+
270
+ // regular notation
271
+ m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
272
+ // shorthand
273
+ m.def("add2", &add, "i"_a=1, "j"_a=2);
274
+
275
+ Exporting variables
276
+ ===================
277
+
278
+ To expose a value from C++, use the ``attr`` function to register it in a
279
+ module as shown below. Built-in types and general objects (more on that later)
280
+ are automatically converted when assigned as attributes, and can be explicitly
281
+ converted using the function ``py::cast``.
282
+
283
+ .. code-block:: cpp
284
+
285
+ PYBIND11_MODULE(example, m) {
286
+ m.attr("the_answer") = 42;
287
+ py::object world = py::cast("World");
288
+ m.attr("what") = world;
289
+ }
290
+
291
+ These are then accessible from Python:
292
+
293
+ .. code-block:: pycon
294
+
295
+ >>> import example
296
+ >>> example.the_answer
297
+ 42
298
+ >>> example.what
299
+ 'World'
300
+
301
+ .. _supported_types:
302
+
303
+ Supported data types
304
+ ====================
305
+
306
+ A large number of data types are supported out of the box and can be used
307
+ seamlessly as functions arguments, return values or with ``py::cast`` in general.
308
+ For a full overview, see the :doc:`advanced/cast/index` section.
third-party/DPVO/DPRetrieval/pybind11/docs/benchmark.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import datetime as dt
3
+ import os
4
+ import random
5
+
6
+ nfns = 4 # Functions per class
7
+ nargs = 4 # Arguments per function
8
+
9
+
10
+ def generate_dummy_code_pybind11(nclasses=10):
11
+ decl = ""
12
+ bindings = ""
13
+
14
+ for cl in range(nclasses):
15
+ decl += "class cl%03i;\n" % cl
16
+ decl += "\n"
17
+
18
+ for cl in range(nclasses):
19
+ decl += "class cl%03i {\n" % cl
20
+ decl += "public:\n"
21
+ bindings += ' py::class_<cl%03i>(m, "cl%03i")\n' % (cl, cl)
22
+ for fn in range(nfns):
23
+ ret = random.randint(0, nclasses - 1)
24
+ params = [random.randint(0, nclasses - 1) for i in range(nargs)]
25
+ decl += " cl%03i *fn_%03i(" % (ret, fn)
26
+ decl += ", ".join("cl%03i *" % p for p in params)
27
+ decl += ");\n"
28
+ bindings += ' .def("fn_%03i", &cl%03i::fn_%03i)\n' % (fn, cl, fn)
29
+ decl += "};\n\n"
30
+ bindings += " ;\n"
31
+
32
+ result = "#include <pybind11/pybind11.h>\n\n"
33
+ result += "namespace py = pybind11;\n\n"
34
+ result += decl + "\n"
35
+ result += "PYBIND11_MODULE(example, m) {\n"
36
+ result += bindings
37
+ result += "}"
38
+ return result
39
+
40
+
41
+ def generate_dummy_code_boost(nclasses=10):
42
+ decl = ""
43
+ bindings = ""
44
+
45
+ for cl in range(nclasses):
46
+ decl += "class cl%03i;\n" % cl
47
+ decl += "\n"
48
+
49
+ for cl in range(nclasses):
50
+ decl += "class cl%03i {\n" % cl
51
+ decl += "public:\n"
52
+ bindings += ' py::class_<cl%03i>("cl%03i")\n' % (cl, cl)
53
+ for fn in range(nfns):
54
+ ret = random.randint(0, nclasses - 1)
55
+ params = [random.randint(0, nclasses - 1) for i in range(nargs)]
56
+ decl += " cl%03i *fn_%03i(" % (ret, fn)
57
+ decl += ", ".join("cl%03i *" % p for p in params)
58
+ decl += ");\n"
59
+ bindings += (
60
+ ' .def("fn_%03i", &cl%03i::fn_%03i, py::return_value_policy<py::manage_new_object>())\n'
61
+ % (fn, cl, fn)
62
+ )
63
+ decl += "};\n\n"
64
+ bindings += " ;\n"
65
+
66
+ result = "#include <boost/python.hpp>\n\n"
67
+ result += "namespace py = boost::python;\n\n"
68
+ result += decl + "\n"
69
+ result += "BOOST_PYTHON_MODULE(example) {\n"
70
+ result += bindings
71
+ result += "}"
72
+ return result
73
+
74
+
75
+ for codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]:
76
+ print("{")
77
+ for i in range(0, 10):
78
+ nclasses = 2 ** i
79
+ with open("test.cpp", "w") as f:
80
+ f.write(codegen(nclasses))
81
+ n1 = dt.datetime.now()
82
+ os.system(
83
+ "g++ -Os -shared -rdynamic -undefined dynamic_lookup "
84
+ "-fvisibility=hidden -std=c++14 test.cpp -I include "
85
+ "-I /System/Library/Frameworks/Python.framework/Headers -o test.so"
86
+ )
87
+ n2 = dt.datetime.now()
88
+ elapsed = (n2 - n1).total_seconds()
89
+ size = os.stat("test.so").st_size
90
+ print(" {%i, %f, %i}," % (nclasses * nfns, elapsed, size))
91
+ print("}")
third-party/DPVO/DPRetrieval/pybind11/docs/benchmark.rst ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Benchmark
2
+ =========
3
+
4
+ The following is the result of a synthetic benchmark comparing both compilation
5
+ time and module size of pybind11 against Boost.Python. A detailed report about a
6
+ Boost.Python to pybind11 conversion of a real project is available here: [#f1]_.
7
+
8
+ .. [#f1] http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf
9
+
10
+ Setup
11
+ -----
12
+
13
+ A python script (see the ``docs/benchmark.py`` file) was used to generate a set
14
+ of files with dummy classes whose count increases for each successive benchmark
15
+ (between 1 and 2048 classes in powers of two). Each class has four methods with
16
+ a randomly generated signature with a return value and four arguments. (There
17
+ was no particular reason for this setup other than the desire to generate many
18
+ unique function signatures whose count could be controlled in a simple way.)
19
+
20
+ Here is an example of the binding code for one class:
21
+
22
+ .. code-block:: cpp
23
+
24
+ ...
25
+ class cl034 {
26
+ public:
27
+ cl279 *fn_000(cl084 *, cl057 *, cl065 *, cl042 *);
28
+ cl025 *fn_001(cl098 *, cl262 *, cl414 *, cl121 *);
29
+ cl085 *fn_002(cl445 *, cl297 *, cl145 *, cl421 *);
30
+ cl470 *fn_003(cl200 *, cl323 *, cl332 *, cl492 *);
31
+ };
32
+ ...
33
+
34
+ PYBIND11_MODULE(example, m) {
35
+ ...
36
+ py::class_<cl034>(m, "cl034")
37
+ .def("fn_000", &cl034::fn_000)
38
+ .def("fn_001", &cl034::fn_001)
39
+ .def("fn_002", &cl034::fn_002)
40
+ .def("fn_003", &cl034::fn_003)
41
+ ...
42
+ }
43
+
44
+ The Boost.Python version looks almost identical except that a return value
45
+ policy had to be specified as an argument to ``def()``. For both libraries,
46
+ compilation was done with
47
+
48
+ .. code-block:: bash
49
+
50
+ Apple LLVM version 7.0.2 (clang-700.1.81)
51
+
52
+ and the following compilation flags
53
+
54
+ .. code-block:: bash
55
+
56
+ g++ -Os -shared -rdynamic -undefined dynamic_lookup -fvisibility=hidden -std=c++14
57
+
58
+ Compilation time
59
+ ----------------
60
+
61
+ The following log-log plot shows how the compilation time grows for an
62
+ increasing number of class and function declarations. pybind11 includes many
63
+ fewer headers, which initially leads to shorter compilation times, but the
64
+ performance is ultimately fairly similar (pybind11 is 19.8 seconds faster for
65
+ the largest largest file with 2048 classes and a total of 8192 methods -- a
66
+ modest **1.2x** speedup relative to Boost.Python, which required 116.35
67
+ seconds).
68
+
69
+ .. only:: not latex
70
+
71
+ .. image:: pybind11_vs_boost_python1.svg
72
+
73
+ .. only:: latex
74
+
75
+ .. image:: pybind11_vs_boost_python1.png
76
+
77
+ Module size
78
+ -----------
79
+
80
+ Differences between the two libraries become much more pronounced when
81
+ considering the file size of the generated Python plugin: for the largest file,
82
+ the binary generated by Boost.Python required 16.8 MiB, which was **2.17
83
+ times** / **9.1 megabytes** larger than the output generated by pybind11. For
84
+ very small inputs, Boost.Python has an edge in the plot below -- however, note
85
+ that it stores many definitions in an external library, whose size was not
86
+ included here, hence the comparison is slightly shifted in Boost.Python's
87
+ favor.
88
+
89
+ .. only:: not latex
90
+
91
+ .. image:: pybind11_vs_boost_python2.svg
92
+
93
+ .. only:: latex
94
+
95
+ .. image:: pybind11_vs_boost_python2.png
third-party/DPVO/DPRetrieval/pybind11/docs/changelog.rst ADDED
The diff for this file is too large to render. See raw diff
 
third-party/DPVO/DPRetrieval/pybind11/docs/classes.rst ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _classes:
2
+
3
+ Object-oriented code
4
+ ####################
5
+
6
+ Creating bindings for a custom type
7
+ ===================================
8
+
9
+ Let's now look at a more complex example where we'll create bindings for a
10
+ custom C++ data structure named ``Pet``. Its definition is given below:
11
+
12
+ .. code-block:: cpp
13
+
14
+ struct Pet {
15
+ Pet(const std::string &name) : name(name) { }
16
+ void setName(const std::string &name_) { name = name_; }
17
+ const std::string &getName() const { return name; }
18
+
19
+ std::string name;
20
+ };
21
+
22
+ The binding code for ``Pet`` looks as follows:
23
+
24
+ .. code-block:: cpp
25
+
26
+ #include <pybind11/pybind11.h>
27
+
28
+ namespace py = pybind11;
29
+
30
+ PYBIND11_MODULE(example, m) {
31
+ py::class_<Pet>(m, "Pet")
32
+ .def(py::init<const std::string &>())
33
+ .def("setName", &Pet::setName)
34
+ .def("getName", &Pet::getName);
35
+ }
36
+
37
+ :class:`class_` creates bindings for a C++ *class* or *struct*-style data
38
+ structure. :func:`init` is a convenience function that takes the types of a
39
+ constructor's parameters as template arguments and wraps the corresponding
40
+ constructor (see the :ref:`custom_constructors` section for details). An
41
+ interactive Python session demonstrating this example is shown below:
42
+
43
+ .. code-block:: pycon
44
+
45
+ % python
46
+ >>> import example
47
+ >>> p = example.Pet("Molly")
48
+ >>> print(p)
49
+ <example.Pet object at 0x10cd98060>
50
+ >>> p.getName()
51
+ u'Molly'
52
+ >>> p.setName("Charly")
53
+ >>> p.getName()
54
+ u'Charly'
55
+
56
+ .. seealso::
57
+
58
+ Static member functions can be bound in the same way using
59
+ :func:`class_::def_static`.
60
+
61
+ Keyword and default arguments
62
+ =============================
63
+ It is possible to specify keyword and default arguments using the syntax
64
+ discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
65
+ and :ref:`default_args` for details.
66
+
67
+ Binding lambda functions
68
+ ========================
69
+
70
+ Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
71
+
72
+ .. code-block:: pycon
73
+
74
+ >>> print(p)
75
+ <example.Pet object at 0x10cd98060>
76
+
77
+ To address this, we could bind a utility function that returns a human-readable
78
+ summary to the special method slot named ``__repr__``. Unfortunately, there is no
79
+ suitable functionality in the ``Pet`` data structure, and it would be nice if
80
+ we did not have to change it. This can easily be accomplished by binding a
81
+ Lambda function instead:
82
+
83
+ .. code-block:: cpp
84
+
85
+ py::class_<Pet>(m, "Pet")
86
+ .def(py::init<const std::string &>())
87
+ .def("setName", &Pet::setName)
88
+ .def("getName", &Pet::getName)
89
+ .def("__repr__",
90
+ [](const Pet &a) {
91
+ return "<example.Pet named '" + a.name + "'>";
92
+ }
93
+ );
94
+
95
+ Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
96
+ With the above change, the same Python code now produces the following output:
97
+
98
+ .. code-block:: pycon
99
+
100
+ >>> print(p)
101
+ <example.Pet named 'Molly'>
102
+
103
+ .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
104
+
105
+ .. _properties:
106
+
107
+ Instance and static fields
108
+ ==========================
109
+
110
+ We can also directly expose the ``name`` field using the
111
+ :func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
112
+ method also exists for ``const`` fields.
113
+
114
+ .. code-block:: cpp
115
+
116
+ py::class_<Pet>(m, "Pet")
117
+ .def(py::init<const std::string &>())
118
+ .def_readwrite("name", &Pet::name)
119
+ // ... remainder ...
120
+
121
+ This makes it possible to write
122
+
123
+ .. code-block:: pycon
124
+
125
+ >>> p = example.Pet("Molly")
126
+ >>> p.name
127
+ u'Molly'
128
+ >>> p.name = "Charly"
129
+ >>> p.name
130
+ u'Charly'
131
+
132
+ Now suppose that ``Pet::name`` was a private internal variable
133
+ that can only be accessed via setters and getters.
134
+
135
+ .. code-block:: cpp
136
+
137
+ class Pet {
138
+ public:
139
+ Pet(const std::string &name) : name(name) { }
140
+ void setName(const std::string &name_) { name = name_; }
141
+ const std::string &getName() const { return name; }
142
+ private:
143
+ std::string name;
144
+ };
145
+
146
+ In this case, the method :func:`class_::def_property`
147
+ (:func:`class_::def_property_readonly` for read-only data) can be used to
148
+ provide a field-like interface within Python that will transparently call
149
+ the setter and getter functions:
150
+
151
+ .. code-block:: cpp
152
+
153
+ py::class_<Pet>(m, "Pet")
154
+ .def(py::init<const std::string &>())
155
+ .def_property("name", &Pet::getName, &Pet::setName)
156
+ // ... remainder ...
157
+
158
+ Write only properties can be defined by passing ``nullptr`` as the
159
+ input for the read function.
160
+
161
+ .. seealso::
162
+
163
+ Similar functions :func:`class_::def_readwrite_static`,
164
+ :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
165
+ and :func:`class_::def_property_readonly_static` are provided for binding
166
+ static variables and properties. Please also see the section on
167
+ :ref:`static_properties` in the advanced part of the documentation.
168
+
169
+ Dynamic attributes
170
+ ==================
171
+
172
+ Native Python classes can pick up new attributes dynamically:
173
+
174
+ .. code-block:: pycon
175
+
176
+ >>> class Pet:
177
+ ... name = "Molly"
178
+ ...
179
+ >>> p = Pet()
180
+ >>> p.name = "Charly" # overwrite existing
181
+ >>> p.age = 2 # dynamically add a new attribute
182
+
183
+ By default, classes exported from C++ do not support this and the only writable
184
+ attributes are the ones explicitly defined using :func:`class_::def_readwrite`
185
+ or :func:`class_::def_property`.
186
+
187
+ .. code-block:: cpp
188
+
189
+ py::class_<Pet>(m, "Pet")
190
+ .def(py::init<>())
191
+ .def_readwrite("name", &Pet::name);
192
+
193
+ Trying to set any other attribute results in an error:
194
+
195
+ .. code-block:: pycon
196
+
197
+ >>> p = example.Pet()
198
+ >>> p.name = "Charly" # OK, attribute defined in C++
199
+ >>> p.age = 2 # fail
200
+ AttributeError: 'Pet' object has no attribute 'age'
201
+
202
+ To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
203
+ must be added to the :class:`py::class_` constructor:
204
+
205
+ .. code-block:: cpp
206
+
207
+ py::class_<Pet>(m, "Pet", py::dynamic_attr())
208
+ .def(py::init<>())
209
+ .def_readwrite("name", &Pet::name);
210
+
211
+ Now everything works as expected:
212
+
213
+ .. code-block:: pycon
214
+
215
+ >>> p = example.Pet()
216
+ >>> p.name = "Charly" # OK, overwrite value in C++
217
+ >>> p.age = 2 # OK, dynamically add a new attribute
218
+ >>> p.__dict__ # just like a native Python class
219
+ {'age': 2}
220
+
221
+ Note that there is a small runtime cost for a class with dynamic attributes.
222
+ Not only because of the addition of a ``__dict__``, but also because of more
223
+ expensive garbage collection tracking which must be activated to resolve
224
+ possible circular references. Native Python classes incur this same cost by
225
+ default, so this is not anything to worry about. By default, pybind11 classes
226
+ are more efficient than native Python classes. Enabling dynamic attributes
227
+ just brings them on par.
228
+
229
+ .. _inheritance:
230
+
231
+ Inheritance and automatic downcasting
232
+ =====================================
233
+
234
+ Suppose now that the example consists of two data structures with an
235
+ inheritance relationship:
236
+
237
+ .. code-block:: cpp
238
+
239
+ struct Pet {
240
+ Pet(const std::string &name) : name(name) { }
241
+ std::string name;
242
+ };
243
+
244
+ struct Dog : Pet {
245
+ Dog(const std::string &name) : Pet(name) { }
246
+ std::string bark() const { return "woof!"; }
247
+ };
248
+
249
+ There are two different ways of indicating a hierarchical relationship to
250
+ pybind11: the first specifies the C++ base class as an extra template
251
+ parameter of the :class:`class_`:
252
+
253
+ .. code-block:: cpp
254
+
255
+ py::class_<Pet>(m, "Pet")
256
+ .def(py::init<const std::string &>())
257
+ .def_readwrite("name", &Pet::name);
258
+
259
+ // Method 1: template parameter:
260
+ py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
261
+ .def(py::init<const std::string &>())
262
+ .def("bark", &Dog::bark);
263
+
264
+ Alternatively, we can also assign a name to the previously bound ``Pet``
265
+ :class:`class_` object and reference it when binding the ``Dog`` class:
266
+
267
+ .. code-block:: cpp
268
+
269
+ py::class_<Pet> pet(m, "Pet");
270
+ pet.def(py::init<const std::string &>())
271
+ .def_readwrite("name", &Pet::name);
272
+
273
+ // Method 2: pass parent class_ object:
274
+ py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
275
+ .def(py::init<const std::string &>())
276
+ .def("bark", &Dog::bark);
277
+
278
+ Functionality-wise, both approaches are equivalent. Afterwards, instances will
279
+ expose fields and methods of both types:
280
+
281
+ .. code-block:: pycon
282
+
283
+ >>> p = example.Dog("Molly")
284
+ >>> p.name
285
+ u'Molly'
286
+ >>> p.bark()
287
+ u'woof!'
288
+
289
+ The C++ classes defined above are regular non-polymorphic types with an
290
+ inheritance relationship. This is reflected in Python:
291
+
292
+ .. code-block:: cpp
293
+
294
+ // Return a base pointer to a derived instance
295
+ m.def("pet_store", []() { return std::unique_ptr<Pet>(new Dog("Molly")); });
296
+
297
+ .. code-block:: pycon
298
+
299
+ >>> p = example.pet_store()
300
+ >>> type(p) # `Dog` instance behind `Pet` pointer
301
+ Pet # no pointer downcasting for regular non-polymorphic types
302
+ >>> p.bark()
303
+ AttributeError: 'Pet' object has no attribute 'bark'
304
+
305
+ The function returned a ``Dog`` instance, but because it's a non-polymorphic
306
+ type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only
307
+ considered polymorphic if it has at least one virtual function and pybind11
308
+ will automatically recognize this:
309
+
310
+ .. code-block:: cpp
311
+
312
+ struct PolymorphicPet {
313
+ virtual ~PolymorphicPet() = default;
314
+ };
315
+
316
+ struct PolymorphicDog : PolymorphicPet {
317
+ std::string bark() const { return "woof!"; }
318
+ };
319
+
320
+ // Same binding code
321
+ py::class_<PolymorphicPet>(m, "PolymorphicPet");
322
+ py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
323
+ .def(py::init<>())
324
+ .def("bark", &PolymorphicDog::bark);
325
+
326
+ // Again, return a base pointer to a derived instance
327
+ m.def("pet_store2", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });
328
+
329
+ .. code-block:: pycon
330
+
331
+ >>> p = example.pet_store2()
332
+ >>> type(p)
333
+ PolymorphicDog # automatically downcast
334
+ >>> p.bark()
335
+ u'woof!'
336
+
337
+ Given a pointer to a polymorphic base, pybind11 performs automatic downcasting
338
+ to the actual derived type. Note that this goes beyond the usual situation in
339
+ C++: we don't just get access to the virtual functions of the base, we get the
340
+ concrete derived type including functions and attributes that the base type may
341
+ not even be aware of.
342
+
343
+ .. seealso::
344
+
345
+ For more information about polymorphic behavior see :ref:`overriding_virtuals`.
346
+
347
+
348
+ Overloaded methods
349
+ ==================
350
+
351
+ Sometimes there are several overloaded C++ methods with the same name taking
352
+ different kinds of input arguments:
353
+
354
+ .. code-block:: cpp
355
+
356
+ struct Pet {
357
+ Pet(const std::string &name, int age) : name(name), age(age) { }
358
+
359
+ void set(int age_) { age = age_; }
360
+ void set(const std::string &name_) { name = name_; }
361
+
362
+ std::string name;
363
+ int age;
364
+ };
365
+
366
+ Attempting to bind ``Pet::set`` will cause an error since the compiler does not
367
+ know which method the user intended to select. We can disambiguate by casting
368
+ them to function pointers. Binding multiple functions to the same Python name
369
+ automatically creates a chain of function overloads that will be tried in
370
+ sequence.
371
+
372
+ .. code-block:: cpp
373
+
374
+ py::class_<Pet>(m, "Pet")
375
+ .def(py::init<const std::string &, int>())
376
+ .def("set", static_cast<void (Pet::*)(int)>(&Pet::set), "Set the pet's age")
377
+ .def("set", static_cast<void (Pet::*)(const std::string &)>(&Pet::set), "Set the pet's name");
378
+
379
+ The overload signatures are also visible in the method's docstring:
380
+
381
+ .. code-block:: pycon
382
+
383
+ >>> help(example.Pet)
384
+
385
+ class Pet(__builtin__.object)
386
+ | Methods defined here:
387
+ |
388
+ | __init__(...)
389
+ | Signature : (Pet, str, int) -> NoneType
390
+ |
391
+ | set(...)
392
+ | 1. Signature : (Pet, int) -> NoneType
393
+ |
394
+ | Set the pet's age
395
+ |
396
+ | 2. Signature : (Pet, str) -> NoneType
397
+ |
398
+ | Set the pet's name
399
+
400
+ If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
401
+ syntax to cast the overloaded function:
402
+
403
+ .. code-block:: cpp
404
+
405
+ py::class_<Pet>(m, "Pet")
406
+ .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
407
+ .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
408
+
409
+ Here, ``py::overload_cast`` only requires the parameter types to be specified.
410
+ The return type and class are deduced. This avoids the additional noise of
411
+ ``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
412
+ on constness, the ``py::const_`` tag should be used:
413
+
414
+ .. code-block:: cpp
415
+
416
+ struct Widget {
417
+ int foo(int x, float y);
418
+ int foo(int x, float y) const;
419
+ };
420
+
421
+ py::class_<Widget>(m, "Widget")
422
+ .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
423
+ .def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
424
+
425
+ If you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only,
426
+ you can use ``py::detail::overload_cast_impl`` with an additional set of parentheses:
427
+
428
+ .. code-block:: cpp
429
+
430
+ template <typename... Args>
431
+ using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;
432
+
433
+ py::class_<Pet>(m, "Pet")
434
+ .def("set", overload_cast_<int>()(&Pet::set), "Set the pet's age")
435
+ .def("set", overload_cast_<const std::string &>()(&Pet::set), "Set the pet's name");
436
+
437
+ .. [#cpp14] A compiler which supports the ``-std=c++14`` flag
438
+ or Visual Studio 2015 Update 2 and newer.
439
+
440
+ .. note::
441
+
442
+ To define multiple overloaded constructors, simply declare one after the
443
+ other using the ``.def(py::init<...>())`` syntax. The existing machinery
444
+ for specifying keyword and default arguments also works.
445
+
446
+ Enumerations and internal types
447
+ ===============================
448
+
449
+ Let's now suppose that the example class contains internal types like enumerations, e.g.:
450
+
451
+ .. code-block:: cpp
452
+
453
+ struct Pet {
454
+ enum Kind {
455
+ Dog = 0,
456
+ Cat
457
+ };
458
+
459
+ struct Attributes {
460
+ float age = 0;
461
+ };
462
+
463
+ Pet(const std::string &name, Kind type) : name(name), type(type) { }
464
+
465
+ std::string name;
466
+ Kind type;
467
+ Attributes attr;
468
+ };
469
+
470
+ The binding code for this example looks as follows:
471
+
472
+ .. code-block:: cpp
473
+
474
+ py::class_<Pet> pet(m, "Pet");
475
+
476
+ pet.def(py::init<const std::string &, Pet::Kind>())
477
+ .def_readwrite("name", &Pet::name)
478
+ .def_readwrite("type", &Pet::type)
479
+ .def_readwrite("attr", &Pet::attr);
480
+
481
+ py::enum_<Pet::Kind>(pet, "Kind")
482
+ .value("Dog", Pet::Kind::Dog)
483
+ .value("Cat", Pet::Kind::Cat)
484
+ .export_values();
485
+
486
+ py::class_<Pet::Attributes> attributes(pet, "Attributes")
487
+ .def(py::init<>())
488
+ .def_readwrite("age", &Pet::Attributes::age);
489
+
490
+
491
+ To ensure that the nested types ``Kind`` and ``Attributes`` are created within the scope of ``Pet``, the
492
+ ``pet`` :class:`class_` instance must be supplied to the :class:`enum_` and :class:`class_`
493
+ constructor. The :func:`enum_::export_values` function exports the enum entries
494
+ into the parent scope, which should be skipped for newer C++11-style strongly
495
+ typed enums.
496
+
497
+ .. code-block:: pycon
498
+
499
+ >>> p = Pet("Lucy", Pet.Cat)
500
+ >>> p.type
501
+ Kind.Cat
502
+ >>> int(p.type)
503
+ 1L
504
+
505
+ The entries defined by the enumeration type are exposed in the ``__members__`` property:
506
+
507
+ .. code-block:: pycon
508
+
509
+ >>> Pet.Kind.__members__
510
+ {'Dog': Kind.Dog, 'Cat': Kind.Cat}
511
+
512
+ The ``name`` property returns the name of the enum value as a unicode string.
513
+
514
+ .. note::
515
+
516
+ It is also possible to use ``str(enum)``, however these accomplish different
517
+ goals. The following shows how these two approaches differ.
518
+
519
+ .. code-block:: pycon
520
+
521
+ >>> p = Pet("Lucy", Pet.Cat)
522
+ >>> pet_type = p.type
523
+ >>> pet_type
524
+ Pet.Cat
525
+ >>> str(pet_type)
526
+ 'Pet.Cat'
527
+ >>> pet_type.name
528
+ 'Cat'
529
+
530
+ .. note::
531
+
532
+ When the special tag ``py::arithmetic()`` is specified to the ``enum_``
533
+ constructor, pybind11 creates an enumeration that also supports rudimentary
534
+ arithmetic and bit-level operations like comparisons, and, or, xor, negation,
535
+ etc.
536
+
537
+ .. code-block:: cpp
538
+
539
+ py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
540
+ ...
541
+
542
+ By default, these are omitted to conserve space.
third-party/DPVO/DPRetrieval/pybind11/docs/cmake/index.rst ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ CMake helpers
2
+ -------------
3
+
4
+ Pybind11 can be used with ``add_subdirectory(extern/pybind11)``, or from an
5
+ install with ``find_package(pybind11 CONFIG)``. The interface provided in
6
+ either case is functionally identical.
7
+
8
+ .. cmake-module:: ../../tools/pybind11Config.cmake.in
third-party/DPVO/DPRetrieval/pybind11/docs/compiling.rst ADDED
@@ -0,0 +1,648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _compiling:
2
+
3
+ Build systems
4
+ #############
5
+
6
+ .. _build-setuptools:
7
+
8
+ Building with setuptools
9
+ ========================
10
+
11
+ For projects on PyPI, building with setuptools is the way to go. Sylvain Corlay
12
+ has kindly provided an example project which shows how to set up everything,
13
+ including automatic generation of documentation using Sphinx. Please refer to
14
+ the [python_example]_ repository.
15
+
16
+ .. [python_example] https://github.com/pybind/python_example
17
+
18
+ A helper file is provided with pybind11 that can simplify usage with setuptools.
19
+
20
+ To use pybind11 inside your ``setup.py``, you have to have some system to
21
+ ensure that ``pybind11`` is installed when you build your package. There are
22
+ four possible ways to do this, and pybind11 supports all four: You can ask all
23
+ users to install pybind11 beforehand (bad), you can use
24
+ :ref:`setup_helpers-pep518` (good, but very new and requires Pip 10),
25
+ :ref:`setup_helpers-setup_requires` (discouraged by Python packagers now that
26
+ PEP 518 is available, but it still works everywhere), or you can
27
+ :ref:`setup_helpers-copy-manually` (always works but you have to manually sync
28
+ your copy to get updates).
29
+
30
+ An example of a ``setup.py`` using pybind11's helpers:
31
+
32
+ .. code-block:: python
33
+
34
+ from glob import glob
35
+ from setuptools import setup
36
+ from pybind11.setup_helpers import Pybind11Extension
37
+
38
+ ext_modules = [
39
+ Pybind11Extension(
40
+ "python_example",
41
+ sorted(glob("src/*.cpp")), # Sort source files for reproducibility
42
+ ),
43
+ ]
44
+
45
+ setup(..., ext_modules=ext_modules)
46
+
47
+ If you want to do an automatic search for the highest supported C++ standard,
48
+ that is supported via a ``build_ext`` command override; it will only affect
49
+ ``Pybind11Extensions``:
50
+
51
+ .. code-block:: python
52
+
53
+ from glob import glob
54
+ from setuptools import setup
55
+ from pybind11.setup_helpers import Pybind11Extension, build_ext
56
+
57
+ ext_modules = [
58
+ Pybind11Extension(
59
+ "python_example",
60
+ sorted(glob("src/*.cpp")),
61
+ ),
62
+ ]
63
+
64
+ setup(..., cmdclass={"build_ext": build_ext}, ext_modules=ext_modules)
65
+
66
+ If you have single-file extension modules that are directly stored in the
67
+ Python source tree (``foo.cpp`` in the same directory as where a ``foo.py``
68
+ would be located), you can also generate ``Pybind11Extensions`` using
69
+ ``setup_helpers.intree_extensions``: ``intree_extensions(["path/to/foo.cpp",
70
+ ...])`` returns a list of ``Pybind11Extensions`` which can be passed to
71
+ ``ext_modules``, possibly after further customizing their attributes
72
+ (``libraries``, ``include_dirs``, etc.). By doing so, a ``foo.*.so`` extension
73
+ module will be generated and made available upon installation.
74
+
75
+ ``intree_extension`` will automatically detect if you are using a ``src``-style
76
+ layout (as long as no namespace packages are involved), but you can also
77
+ explicitly pass ``package_dir`` to it (as in ``setuptools.setup``).
78
+
79
+ Since pybind11 does not require NumPy when building, a light-weight replacement
80
+ for NumPy's parallel compilation distutils tool is included. Use it like this:
81
+
82
+ .. code-block:: python
83
+
84
+ from pybind11.setup_helpers import ParallelCompile
85
+
86
+ # Optional multithreaded build
87
+ ParallelCompile("NPY_NUM_BUILD_JOBS").install()
88
+
89
+ setup(...)
90
+
91
+ The argument is the name of an environment variable to control the number of
92
+ threads, such as ``NPY_NUM_BUILD_JOBS`` (as used by NumPy), though you can set
93
+ something different if you want; ``CMAKE_BUILD_PARALLEL_LEVEL`` is another choice
94
+ a user might expect. You can also pass ``default=N`` to set the default number
95
+ of threads (0 will take the number of threads available) and ``max=N``, the
96
+ maximum number of threads; if you have a large extension you may want set this
97
+ to a memory dependent number.
98
+
99
+ If you are developing rapidly and have a lot of C++ files, you may want to
100
+ avoid rebuilding files that have not changed. For simple cases were you are
101
+ using ``pip install -e .`` and do not have local headers, you can skip the
102
+ rebuild if an object file is newer than its source (headers are not checked!)
103
+ with the following:
104
+
105
+ .. code-block:: python
106
+
107
+ from pybind11.setup_helpers import ParallelCompile, naive_recompile
108
+
109
+ ParallelCompile("NPY_NUM_BUILD_JOBS", needs_recompile=naive_recompile).install()
110
+
111
+
112
+ If you have a more complex build, you can implement a smarter function and pass
113
+ it to ``needs_recompile``, or you can use [Ccache]_ instead. ``CXX="cache g++"
114
+ pip install -e .`` would be the way to use it with GCC, for example. Unlike the
115
+ simple solution, this even works even when not compiling in editable mode, but
116
+ it does require Ccache to be installed.
117
+
118
+ Keep in mind that Pip will not even attempt to rebuild if it thinks it has
119
+ already built a copy of your code, which it deduces from the version number.
120
+ One way to avoid this is to use [setuptools_scm]_, which will generate a
121
+ version number that includes the number of commits since your last tag and a
122
+ hash for a dirty directory. Another way to force a rebuild is purge your cache
123
+ or use Pip's ``--no-cache-dir`` option.
124
+
125
+ .. [Ccache] https://ccache.dev
126
+
127
+ .. [setuptools_scm] https://github.com/pypa/setuptools_scm
128
+
129
+ .. _setup_helpers-pep518:
130
+
131
+ PEP 518 requirements (Pip 10+ required)
132
+ ---------------------------------------
133
+
134
+ If you use `PEP 518's <https://www.python.org/dev/peps/pep-0518/>`_
135
+ ``pyproject.toml`` file, you can ensure that ``pybind11`` is available during
136
+ the compilation of your project. When this file exists, Pip will make a new
137
+ virtual environment, download just the packages listed here in ``requires=``,
138
+ and build a wheel (binary Python package). It will then throw away the
139
+ environment, and install your wheel.
140
+
141
+ Your ``pyproject.toml`` file will likely look something like this:
142
+
143
+ .. code-block:: toml
144
+
145
+ [build-system]
146
+ requires = ["setuptools>=42", "wheel", "pybind11~=2.6.1"]
147
+ build-backend = "setuptools.build_meta"
148
+
149
+ .. note::
150
+
151
+ The main drawback to this method is that a `PEP 517`_ compliant build tool,
152
+ such as Pip 10+, is required for this approach to work; older versions of
153
+ Pip completely ignore this file. If you distribute binaries (called wheels
154
+ in Python) using something like `cibuildwheel`_, remember that ``setup.py``
155
+ and ``pyproject.toml`` are not even contained in the wheel, so this high
156
+ Pip requirement is only for source builds, and will not affect users of
157
+ your binary wheels. If you are building SDists and wheels, then
158
+ `pypa-build`_ is the recommended official tool.
159
+
160
+ .. _PEP 517: https://www.python.org/dev/peps/pep-0517/
161
+ .. _cibuildwheel: https://cibuildwheel.readthedocs.io
162
+ .. _pypa-build: https://pypa-build.readthedocs.io/en/latest/
163
+
164
+ .. _setup_helpers-setup_requires:
165
+
166
+ Classic ``setup_requires``
167
+ --------------------------
168
+
169
+ If you want to support old versions of Pip with the classic
170
+ ``setup_requires=["pybind11"]`` keyword argument to setup, which triggers a
171
+ two-phase ``setup.py`` run, then you will need to use something like this to
172
+ ensure the first pass works (which has not yet installed the ``setup_requires``
173
+ packages, since it can't install something it does not know about):
174
+
175
+ .. code-block:: python
176
+
177
+ try:
178
+ from pybind11.setup_helpers import Pybind11Extension
179
+ except ImportError:
180
+ from setuptools import Extension as Pybind11Extension
181
+
182
+
183
+ It doesn't matter that the Extension class is not the enhanced subclass for the
184
+ first pass run; and the second pass will have the ``setup_requires``
185
+ requirements.
186
+
187
+ This is obviously more of a hack than the PEP 518 method, but it supports
188
+ ancient versions of Pip.
189
+
190
+ .. _setup_helpers-copy-manually:
191
+
192
+ Copy manually
193
+ -------------
194
+
195
+ You can also copy ``setup_helpers.py`` directly to your project; it was
196
+ designed to be usable standalone, like the old example ``setup.py``. You can
197
+ set ``include_pybind11=False`` to skip including the pybind11 package headers,
198
+ so you can use it with git submodules and a specific git version. If you use
199
+ this, you will need to import from a local file in ``setup.py`` and ensure the
200
+ helper file is part of your MANIFEST.
201
+
202
+
203
+ Closely related, if you include pybind11 as a subproject, you can run the
204
+ ``setup_helpers.py`` inplace. If loaded correctly, this should even pick up
205
+ the correct include for pybind11, though you can turn it off as shown above if
206
+ you want to input it manually.
207
+
208
+ Suggested usage if you have pybind11 as a submodule in ``extern/pybind11``:
209
+
210
+ .. code-block:: python
211
+
212
+ DIR = os.path.abspath(os.path.dirname(__file__))
213
+
214
+ sys.path.append(os.path.join(DIR, "extern", "pybind11"))
215
+ from pybind11.setup_helpers import Pybind11Extension # noqa: E402
216
+
217
+ del sys.path[-1]
218
+
219
+
220
+ .. versionchanged:: 2.6
221
+
222
+ Added ``setup_helpers`` file.
223
+
224
+ Building with cppimport
225
+ ========================
226
+
227
+ [cppimport]_ is a small Python import hook that determines whether there is a C++
228
+ source file whose name matches the requested module. If there is, the file is
229
+ compiled as a Python extension using pybind11 and placed in the same folder as
230
+ the C++ source file. Python is then able to find the module and load it.
231
+
232
+ .. [cppimport] https://github.com/tbenthompson/cppimport
233
+
234
+ .. _cmake:
235
+
236
+ Building with CMake
237
+ ===================
238
+
239
+ For C++ codebases that have an existing CMake-based build system, a Python
240
+ extension module can be created with just a few lines of code:
241
+
242
+ .. code-block:: cmake
243
+
244
+ cmake_minimum_required(VERSION 3.4...3.18)
245
+ project(example LANGUAGES CXX)
246
+
247
+ add_subdirectory(pybind11)
248
+ pybind11_add_module(example example.cpp)
249
+
250
+ This assumes that the pybind11 repository is located in a subdirectory named
251
+ :file:`pybind11` and that the code is located in a file named :file:`example.cpp`.
252
+ The CMake command ``add_subdirectory`` will import the pybind11 project which
253
+ provides the ``pybind11_add_module`` function. It will take care of all the
254
+ details needed to build a Python extension module on any platform.
255
+
256
+ A working sample project, including a way to invoke CMake from :file:`setup.py` for
257
+ PyPI integration, can be found in the [cmake_example]_ repository.
258
+
259
+ .. [cmake_example] https://github.com/pybind/cmake_example
260
+
261
+ .. versionchanged:: 2.6
262
+ CMake 3.4+ is required.
263
+
264
+ Further information can be found at :doc:`cmake/index`.
265
+
266
+ pybind11_add_module
267
+ -------------------
268
+
269
+ To ease the creation of Python extension modules, pybind11 provides a CMake
270
+ function with the following signature:
271
+
272
+ .. code-block:: cmake
273
+
274
+ pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]
275
+ [NO_EXTRAS] [THIN_LTO] [OPT_SIZE] source1 [source2 ...])
276
+
277
+ This function behaves very much like CMake's builtin ``add_library`` (in fact,
278
+ it's a wrapper function around that command). It will add a library target
279
+ called ``<name>`` to be built from the listed source files. In addition, it
280
+ will take care of all the Python-specific compiler and linker flags as well
281
+ as the OS- and Python-version-specific file extension. The produced target
282
+ ``<name>`` can be further manipulated with regular CMake commands.
283
+
284
+ ``MODULE`` or ``SHARED`` may be given to specify the type of library. If no
285
+ type is given, ``MODULE`` is used by default which ensures the creation of a
286
+ Python-exclusive module. Specifying ``SHARED`` will create a more traditional
287
+ dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL``
288
+ removes this target from the default build (see CMake docs for details).
289
+
290
+ Since pybind11 is a template library, ``pybind11_add_module`` adds compiler
291
+ flags to ensure high quality code generation without bloat arising from long
292
+ symbol names and duplication of code in different translation units. It
293
+ sets default visibility to *hidden*, which is required for some pybind11
294
+ features and functionality when attempting to load multiple pybind11 modules
295
+ compiled under different pybind11 versions. It also adds additional flags
296
+ enabling LTO (Link Time Optimization) and strip unneeded symbols. See the
297
+ :ref:`FAQ entry <faq:symhidden>` for a more detailed explanation. These
298
+ latter optimizations are never applied in ``Debug`` mode. If ``NO_EXTRAS`` is
299
+ given, they will always be disabled, even in ``Release`` mode. However, this
300
+ will result in code bloat and is generally not recommended.
301
+
302
+ As stated above, LTO is enabled by default. Some newer compilers also support
303
+ different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause
304
+ the function to prefer this flavor if available. The function falls back to
305
+ regular LTO if ``-flto=thin`` is not available. If
306
+ ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is set (either ``ON`` or ``OFF``), then
307
+ that will be respected instead of the built-in flag search.
308
+
309
+ .. note::
310
+
311
+ If you want to set the property form on targets or the
312
+ ``CMAKE_INTERPROCEDURAL_OPTIMIZATION_<CONFIG>`` versions of this, you should
313
+ still use ``set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF)`` (otherwise a
314
+ no-op) to disable pybind11's ipo flags.
315
+
316
+ The ``OPT_SIZE`` flag enables size-based optimization equivalent to the
317
+ standard ``/Os`` or ``-Os`` compiler flags and the ``MinSizeRel`` build type,
318
+ which avoid optimizations that that can substantially increase the size of the
319
+ resulting binary. This flag is particularly useful in projects that are split
320
+ into performance-critical parts and associated bindings. In this case, we can
321
+ compile the project in release mode (and hence, optimize performance globally),
322
+ and specify ``OPT_SIZE`` for the binding target, where size might be the main
323
+ concern as performance is often less critical here. A ~25% size reduction has
324
+ been observed in practice. This flag only changes the optimization behavior at
325
+ a per-target level and takes precedence over the global CMake build type
326
+ (``Release``, ``RelWithDebInfo``) except for ``Debug`` builds, where
327
+ optimizations remain disabled.
328
+
329
+ .. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html
330
+
331
+ Configuration variables
332
+ -----------------------
333
+
334
+ By default, pybind11 will compile modules with the compiler default or the
335
+ minimum standard required by pybind11, whichever is higher. You can set the
336
+ standard explicitly with
337
+ `CMAKE_CXX_STANDARD <https://cmake.org/cmake/help/latest/variable/CMAKE_CXX_STANDARD.html>`_:
338
+
339
+ .. code-block:: cmake
340
+
341
+ set(CMAKE_CXX_STANDARD 14 CACHE STRING "C++ version selection") # or 11, 14, 17, 20
342
+ set(CMAKE_CXX_STANDARD_REQUIRED ON) # optional, ensure standard is supported
343
+ set(CMAKE_CXX_EXTENSIONS OFF) # optional, keep compiler extensions off
344
+
345
+ The variables can also be set when calling CMake from the command line using
346
+ the ``-D<variable>=<value>`` flag. You can also manually set ``CXX_STANDARD``
347
+ on a target or use ``target_compile_features`` on your targets - anything that
348
+ CMake supports.
349
+
350
+ Classic Python support: The target Python version can be selected by setting
351
+ ``PYBIND11_PYTHON_VERSION`` or an exact Python installation can be specified
352
+ with ``PYTHON_EXECUTABLE``. For example:
353
+
354
+ .. code-block:: bash
355
+
356
+ cmake -DPYBIND11_PYTHON_VERSION=3.6 ..
357
+
358
+ # Another method:
359
+ cmake -DPYTHON_EXECUTABLE=/path/to/python ..
360
+
361
+ # This often is a good way to get the current Python, works in environments:
362
+ cmake -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)") ..
363
+
364
+
365
+ find_package vs. add_subdirectory
366
+ ---------------------------------
367
+
368
+ For CMake-based projects that don't include the pybind11 repository internally,
369
+ an external installation can be detected through ``find_package(pybind11)``.
370
+ See the `Config file`_ docstring for details of relevant CMake variables.
371
+
372
+ .. code-block:: cmake
373
+
374
+ cmake_minimum_required(VERSION 3.4...3.18)
375
+ project(example LANGUAGES CXX)
376
+
377
+ find_package(pybind11 REQUIRED)
378
+ pybind11_add_module(example example.cpp)
379
+
380
+ Note that ``find_package(pybind11)`` will only work correctly if pybind11
381
+ has been correctly installed on the system, e. g. after downloading or cloning
382
+ the pybind11 repository :
383
+
384
+ .. code-block:: bash
385
+
386
+ # Classic CMake
387
+ cd pybind11
388
+ mkdir build
389
+ cd build
390
+ cmake ..
391
+ make install
392
+
393
+ # CMake 3.15+
394
+ cd pybind11
395
+ cmake -S . -B build
396
+ cmake --build build -j 2 # Build on 2 cores
397
+ cmake --install build
398
+
399
+ Once detected, the aforementioned ``pybind11_add_module`` can be employed as
400
+ before. The function usage and configuration variables are identical no matter
401
+ if pybind11 is added as a subdirectory or found as an installed package. You
402
+ can refer to the same [cmake_example]_ repository for a full sample project
403
+ -- just swap out ``add_subdirectory`` for ``find_package``.
404
+
405
+ .. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in
406
+
407
+
408
+ .. _find-python-mode:
409
+
410
+ FindPython mode
411
+ ---------------
412
+
413
+ CMake 3.12+ (3.15+ recommended, 3.18.2+ ideal) added a new module called
414
+ FindPython that had a highly improved search algorithm and modern targets
415
+ and tools. If you use FindPython, pybind11 will detect this and use the
416
+ existing targets instead:
417
+
418
+ .. code-block:: cmake
419
+
420
+ cmake_minimum_required(VERSION 3.15...3.19)
421
+ project(example LANGUAGES CXX)
422
+
423
+ find_package(Python COMPONENTS Interpreter Development REQUIRED)
424
+ find_package(pybind11 CONFIG REQUIRED)
425
+ # or add_subdirectory(pybind11)
426
+
427
+ pybind11_add_module(example example.cpp)
428
+
429
+ You can also use the targets (as listed below) with FindPython. If you define
430
+ ``PYBIND11_FINDPYTHON``, pybind11 will perform the FindPython step for you
431
+ (mostly useful when building pybind11's own tests, or as a way to change search
432
+ algorithms from the CMake invocation, with ``-DPYBIND11_FINDPYTHON=ON``.
433
+
434
+ .. warning::
435
+
436
+ If you use FindPython2 and FindPython3 to dual-target Python, use the
437
+ individual targets listed below, and avoid targets that directly include
438
+ Python parts.
439
+
440
+ There are `many ways to hint or force a discovery of a specific Python
441
+ installation <https://cmake.org/cmake/help/latest/module/FindPython.html>`_),
442
+ setting ``Python_ROOT_DIR`` may be the most common one (though with
443
+ virtualenv/venv support, and Conda support, this tends to find the correct
444
+ Python version more often than the old system did).
445
+
446
+ .. warning::
447
+
448
+ When the Python libraries (i.e. ``libpythonXX.a`` and ``libpythonXX.so``
449
+ on Unix) are not available, as is the case on a manylinux image, the
450
+ ``Development`` component will not be resolved by ``FindPython``. When not
451
+ using the embedding functionality, CMake 3.18+ allows you to specify
452
+ ``Development.Module`` instead of ``Development`` to resolve this issue.
453
+
454
+ .. versionadded:: 2.6
455
+
456
+ Advanced: interface library targets
457
+ -----------------------------------
458
+
459
+ Pybind11 supports modern CMake usage patterns with a set of interface targets,
460
+ available in all modes. The targets provided are:
461
+
462
+ ``pybind11::headers``
463
+ Just the pybind11 headers and minimum compile requirements
464
+
465
+ ``pybind11::python2_no_register``
466
+ Quiets the warning/error when mixing C++14 or higher and Python 2
467
+
468
+ ``pybind11::pybind11``
469
+ Python headers + ``pybind11::headers`` + ``pybind11::python2_no_register`` (Python 2 only)
470
+
471
+ ``pybind11::python_link_helper``
472
+ Just the "linking" part of pybind11:module
473
+
474
+ ``pybind11::module``
475
+ Everything for extension modules - ``pybind11::pybind11`` + ``Python::Module`` (FindPython CMake 3.15+) or ``pybind11::python_link_helper``
476
+
477
+ ``pybind11::embed``
478
+ Everything for embedding the Python interpreter - ``pybind11::pybind11`` + ``Python::Python`` (FindPython) or Python libs
479
+
480
+ ``pybind11::lto`` / ``pybind11::thin_lto``
481
+ An alternative to `INTERPROCEDURAL_OPTIMIZATION` for adding link-time optimization.
482
+
483
+ ``pybind11::windows_extras``
484
+ ``/bigobj`` and ``/mp`` for MSVC.
485
+
486
+ ``pybind11::opt_size``
487
+ ``/Os`` for MSVC, ``-Os`` for other compilers. Does nothing for debug builds.
488
+
489
+ Two helper functions are also provided:
490
+
491
+ ``pybind11_strip(target)``
492
+ Strips a target (uses ``CMAKE_STRIP`` after the target is built)
493
+
494
+ ``pybind11_extension(target)``
495
+ Sets the correct extension (with SOABI) for a target.
496
+
497
+ You can use these targets to build complex applications. For example, the
498
+ ``add_python_module`` function is identical to:
499
+
500
+ .. code-block:: cmake
501
+
502
+ cmake_minimum_required(VERSION 3.4)
503
+ project(example LANGUAGES CXX)
504
+
505
+ find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
506
+
507
+ add_library(example MODULE main.cpp)
508
+
509
+ target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras)
510
+
511
+ pybind11_extension(example)
512
+ pybind11_strip(example)
513
+
514
+ set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden"
515
+ CUDA_VISIBILITY_PRESET "hidden")
516
+
517
+ Instead of setting properties, you can set ``CMAKE_*`` variables to initialize these correctly.
518
+
519
+ .. warning::
520
+
521
+ Since pybind11 is a metatemplate library, it is crucial that certain
522
+ compiler flags are provided to ensure high quality code generation. In
523
+ contrast to the ``pybind11_add_module()`` command, the CMake interface
524
+ provides a *composable* set of targets to ensure that you retain flexibility.
525
+ It can be especially important to provide or set these properties; the
526
+ :ref:`FAQ <faq:symhidden>` contains an explanation on why these are needed.
527
+
528
+ .. versionadded:: 2.6
529
+
530
+ .. _nopython-mode:
531
+
532
+ Advanced: NOPYTHON mode
533
+ -----------------------
534
+
535
+ If you want complete control, you can set ``PYBIND11_NOPYTHON`` to completely
536
+ disable Python integration (this also happens if you run ``FindPython2`` and
537
+ ``FindPython3`` without running ``FindPython``). This gives you complete
538
+ freedom to integrate into an existing system (like `Scikit-Build's
539
+ <https://scikit-build.readthedocs.io>`_ ``PythonExtensions``).
540
+ ``pybind11_add_module`` and ``pybind11_extension`` will be unavailable, and the
541
+ targets will be missing any Python specific behavior.
542
+
543
+ .. versionadded:: 2.6
544
+
545
+ Embedding the Python interpreter
546
+ --------------------------------
547
+
548
+ In addition to extension modules, pybind11 also supports embedding Python into
549
+ a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
550
+ target. It provides everything needed to get the interpreter running. The Python
551
+ headers and libraries are attached to the target. Unlike ``pybind11::module``,
552
+ there is no need to manually set any additional properties here. For more
553
+ information about usage in C++, see :doc:`/advanced/embedding`.
554
+
555
+ .. code-block:: cmake
556
+
557
+ cmake_minimum_required(VERSION 3.4...3.18)
558
+ project(example LANGUAGES CXX)
559
+
560
+ find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
561
+
562
+ add_executable(example main.cpp)
563
+ target_link_libraries(example PRIVATE pybind11::embed)
564
+
565
+ .. _building_manually:
566
+
567
+ Building manually
568
+ =================
569
+
570
+ pybind11 is a header-only library, hence it is not necessary to link against
571
+ any special libraries and there are no intermediate (magic) translation steps.
572
+
573
+ On Linux, you can compile an example such as the one given in
574
+ :ref:`simple_example` using the following command:
575
+
576
+ .. code-block:: bash
577
+
578
+ $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
579
+
580
+ The flags given here assume that you're using Python 3. For Python 2, just
581
+ change the executable appropriately (to ``python`` or ``python2``).
582
+
583
+ The ``python3 -m pybind11 --includes`` command fetches the include paths for
584
+ both pybind11 and Python headers. This assumes that pybind11 has been installed
585
+ using ``pip`` or ``conda``. If it hasn't, you can also manually specify
586
+ ``-I <path-to-pybind11>/include`` together with the Python includes path
587
+ ``python3-config --includes``.
588
+
589
+ Note that Python 2.7 modules don't use a special suffix, so you should simply
590
+ use ``example.so`` instead of ``example$(python3-config --extension-suffix)``.
591
+ Besides, the ``--extension-suffix`` option may or may not be available, depending
592
+ on the distribution; in the latter case, the module extension can be manually
593
+ set to ``.so``.
594
+
595
+ On macOS: the build command is almost the same but it also requires passing
596
+ the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
597
+ building the module:
598
+
599
+ .. code-block:: bash
600
+
601
+ $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
602
+
603
+ In general, it is advisable to include several additional build parameters
604
+ that can considerably reduce the size of the created binary. Refer to section
605
+ :ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
606
+ build system that works on all platforms including Windows.
607
+
608
+ .. note::
609
+
610
+ On Linux and macOS, it's better to (intentionally) not link against
611
+ ``libpython``. The symbols will be resolved when the extension library
612
+ is loaded into a Python binary. This is preferable because you might
613
+ have several different installations of a given Python version (e.g. the
614
+ system-provided Python, and one that ships with a piece of commercial
615
+ software). In this way, the plugin will work with both versions, instead
616
+ of possibly importing a second Python library into a process that already
617
+ contains one (which will lead to a segfault).
618
+
619
+
620
+ Building with Bazel
621
+ ===================
622
+
623
+ You can build with the Bazel build system using the `pybind11_bazel
624
+ <https://github.com/pybind/pybind11_bazel>`_ repository.
625
+
626
+ Generating binding code automatically
627
+ =====================================
628
+
629
+ The ``Binder`` project is a tool for automatic generation of pybind11 binding
630
+ code by introspecting existing C++ codebases using LLVM/Clang. See the
631
+ [binder]_ documentation for details.
632
+
633
+ .. [binder] http://cppbinder.readthedocs.io/en/latest/about.html
634
+
635
+ [AutoWIG]_ is a Python library that wraps automatically compiled libraries into
636
+ high-level languages. It parses C++ code using LLVM/Clang technologies and
637
+ generates the wrappers using the Mako templating engine. The approach is automatic,
638
+ extensible, and applies to very complex C++ libraries, composed of thousands of
639
+ classes or incorporating modern meta-programming constructs.
640
+
641
+ .. [AutoWIG] https://github.com/StatisKit/AutoWIG
642
+
643
+ [robotpy-build]_ is a is a pure python, cross platform build tool that aims to
644
+ simplify creation of python wheels for pybind11 projects, and provide
645
+ cross-project dependency management. Additionally, it is able to autogenerate
646
+ customizable pybind11-based wrappers by parsing C++ header files.
647
+
648
+ .. [robotpy-build] https://robotpy-build.readthedocs.io
third-party/DPVO/DPRetrieval/pybind11/docs/conf.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # pybind11 documentation build configuration file, created by
5
+ # sphinx-quickstart on Sun Oct 11 19:23:48 2015.
6
+ #
7
+ # This file is execfile()d with the current directory set to its
8
+ # containing dir.
9
+ #
10
+ # Note that not all possible configuration values are present in this
11
+ # autogenerated file.
12
+ #
13
+ # All configuration values have a default; values that are commented out
14
+ # serve to show the default.
15
+
16
+ import os
17
+ import re
18
+ import subprocess
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ DIR = Path(__file__).parent.resolve()
23
+
24
+ # If extensions (or modules to document with autodoc) are in another directory,
25
+ # add these directories to sys.path here. If the directory is relative to the
26
+ # documentation root, use os.path.abspath to make it absolute, like shown here.
27
+ # sys.path.insert(0, os.path.abspath('.'))
28
+
29
+ # -- General configuration ------------------------------------------------
30
+
31
+ # If your documentation needs a minimal Sphinx version, state it here.
32
+ # needs_sphinx = '1.0'
33
+
34
+ # Add any Sphinx extension module names here, as strings. They can be
35
+ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
36
+ # ones.
37
+ extensions = [
38
+ "breathe",
39
+ "sphinxcontrib.rsvgconverter",
40
+ "sphinxcontrib.moderncmakedomain",
41
+ ]
42
+
43
+ breathe_projects = {"pybind11": ".build/doxygenxml/"}
44
+ breathe_default_project = "pybind11"
45
+ breathe_domain_by_extension = {"h": "cpp"}
46
+
47
+ # Add any paths that contain templates here, relative to this directory.
48
+ templates_path = [".templates"]
49
+
50
+ # The suffix(es) of source filenames.
51
+ # You can specify multiple suffix as a list of string:
52
+ # source_suffix = ['.rst', '.md']
53
+ source_suffix = ".rst"
54
+
55
+ # The encoding of source files.
56
+ # source_encoding = 'utf-8-sig'
57
+
58
+ # The master toctree document.
59
+ master_doc = "index"
60
+
61
+ # General information about the project.
62
+ project = "pybind11"
63
+ copyright = "2017, Wenzel Jakob"
64
+ author = "Wenzel Jakob"
65
+
66
+ # The version info for the project you're documenting, acts as replacement for
67
+ # |version| and |release|, also used in various other places throughout the
68
+ # built documents.
69
+
70
+ # Read the listed version
71
+ with open("../pybind11/_version.py") as f:
72
+ code = compile(f.read(), "../pybind11/_version.py", "exec")
73
+ loc = {}
74
+ exec(code, loc)
75
+
76
+ # The full version, including alpha/beta/rc tags.
77
+ version = loc["__version__"]
78
+
79
+ # The language for content autogenerated by Sphinx. Refer to documentation
80
+ # for a list of supported languages.
81
+ #
82
+ # This is also used if you do content translation via gettext catalogs.
83
+ # Usually you set "language" from the command line for these cases.
84
+ language = None
85
+
86
+ # There are two options for replacing |today|: either, you set today to some
87
+ # non-false value, then it is used:
88
+ # today = ''
89
+ # Else, today_fmt is used as the format for a strftime call.
90
+ # today_fmt = '%B %d, %Y'
91
+
92
+ # List of patterns, relative to source directory, that match files and
93
+ # directories to ignore when looking for source files.
94
+ exclude_patterns = [".build", "release.rst"]
95
+
96
+ # The reST default role (used for this markup: `text`) to use for all
97
+ # documents.
98
+ default_role = "any"
99
+
100
+ # If true, '()' will be appended to :func: etc. cross-reference text.
101
+ # add_function_parentheses = True
102
+
103
+ # If true, the current module name will be prepended to all description
104
+ # unit titles (such as .. function::).
105
+ # add_module_names = True
106
+
107
+ # If true, sectionauthor and moduleauthor directives will be shown in the
108
+ # output. They are ignored by default.
109
+ # show_authors = False
110
+
111
+ # The name of the Pygments (syntax highlighting) style to use.
112
+ # pygments_style = 'monokai'
113
+
114
+ # A list of ignored prefixes for module index sorting.
115
+ # modindex_common_prefix = []
116
+
117
+ # If true, keep warnings as "system message" paragraphs in the built documents.
118
+ # keep_warnings = False
119
+
120
+ # If true, `todo` and `todoList` produce output, else they produce nothing.
121
+ todo_include_todos = False
122
+
123
+
124
+ # -- Options for HTML output ----------------------------------------------
125
+
126
+ # The theme to use for HTML and HTML Help pages. See the documentation for
127
+ # a list of builtin themes.
128
+
129
+ on_rtd = os.environ.get("READTHEDOCS", None) == "True"
130
+
131
+ if not on_rtd: # only import and set the theme if we're building docs locally
132
+ import sphinx_rtd_theme
133
+
134
+ html_theme = "sphinx_rtd_theme"
135
+ html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
136
+
137
+ html_context = {"css_files": ["_static/theme_overrides.css"]}
138
+ else:
139
+ html_context = {
140
+ "css_files": [
141
+ "//media.readthedocs.org/css/sphinx_rtd_theme.css",
142
+ "//media.readthedocs.org/css/readthedocs-doc-embed.css",
143
+ "_static/theme_overrides.css",
144
+ ]
145
+ }
146
+
147
+ # Theme options are theme-specific and customize the look and feel of a theme
148
+ # further. For a list of options available for each theme, see the
149
+ # documentation.
150
+ # html_theme_options = {}
151
+
152
+ # Add any paths that contain custom themes here, relative to this directory.
153
+ # html_theme_path = []
154
+
155
+ # The name for this set of Sphinx documents. If None, it defaults to
156
+ # "<project> v<version> documentation".
157
+ # html_title = None
158
+
159
+ # A shorter title for the navigation bar. Default is the same as html_title.
160
+ # html_short_title = None
161
+
162
+ # The name of an image file (relative to this directory) to place at the top
163
+ # of the sidebar.
164
+ # html_logo = None
165
+
166
+ # The name of an image file (within the static path) to use as favicon of the
167
+ # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
168
+ # pixels large.
169
+ # html_favicon = None
170
+
171
+ # Add any paths that contain custom static files (such as style sheets) here,
172
+ # relative to this directory. They are copied after the builtin static files,
173
+ # so a file named "default.css" will overwrite the builtin "default.css".
174
+ html_static_path = ["_static"]
175
+
176
+ # Add any extra paths that contain custom files (such as robots.txt or
177
+ # .htaccess) here, relative to this directory. These files are copied
178
+ # directly to the root of the documentation.
179
+ # html_extra_path = []
180
+
181
+ # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
182
+ # using the given strftime format.
183
+ # html_last_updated_fmt = '%b %d, %Y'
184
+
185
+ # If true, SmartyPants will be used to convert quotes and dashes to
186
+ # typographically correct entities.
187
+ # html_use_smartypants = True
188
+
189
+ # Custom sidebar templates, maps document names to template names.
190
+ # html_sidebars = {}
191
+
192
+ # Additional templates that should be rendered to pages, maps page names to
193
+ # template names.
194
+ # html_additional_pages = {}
195
+
196
+ # If false, no module index is generated.
197
+ # html_domain_indices = True
198
+
199
+ # If false, no index is generated.
200
+ # html_use_index = True
201
+
202
+ # If true, the index is split into individual pages for each letter.
203
+ # html_split_index = False
204
+
205
+ # If true, links to the reST sources are added to the pages.
206
+ # html_show_sourcelink = True
207
+
208
+ # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
209
+ # html_show_sphinx = True
210
+
211
+ # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
212
+ # html_show_copyright = True
213
+
214
+ # If true, an OpenSearch description file will be output, and all pages will
215
+ # contain a <link> tag referring to it. The value of this option must be the
216
+ # base URL from which the finished HTML is served.
217
+ # html_use_opensearch = ''
218
+
219
+ # This is the file name suffix for HTML files (e.g. ".xhtml").
220
+ # html_file_suffix = None
221
+
222
+ # Language to be used for generating the HTML full-text search index.
223
+ # Sphinx supports the following languages:
224
+ # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
225
+ # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
226
+ # html_search_language = 'en'
227
+
228
+ # A dictionary with options for the search language support, empty by default.
229
+ # Now only 'ja' uses this config value
230
+ # html_search_options = {'type': 'default'}
231
+
232
+ # The name of a javascript file (relative to the configuration directory) that
233
+ # implements a search results scorer. If empty, the default will be used.
234
+ # html_search_scorer = 'scorer.js'
235
+
236
+ # Output file base name for HTML help builder.
237
+ htmlhelp_basename = "pybind11doc"
238
+
239
+ # -- Options for LaTeX output ---------------------------------------------
240
+
241
+ latex_engine = "pdflatex"
242
+
243
+ latex_elements = {
244
+ # The paper size ('letterpaper' or 'a4paper').
245
+ # 'papersize': 'letterpaper',
246
+ #
247
+ # The font size ('10pt', '11pt' or '12pt').
248
+ # 'pointsize': '10pt',
249
+ #
250
+ # Additional stuff for the LaTeX preamble.
251
+ # remove blank pages (between the title page and the TOC, etc.)
252
+ "classoptions": ",openany,oneside",
253
+ "preamble": r"""
254
+ \usepackage{fontawesome}
255
+ \usepackage{textgreek}
256
+ \DeclareUnicodeCharacter{00A0}{}
257
+ \DeclareUnicodeCharacter{2194}{\faArrowsH}
258
+ \DeclareUnicodeCharacter{1F382}{\faBirthdayCake}
259
+ \DeclareUnicodeCharacter{1F355}{\faAdjust}
260
+ \DeclareUnicodeCharacter{0301}{'}
261
+ \DeclareUnicodeCharacter{03C0}{\textpi}
262
+
263
+ """,
264
+ # Latex figure (float) alignment
265
+ # 'figure_align': 'htbp',
266
+ }
267
+
268
+ # Grouping the document tree into LaTeX files. List of tuples
269
+ # (source start file, target name, title,
270
+ # author, documentclass [howto, manual, or own class]).
271
+ latex_documents = [
272
+ (master_doc, "pybind11.tex", "pybind11 Documentation", "Wenzel Jakob", "manual"),
273
+ ]
274
+
275
+ # The name of an image file (relative to this directory) to place at the top of
276
+ # the title page.
277
+ # latex_logo = 'pybind11-logo.png'
278
+
279
+ # For "manual" documents, if this is true, then toplevel headings are parts,
280
+ # not chapters.
281
+ # latex_use_parts = False
282
+
283
+ # If true, show page references after internal links.
284
+ # latex_show_pagerefs = False
285
+
286
+ # If true, show URL addresses after external links.
287
+ # latex_show_urls = False
288
+
289
+ # Documents to append as an appendix to all manuals.
290
+ # latex_appendices = []
291
+
292
+ # If false, no module index is generated.
293
+ # latex_domain_indices = True
294
+
295
+
296
+ # -- Options for manual page output ---------------------------------------
297
+
298
+ # One entry per manual page. List of tuples
299
+ # (source start file, name, description, authors, manual section).
300
+ man_pages = [(master_doc, "pybind11", "pybind11 Documentation", [author], 1)]
301
+
302
+ # If true, show URL addresses after external links.
303
+ # man_show_urls = False
304
+
305
+
306
+ # -- Options for Texinfo output -------------------------------------------
307
+
308
+ # Grouping the document tree into Texinfo files. List of tuples
309
+ # (source start file, target name, title, author,
310
+ # dir menu entry, description, category)
311
+ texinfo_documents = [
312
+ (
313
+ master_doc,
314
+ "pybind11",
315
+ "pybind11 Documentation",
316
+ author,
317
+ "pybind11",
318
+ "One line description of project.",
319
+ "Miscellaneous",
320
+ ),
321
+ ]
322
+
323
+ # Documents to append as an appendix to all manuals.
324
+ # texinfo_appendices = []
325
+
326
+ # If false, no module index is generated.
327
+ # texinfo_domain_indices = True
328
+
329
+ # How to display URL addresses: 'footnote', 'no', or 'inline'.
330
+ # texinfo_show_urls = 'footnote'
331
+
332
+ # If true, do not generate a @detailmenu in the "Top" node's menu.
333
+ # texinfo_no_detailmenu = False
334
+
335
+ primary_domain = "cpp"
336
+ highlight_language = "cpp"
337
+
338
+
339
+ def generate_doxygen_xml(app):
340
+ build_dir = os.path.join(app.confdir, ".build")
341
+ if not os.path.exists(build_dir):
342
+ os.mkdir(build_dir)
343
+
344
+ try:
345
+ subprocess.call(["doxygen", "--version"])
346
+ retcode = subprocess.call(["doxygen"], cwd=app.confdir)
347
+ if retcode < 0:
348
+ sys.stderr.write("doxygen error code: {}\n".format(-retcode))
349
+ except OSError as e:
350
+ sys.stderr.write("doxygen execution failed: {}\n".format(e))
351
+
352
+
353
+ def prepare(app):
354
+ with open(DIR.parent / "README.rst") as f:
355
+ contents = f.read()
356
+
357
+ if app.builder.name == "latex":
358
+ # Remove badges and stuff from start
359
+ contents = contents[contents.find(r".. start") :]
360
+
361
+ # Filter out section titles for index.rst for LaTeX
362
+ contents = re.sub(r"^(.*)\n[-~]{3,}$", r"**\1**", contents, flags=re.MULTILINE)
363
+
364
+ with open(DIR / "readme.rst", "w") as f:
365
+ f.write(contents)
366
+
367
+
368
+ def clean_up(app, exception):
369
+ (DIR / "readme.rst").unlink()
370
+
371
+
372
+ def setup(app):
373
+
374
+ # Add hook for building doxygen xml when needed
375
+ app.connect("builder-inited", generate_doxygen_xml)
376
+
377
+ # Copy the readme in
378
+ app.connect("builder-inited", prepare)
379
+
380
+ # Clean up the generated readme
381
+ app.connect("build-finished", clean_up)
third-party/DPVO/DPRetrieval/pybind11/docs/faq.rst ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Frequently asked questions
2
+ ##########################
3
+
4
+ "ImportError: dynamic module does not define init function"
5
+ ===========================================================
6
+
7
+ 1. Make sure that the name specified in PYBIND11_MODULE is identical to the
8
+ filename of the extension library (without suffixes such as ``.so``).
9
+
10
+ 2. If the above did not fix the issue, you are likely using an incompatible
11
+ version of Python (for instance, the extension library was compiled against
12
+ Python 2, while the interpreter is running on top of some version of Python
13
+ 3, or vice versa).
14
+
15
+ "Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
16
+ ========================================================================
17
+
18
+ See the first answer.
19
+
20
+ "SystemError: dynamic module not initialized properly"
21
+ ======================================================
22
+
23
+ See the first answer.
24
+
25
+ The Python interpreter immediately crashes when importing my module
26
+ ===================================================================
27
+
28
+ See the first answer.
29
+
30
+ .. _faq_reference_arguments:
31
+
32
+ Limitations involving reference arguments
33
+ =========================================
34
+
35
+ In C++, it's fairly common to pass arguments using mutable references or
36
+ mutable pointers, which allows both read and write access to the value
37
+ supplied by the caller. This is sometimes done for efficiency reasons, or to
38
+ realize functions that have multiple return values. Here are two very basic
39
+ examples:
40
+
41
+ .. code-block:: cpp
42
+
43
+ void increment(int &i) { i++; }
44
+ void increment_ptr(int *i) { (*i)++; }
45
+
46
+ In Python, all arguments are passed by reference, so there is no general
47
+ issue in binding such code from Python.
48
+
49
+ However, certain basic Python types (like ``str``, ``int``, ``bool``,
50
+ ``float``, etc.) are **immutable**. This means that the following attempt
51
+ to port the function to Python doesn't have the same effect on the value
52
+ provided by the caller -- in fact, it does nothing at all.
53
+
54
+ .. code-block:: python
55
+
56
+ def increment(i):
57
+ i += 1 # nope..
58
+
59
+ pybind11 is also affected by such language-level conventions, which means that
60
+ binding ``increment`` or ``increment_ptr`` will also create Python functions
61
+ that don't modify their arguments.
62
+
63
+ Although inconvenient, one workaround is to encapsulate the immutable types in
64
+ a custom type that does allow modifications.
65
+
66
+ An other alternative involves binding a small wrapper lambda function that
67
+ returns a tuple with all output arguments (see the remainder of the
68
+ documentation for examples on binding lambda functions). An example:
69
+
70
+ .. code-block:: cpp
71
+
72
+ int foo(int &i) { i++; return 123; }
73
+
74
+ and the binding code
75
+
76
+ .. code-block:: cpp
77
+
78
+ m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
79
+
80
+
81
+ How can I reduce the build time?
82
+ ================================
83
+
84
+ It's good practice to split binding code over multiple files, as in the
85
+ following example:
86
+
87
+ :file:`example.cpp`:
88
+
89
+ .. code-block:: cpp
90
+
91
+ void init_ex1(py::module_ &);
92
+ void init_ex2(py::module_ &);
93
+ /* ... */
94
+
95
+ PYBIND11_MODULE(example, m) {
96
+ init_ex1(m);
97
+ init_ex2(m);
98
+ /* ... */
99
+ }
100
+
101
+ :file:`ex1.cpp`:
102
+
103
+ .. code-block:: cpp
104
+
105
+ void init_ex1(py::module_ &m) {
106
+ m.def("add", [](int a, int b) { return a + b; });
107
+ }
108
+
109
+ :file:`ex2.cpp`:
110
+
111
+ .. code-block:: cpp
112
+
113
+ void init_ex2(py::module_ &m) {
114
+ m.def("sub", [](int a, int b) { return a - b; });
115
+ }
116
+
117
+ :command:`python`:
118
+
119
+ .. code-block:: pycon
120
+
121
+ >>> import example
122
+ >>> example.add(1, 2)
123
+ 3
124
+ >>> example.sub(1, 1)
125
+ 0
126
+
127
+ As shown above, the various ``init_ex`` functions should be contained in
128
+ separate files that can be compiled independently from one another, and then
129
+ linked together into the same final shared object. Following this approach
130
+ will:
131
+
132
+ 1. reduce memory requirements per compilation unit.
133
+
134
+ 2. enable parallel builds (if desired).
135
+
136
+ 3. allow for faster incremental builds. For instance, when a single class
137
+ definition is changed, only a subset of the binding code will generally need
138
+ to be recompiled.
139
+
140
+ "recursive template instantiation exceeded maximum depth of 256"
141
+ ================================================================
142
+
143
+ If you receive an error about excessive recursive template evaluation, try
144
+ specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The
145
+ culprit is generally the generation of function signatures at compile time
146
+ using C++14 template metaprogramming.
147
+
148
+ .. _`faq:hidden_visibility`:
149
+
150
+ "‘SomeClass’ declared with greater visibility than the type of its field ‘SomeClass::member’ [-Wattributes]"
151
+ ============================================================================================================
152
+
153
+ This error typically indicates that you are compiling without the required
154
+ ``-fvisibility`` flag. pybind11 code internally forces hidden visibility on
155
+ all internal code, but if non-hidden (and thus *exported*) code attempts to
156
+ include a pybind type (for example, ``py::object`` or ``py::list``) you can run
157
+ into this warning.
158
+
159
+ To avoid it, make sure you are specifying ``-fvisibility=hidden`` when
160
+ compiling pybind code.
161
+
162
+ As to why ``-fvisibility=hidden`` is necessary, because pybind modules could
163
+ have been compiled under different versions of pybind itself, it is also
164
+ important that the symbols defined in one module do not clash with the
165
+ potentially-incompatible symbols defined in another. While Python extension
166
+ modules are usually loaded with localized symbols (under POSIX systems
167
+ typically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default
168
+ can be changed, but even if it isn't it is not always enough to guarantee
169
+ complete independence of the symbols involved when not using
170
+ ``-fvisibility=hidden``.
171
+
172
+ Additionally, ``-fvisibility=hidden`` can deliver considerably binary size
173
+ savings. (See the following section for more details.)
174
+
175
+
176
+ .. _`faq:symhidden`:
177
+
178
+ How can I create smaller binaries?
179
+ ==================================
180
+
181
+ To do its job, pybind11 extensively relies on a programming technique known as
182
+ *template metaprogramming*, which is a way of performing computation at compile
183
+ time using type information. Template metaprogramming usually instantiates code
184
+ involving significant numbers of deeply nested types that are either completely
185
+ removed or reduced to just a few instructions during the compiler's optimization
186
+ phase. However, due to the nested nature of these types, the resulting symbol
187
+ names in the compiled extension library can be extremely long. For instance,
188
+ the included test suite contains the following symbol:
189
+
190
+ .. only:: html
191
+
192
+ .. code-block:: none
193
+
194
+ _​_​Z​N​8​p​y​b​i​n​d​1​1​1​2​c​p​p​_​f​u​n​c​t​i​o​n​C​1​I​v​8​E​x​a​m​p​l​e​2​J​R​N​S​t​3​_​_​1​6​v​e​c​t​o​r​I​N​S​3​_​1​2​b​a​s​i​c​_​s​t​r​i​n​g​I​w​N​S​3​_​1​1​c​h​a​r​_​t​r​a​i​t​s​I​w​E​E​N​S​3​_​9​a​l​l​o​c​a​t​o​r​I​w​E​E​E​E​N​S​8​_​I​S​A​_​E​E​E​E​E​J​N​S​_​4​n​a​m​e​E​N​S​_​7​s​i​b​l​i​n​g​E​N​S​_​9​i​s​_​m​e​t​h​o​d​E​A​2​8​_​c​E​E​E​M​T​0​_​F​T​_​D​p​T​1​_​E​D​p​R​K​T​2​_
195
+
196
+ .. only:: not html
197
+
198
+ .. code-block:: cpp
199
+
200
+ __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
201
+
202
+ which is the mangled form of the following function type:
203
+
204
+ .. code-block:: cpp
205
+
206
+ pybind11::cpp_function::cpp_function<void, Example2, std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28])
207
+
208
+ The memory needed to store just the mangled name of this function (196 bytes)
209
+ is larger than the actual piece of code (111 bytes) it represents! On the other
210
+ hand, it's silly to even give this function a name -- after all, it's just a
211
+ tiny cog in a bigger piece of machinery that is not exposed to the outside
212
+ world. So we'll generally only want to export symbols for those functions which
213
+ are actually called from the outside.
214
+
215
+ This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
216
+ and Clang, which sets the default symbol visibility to *hidden*, which has a
217
+ tremendous impact on the final binary size of the resulting extension library.
218
+ (On Visual Studio, symbols are already hidden by default, so nothing needs to
219
+ be done there.)
220
+
221
+ In addition to decreasing binary size, ``-fvisibility=hidden`` also avoids
222
+ potential serious issues when loading multiple modules and is required for
223
+ proper pybind operation. See the previous FAQ entry for more details.
224
+
225
+ Working with ancient Visual Studio 2008 builds on Windows
226
+ =========================================================
227
+
228
+ The official Windows distributions of Python are compiled using truly
229
+ ancient versions of Visual Studio that lack good C++11 support. Some users
230
+ implicitly assume that it would be impossible to load a plugin built with
231
+ Visual Studio 2015 into a Python distribution that was compiled using Visual
232
+ Studio 2008. However, no such issue exists: it's perfectly legitimate to
233
+ interface DLLs that are built with different compilers and/or C libraries.
234
+ Common gotchas to watch out for involve not ``free()``-ing memory region
235
+ that that were ``malloc()``-ed in another shared library, using data
236
+ structures with incompatible ABIs, and so on. pybind11 is very careful not
237
+ to make these types of mistakes.
238
+
239
+ How can I properly handle Ctrl-C in long-running functions?
240
+ ===========================================================
241
+
242
+ Ctrl-C is received by the Python interpreter, and holds it until the GIL
243
+ is released, so a long-running function won't be interrupted.
244
+
245
+ To interrupt from inside your function, you can use the ``PyErr_CheckSignals()``
246
+ function, that will tell if a signal has been raised on the Python side. This
247
+ function merely checks a flag, so its impact is negligible. When a signal has
248
+ been received, you must either explicitly interrupt execution by throwing
249
+ ``py::error_already_set`` (which will propagate the existing
250
+ ``KeyboardInterrupt``), or clear the error (which you usually will not want):
251
+
252
+ .. code-block:: cpp
253
+
254
+ PYBIND11_MODULE(example, m)
255
+ {
256
+ m.def("long running_func", []()
257
+ {
258
+ for (;;) {
259
+ if (PyErr_CheckSignals() != 0)
260
+ throw py::error_already_set();
261
+ // Long running iteration
262
+ }
263
+ });
264
+ }
265
+
266
+ CMake doesn't detect the right Python version
267
+ =============================================
268
+
269
+ The CMake-based build system will try to automatically detect the installed
270
+ version of Python and link against that. When this fails, or when there are
271
+ multiple versions of Python and it finds the wrong one, delete
272
+ ``CMakeCache.txt`` and then add ``-DPYTHON_EXECUTABLE=$(which python)`` to your
273
+ CMake configure line. (Replace ``$(which python)`` with a path to python if
274
+ your prefer.)
275
+
276
+ You can alternatively try ``-DPYBIND11_FINDPYTHON=ON``, which will activate the
277
+ new CMake FindPython support instead of pybind11's custom search. Requires
278
+ CMake 3.12+, and 3.15+ or 3.18.2+ are even better. You can set this in your
279
+ ``CMakeLists.txt`` before adding or finding pybind11, as well.
280
+
281
+ Inconsistent detection of Python version in CMake and pybind11
282
+ ==============================================================
283
+
284
+ The functions ``find_package(PythonInterp)`` and ``find_package(PythonLibs)``
285
+ provided by CMake for Python version detection are modified by pybind11 due to
286
+ unreliability and limitations that make them unsuitable for pybind11's needs.
287
+ Instead pybind11 provides its own, more reliable Python detection CMake code.
288
+ Conflicts can arise, however, when using pybind11 in a project that *also* uses
289
+ the CMake Python detection in a system with several Python versions installed.
290
+
291
+ This difference may cause inconsistencies and errors if *both* mechanisms are
292
+ used in the same project. Consider the following CMake code executed in a
293
+ system with Python 2.7 and 3.x installed:
294
+
295
+ .. code-block:: cmake
296
+
297
+ find_package(PythonInterp)
298
+ find_package(PythonLibs)
299
+ find_package(pybind11)
300
+
301
+ It will detect Python 2.7 and pybind11 will pick it as well.
302
+
303
+ In contrast this code:
304
+
305
+ .. code-block:: cmake
306
+
307
+ find_package(pybind11)
308
+ find_package(PythonInterp)
309
+ find_package(PythonLibs)
310
+
311
+ will detect Python 3.x for pybind11 and may crash on
312
+ ``find_package(PythonLibs)`` afterwards.
313
+
314
+ There are three possible solutions:
315
+
316
+ 1. Avoid using ``find_package(PythonInterp)`` and ``find_package(PythonLibs)``
317
+ from CMake and rely on pybind11 in detecting Python version. If this is not
318
+ possible, the CMake machinery should be called *before* including pybind11.
319
+ 2. Set ``PYBIND11_FINDPYTHON`` to ``True`` or use ``find_package(Python
320
+ COMPONENTS Interpreter Development)`` on modern CMake (3.12+, 3.15+ better,
321
+ 3.18.2+ best). Pybind11 in these cases uses the new CMake FindPython instead
322
+ of the old, deprecated search tools, and these modules are much better at
323
+ finding the correct Python.
324
+ 3. Set ``PYBIND11_NOPYTHON`` to ``TRUE``. Pybind11 will not search for Python.
325
+ However, you will have to use the target-based system, and do more setup
326
+ yourself, because it does not know about or include things that depend on
327
+ Python, like ``pybind11_add_module``. This might be ideal for integrating
328
+ into an existing system, like scikit-build's Python helpers.
329
+
330
+ How to cite this project?
331
+ =========================
332
+
333
+ We suggest the following BibTeX template to cite pybind11 in scientific
334
+ discourse:
335
+
336
+ .. code-block:: bash
337
+
338
+ @misc{pybind11,
339
+ author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan},
340
+ year = {2017},
341
+ note = {https://github.com/pybind/pybind11},
342
+ title = {pybind11 -- Seamless operability between C++11 and Python}
343
+ }
third-party/DPVO/DPRetrieval/pybind11/docs/index.rst ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. only:: latex
2
+
3
+ Intro
4
+ =====
5
+
6
+ .. include:: readme.rst
7
+
8
+ .. only:: not latex
9
+
10
+ Contents:
11
+
12
+ .. toctree::
13
+ :maxdepth: 1
14
+
15
+ changelog
16
+ upgrade
17
+
18
+ .. toctree::
19
+ :caption: The Basics
20
+ :maxdepth: 2
21
+
22
+ installing
23
+ basics
24
+ classes
25
+ compiling
26
+
27
+ .. toctree::
28
+ :caption: Advanced Topics
29
+ :maxdepth: 2
30
+
31
+ advanced/functions
32
+ advanced/classes
33
+ advanced/exceptions
34
+ advanced/smart_ptrs
35
+ advanced/cast/index
36
+ advanced/pycpp/index
37
+ advanced/embedding
38
+ advanced/misc
39
+
40
+ .. toctree::
41
+ :caption: Extra Information
42
+ :maxdepth: 1
43
+
44
+ faq
45
+ benchmark
46
+ limitations
47
+ reference
48
+ cmake/index
third-party/DPVO/DPRetrieval/pybind11/docs/installing.rst ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _installing:
2
+
3
+ Installing the library
4
+ ######################
5
+
6
+ There are several ways to get the pybind11 source, which lives at
7
+ `pybind/pybind11 on GitHub <https://github.com/pybind/pybind11>`_. The pybind11
8
+ developers recommend one of the first three ways listed here, submodule, PyPI,
9
+ or conda-forge, for obtaining pybind11.
10
+
11
+ .. _include_as_a_submodule:
12
+
13
+ Include as a submodule
14
+ ======================
15
+
16
+ When you are working on a project in Git, you can use the pybind11 repository
17
+ as a submodule. From your git repository, use:
18
+
19
+ .. code-block:: bash
20
+
21
+ git submodule add -b stable ../../pybind/pybind11 extern/pybind11
22
+ git submodule update --init
23
+
24
+ This assumes you are placing your dependencies in ``extern/``, and that you are
25
+ using GitHub; if you are not using GitHub, use the full https or ssh URL
26
+ instead of the relative URL ``../../pybind/pybind11`` above. Some other servers
27
+ also require the ``.git`` extension (GitHub does not).
28
+
29
+ From here, you can now include ``extern/pybind11/include``, or you can use
30
+ the various integration tools (see :ref:`compiling`) pybind11 provides directly
31
+ from the local folder.
32
+
33
+ Include with PyPI
34
+ =================
35
+
36
+ You can download the sources and CMake files as a Python package from PyPI
37
+ using Pip. Just use:
38
+
39
+ .. code-block:: bash
40
+
41
+ pip install pybind11
42
+
43
+ This will provide pybind11 in a standard Python package format. If you want
44
+ pybind11 available directly in your environment root, you can use:
45
+
46
+ .. code-block:: bash
47
+
48
+ pip install "pybind11[global]"
49
+
50
+ This is not recommended if you are installing with your system Python, as it
51
+ will add files to ``/usr/local/include/pybind11`` and
52
+ ``/usr/local/share/cmake/pybind11``, so unless that is what you want, it is
53
+ recommended only for use in virtual environments or your ``pyproject.toml``
54
+ file (see :ref:`compiling`).
55
+
56
+ Include with conda-forge
57
+ ========================
58
+
59
+ You can use pybind11 with conda packaging via `conda-forge
60
+ <https://github.com/conda-forge/pybind11-feedstock>`_:
61
+
62
+ .. code-block:: bash
63
+
64
+ conda install -c conda-forge pybind11
65
+
66
+
67
+ Include with vcpkg
68
+ ==================
69
+ You can download and install pybind11 using the Microsoft `vcpkg
70
+ <https://github.com/Microsoft/vcpkg/>`_ dependency manager:
71
+
72
+ .. code-block:: bash
73
+
74
+ git clone https://github.com/Microsoft/vcpkg.git
75
+ cd vcpkg
76
+ ./bootstrap-vcpkg.sh
77
+ ./vcpkg integrate install
78
+ vcpkg install pybind11
79
+
80
+ The pybind11 port in vcpkg is kept up to date by Microsoft team members and
81
+ community contributors. If the version is out of date, please `create an issue
82
+ or pull request <https://github.com/Microsoft/vcpkg/>`_ on the vcpkg
83
+ repository.
84
+
85
+ Global install with brew
86
+ ========================
87
+
88
+ The brew package manager (Homebrew on macOS, or Linuxbrew on Linux) has a
89
+ `pybind11 package
90
+ <https://github.com/Homebrew/homebrew-core/blob/master/Formula/pybind11.rb>`_.
91
+ To install:
92
+
93
+ .. code-block:: bash
94
+
95
+ brew install pybind11
96
+
97
+ .. We should list Conan, and possibly a few other C++ package managers (hunter,
98
+ .. perhaps). Conan has a very clean CMake integration that would be good to show.
99
+
100
+ Other options
101
+ =============
102
+
103
+ Other locations you can find pybind11 are `listed here
104
+ <https://repology.org/project/python:pybind11/versions>`_; these are maintained
105
+ by various packagers and the community.
third-party/DPVO/DPRetrieval/pybind11/docs/limitations.rst ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Limitations
2
+ ###########
3
+
4
+ Design choices
5
+ ^^^^^^^^^^^^^^
6
+
7
+ pybind11 strives to be a general solution to binding generation, but it also has
8
+ certain limitations:
9
+
10
+ - pybind11 casts away ``const``-ness in function arguments and return values.
11
+ This is in line with the Python language, which has no concept of ``const``
12
+ values. This means that some additional care is needed to avoid bugs that
13
+ would be caught by the type checker in a traditional C++ program.
14
+
15
+ - The NumPy interface ``pybind11::array`` greatly simplifies accessing
16
+ numerical data from C++ (and vice versa), but it's not a full-blown array
17
+ class like ``Eigen::Array`` or ``boost.multi_array``. ``Eigen`` objects are
18
+ directly supported, however, with ``pybind11/eigen.h``.
19
+
20
+ Large but useful features could be implemented in pybind11 but would lead to a
21
+ significant increase in complexity. Pybind11 strives to be simple and compact.
22
+ Users who require large new features are encouraged to write an extension to
23
+ pybind11; see `pybind11_json <https://github.com/pybind/pybind11_json>`_ for an
24
+ example.
25
+
26
+
27
+ Known bugs
28
+ ^^^^^^^^^^
29
+
30
+ These are issues that hopefully will one day be fixed, but currently are
31
+ unsolved. If you know how to help with one of these issues, contributions
32
+ are welcome!
33
+
34
+ - Intel 20.2 is currently having an issue with the test suite.
35
+ `#2573 <https://github.com/pybind/pybind11/pull/2573>`_
36
+
37
+ - Debug mode Python does not support 1-5 tests in the test suite currently.
38
+ `#2422 <https://github.com/pybind/pybind11/pull/2422>`_
39
+
40
+ - PyPy3 7.3.1 and 7.3.2 have issues with several tests on 32-bit Windows.
41
+
42
+ Known limitations
43
+ ^^^^^^^^^^^^^^^^^
44
+
45
+ These are issues that are probably solvable, but have not been fixed yet. A
46
+ clean, well written patch would likely be accepted to solve them.
47
+
48
+ - Type casters are not kept alive recursively.
49
+ `#2527 <https://github.com/pybind/pybind11/issues/2527>`_
50
+ One consequence is that containers of ``char *`` are currently not supported.
51
+ `#2245 <https://github.com/pybind/pybind11/issues/2245>`_
52
+
53
+ - The ``cpptest`` does not run on Windows with Python 3.8 or newer, due to DLL
54
+ loader changes. User code that is correctly installed should not be affected.
55
+ `#2560 <https://github.com/pybind/pybind11/issue/2560>`_
56
+
57
+ Python 3.9.0 warning
58
+ ^^^^^^^^^^^^^^^^^^^^
59
+
60
+ Combining older versions of pybind11 (< 2.6.0) with Python on exactly 3.9.0
61
+ will trigger undefined behavior that typically manifests as crashes during
62
+ interpreter shutdown (but could also destroy your data. **You have been
63
+ warned**).
64
+
65
+ This issue was `fixed in Python <https://github.com/python/cpython/pull/22670>`_.
66
+ As a mitigation for this bug, pybind11 2.6.0 or newer includes a workaround
67
+ specifically when Python 3.9.0 is detected at runtime, leaking about 50 bytes
68
+ of memory when a callback function is garbage collected. For reference, the
69
+ pybind11 test suite has about 2,000 such callbacks, but only 49 are garbage
70
+ collected before the end-of-process. Wheels (even if built with Python 3.9.0)
71
+ will correctly avoid the leak when run in Python 3.9.1, and this does not
72
+ affect other 3.X versions.
third-party/DPVO/DPRetrieval/pybind11/docs/pybind11-logo.png ADDED
third-party/DPVO/DPRetrieval/pybind11/docs/pybind11_vs_boost_python1.png ADDED
third-party/DPVO/DPRetrieval/pybind11/docs/pybind11_vs_boost_python1.svg ADDED
third-party/DPVO/DPRetrieval/pybind11/docs/pybind11_vs_boost_python2.png ADDED
third-party/DPVO/DPRetrieval/pybind11/docs/pybind11_vs_boost_python2.svg ADDED
third-party/DPVO/DPRetrieval/pybind11/docs/reference.rst ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _reference:
2
+
3
+ .. warning::
4
+
5
+ Please be advised that the reference documentation discussing pybind11
6
+ internals is currently incomplete. Please refer to the previous sections
7
+ and the pybind11 header files for the nitty gritty details.
8
+
9
+ Reference
10
+ #########
11
+
12
+ .. _macros:
13
+
14
+ Macros
15
+ ======
16
+
17
+ .. doxygendefine:: PYBIND11_MODULE
18
+
19
+ .. _core_types:
20
+
21
+ Convenience classes for arbitrary Python types
22
+ ==============================================
23
+
24
+ Common member functions
25
+ -----------------------
26
+
27
+ .. doxygenclass:: object_api
28
+ :members:
29
+
30
+ Without reference counting
31
+ --------------------------
32
+
33
+ .. doxygenclass:: handle
34
+ :members:
35
+
36
+ With reference counting
37
+ -----------------------
38
+
39
+ .. doxygenclass:: object
40
+ :members:
41
+
42
+ .. doxygenfunction:: reinterpret_borrow
43
+
44
+ .. doxygenfunction:: reinterpret_steal
45
+
46
+ Convenience classes for specific Python types
47
+ =============================================
48
+
49
+ .. doxygenclass:: module_
50
+ :members:
51
+
52
+ .. doxygengroup:: pytypes
53
+ :members:
54
+
55
+ Convenience functions converting to Python types
56
+ ================================================
57
+
58
+ .. doxygenfunction:: make_tuple(Args&&...)
59
+
60
+ .. doxygenfunction:: make_iterator(Iterator, Sentinel, Extra &&...)
61
+ .. doxygenfunction:: make_iterator(Type &, Extra&&...)
62
+
63
+ .. doxygenfunction:: make_key_iterator(Iterator, Sentinel, Extra &&...)
64
+ .. doxygenfunction:: make_key_iterator(Type &, Extra&&...)
65
+
66
+ .. doxygenfunction:: make_value_iterator(Iterator, Sentinel, Extra &&...)
67
+ .. doxygenfunction:: make_value_iterator(Type &, Extra&&...)
68
+
69
+ .. _extras:
70
+
71
+ Passing extra arguments to ``def`` or ``class_``
72
+ ================================================
73
+
74
+ .. doxygengroup:: annotations
75
+ :members:
76
+
77
+ Embedding the interpreter
78
+ =========================
79
+
80
+ .. doxygendefine:: PYBIND11_EMBEDDED_MODULE
81
+
82
+ .. doxygenfunction:: initialize_interpreter
83
+
84
+ .. doxygenfunction:: finalize_interpreter
85
+
86
+ .. doxygenclass:: scoped_interpreter
87
+
88
+ Redirecting C++ streams
89
+ =======================
90
+
91
+ .. doxygenclass:: scoped_ostream_redirect
92
+
93
+ .. doxygenclass:: scoped_estream_redirect
94
+
95
+ .. doxygenfunction:: add_ostream_redirect
96
+
97
+ Python built-in functions
98
+ =========================
99
+
100
+ .. doxygengroup:: python_builtins
101
+ :members:
102
+
103
+ Inheritance
104
+ ===========
105
+
106
+ See :doc:`/classes` and :doc:`/advanced/classes` for more detail.
107
+
108
+ .. doxygendefine:: PYBIND11_OVERRIDE
109
+
110
+ .. doxygendefine:: PYBIND11_OVERRIDE_PURE
111
+
112
+ .. doxygendefine:: PYBIND11_OVERRIDE_NAME
113
+
114
+ .. doxygendefine:: PYBIND11_OVERRIDE_PURE_NAME
115
+
116
+ .. doxygenfunction:: get_override
117
+
118
+ Exceptions
119
+ ==========
120
+
121
+ .. doxygenclass:: error_already_set
122
+ :members:
123
+
124
+ .. doxygenclass:: builtin_exception
125
+ :members:
126
+
127
+ Literals
128
+ ========
129
+
130
+ .. doxygennamespace:: literals
third-party/DPVO/DPRetrieval/pybind11/docs/release.rst ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ On version numbers
2
+ ^^^^^^^^^^^^^^^^^^
3
+
4
+ The two version numbers (C++ and Python) must match when combined (checked when
5
+ you build the PyPI package), and must be a valid `PEP 440
6
+ <https://www.python.org/dev/peps/pep-0440>`_ version when combined.
7
+
8
+ For example:
9
+
10
+ .. code-block:: C++
11
+
12
+ #define PYBIND11_VERSION_MAJOR X
13
+ #define PYBIND11_VERSION_MINOR Y
14
+ #define PYBIND11_VERSION_PATCH Z.dev1
15
+
16
+ For beta, ``PYBIND11_VERSION_PATCH`` should be ``Z.b1``. RC's can be ``Z.rc1``.
17
+ Always include the dot (even though PEP 440 allows it to be dropped). For a
18
+ final release, this must be a simple integer. There is also a HEX version of
19
+ the version just below.
20
+
21
+
22
+ To release a new version of pybind11:
23
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
24
+
25
+ If you don't have nox, you should either use ``pipx run nox`` instead, or use
26
+ ``pipx install nox`` or ``brew install nox`` (Unix).
27
+
28
+ - Update the version number
29
+ - Update ``PYBIND11_VERSION_MAJOR`` etc. in
30
+ ``include/pybind11/detail/common.h``. PATCH should be a simple integer.
31
+ - Update the version HEX just below, as well.
32
+ - Update ``pybind11/_version.py`` (match above)
33
+ - Run ``nox -s tests_packaging`` to ensure this was done correctly.
34
+ - Ensure that all the information in ``setup.cfg`` is up-to-date, like
35
+ supported Python versions.
36
+ - Add release date in ``docs/changelog.rst``.
37
+ - Check to make sure
38
+ `needs-changelog <https://github.com/pybind/pybind11/pulls?q=is%3Apr+is%3Aclosed+label%3A%22needs+changelog%22>`_
39
+ issues are entered in the changelog (clear the label when done).
40
+ - ``git add`` and ``git commit``, ``git push``. **Ensure CI passes**. (If it
41
+ fails due to a known flake issue, either ignore or restart CI.)
42
+ - Add a release branch if this is a new minor version, or update the existing release branch if it is a patch version
43
+ - New branch: ``git checkout -b vX.Y``, ``git push -u origin vX.Y``
44
+ - Update branch: ``git checkout vX.Y``, ``git merge <release branch>``, ``git push``
45
+ - Update tags (optional; if you skip this, the GitHub release makes a
46
+ non-annotated tag for you)
47
+ - ``git tag -a vX.Y.Z -m 'vX.Y.Z release'``.
48
+ - ``git push --tags``.
49
+ - Update stable
50
+ - ``git checkout stable``
51
+ - ``git merge master``
52
+ - ``git push``
53
+ - Make a GitHub release (this shows up in the UI, sends new release
54
+ notifications to users watching releases, and also uploads PyPI packages).
55
+ (Note: if you do not use an existing tag, this creates a new lightweight tag
56
+ for you, so you could skip the above step.)
57
+ - GUI method: Under `releases <https://github.com/pybind/pybind11/releases>`_
58
+ click "Draft a new release" on the far right, fill in the tag name
59
+ (if you didn't tag above, it will be made here), fill in a release name
60
+ like "Version X.Y.Z", and copy-and-paste the markdown-formatted (!) changelog
61
+ into the description (usually ``cat docs/changelog.rst | pandoc -f rst -t gfm``).
62
+ Check "pre-release" if this is a beta/RC.
63
+ - CLI method: with ``gh`` installed, run ``gh release create vX.Y.Z -t "Version X.Y.Z"``
64
+ If this is a pre-release, add ``-p``.
65
+
66
+ - Get back to work
67
+ - Make sure you are on master, not somewhere else: ``git checkout master``
68
+ - Update version macros in ``include/pybind11/detail/common.h`` (set PATCH to
69
+ ``0.dev1`` and increment MINOR).
70
+ - Update ``_version.py`` to match
71
+ - Run ``nox -s tests_packaging`` to ensure this was done correctly.
72
+ - Add a spot for in-development updates in ``docs/changelog.rst``.
73
+ - ``git add``, ``git commit``, ``git push``
74
+
75
+ If a version branch is updated, remember to set PATCH to ``1.dev1``.
76
+
77
+ If you'd like to bump homebrew, run:
78
+
79
+ .. code-block:: console
80
+
81
+ brew bump-formula-pr --url https://github.com/pybind/pybind11/archive/vX.Y.Z.tar.gz
82
+
83
+ Conda-forge should automatically make a PR in a few hours, and automatically
84
+ merge it if there are no issues.
85
+
86
+
87
+ Manual packaging
88
+ ^^^^^^^^^^^^^^^^
89
+
90
+ If you need to manually upload releases, you can download the releases from the job artifacts and upload them with twine. You can also make the files locally (not recommended in general, as your local directory is more likely to be "dirty" and SDists love picking up random unrelated/hidden files); this is the procedure:
91
+
92
+ .. code-block:: bash
93
+
94
+ nox -s build
95
+ twine upload dist/*
96
+
97
+ This makes SDists and wheels, and the final line uploads them.
third-party/DPVO/DPRetrieval/pybind11/docs/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ breathe==4.31.0
2
+ sphinx==3.5.4
3
+ sphinx_rtd_theme==1.0.0
4
+ sphinxcontrib-moderncmakedomain==3.19
5
+ sphinxcontrib-svg2pdfconverter==1.1.1
third-party/DPVO/DPRetrieval/pybind11/docs/upgrade.rst ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Upgrade guide
2
+ #############
3
+
4
+ This is a companion guide to the :doc:`changelog`. While the changelog briefly
5
+ lists all of the new features, improvements and bug fixes, this upgrade guide
6
+ focuses only the subset which directly impacts your experience when upgrading
7
+ to a new version. But it goes into more detail. This includes things like
8
+ deprecated APIs and their replacements, build system changes, general code
9
+ modernization and other useful information.
10
+
11
+ .. _upgrade-guide-2.9:
12
+
13
+ v2.9
14
+ ====
15
+
16
+ * Any usage of the recently added ``py::make_simple_namespace`` should be
17
+ converted to using ``py::module_::import("types").attr("SimpleNamespace")``
18
+ instead.
19
+
20
+ * The use of ``_`` in custom type casters can now be replaced with the more
21
+ readable ``const_name`` instead. The old ``_`` shortcut has been retained
22
+ unless it is being used as a macro (like for gettext).
23
+
24
+
25
+ .. _upgrade-guide-2.7:
26
+
27
+ v2.7
28
+ ====
29
+
30
+ *Before* v2.7, ``py::str`` can hold ``PyUnicodeObject`` or ``PyBytesObject``,
31
+ and ``py::isinstance<str>()`` is ``true`` for both ``py::str`` and
32
+ ``py::bytes``. Starting with v2.7, ``py::str`` exclusively holds
33
+ ``PyUnicodeObject`` (`#2409 <https://github.com/pybind/pybind11/pull/2409>`_),
34
+ and ``py::isinstance<str>()`` is ``true`` only for ``py::str``. To help in
35
+ the transition of user code, the ``PYBIND11_STR_LEGACY_PERMISSIVE`` macro
36
+ is provided as an escape hatch to go back to the legacy behavior. This macro
37
+ will be removed in future releases. Two types of required fixes are expected
38
+ to be common:
39
+
40
+ * Accidental use of ``py::str`` instead of ``py::bytes``, masked by the legacy
41
+ behavior. These are probably very easy to fix, by changing from
42
+ ``py::str`` to ``py::bytes``.
43
+
44
+ * Reliance on py::isinstance<str>(obj) being ``true`` for
45
+ ``py::bytes``. This is likely to be easy to fix in most cases by adding
46
+ ``|| py::isinstance<bytes>(obj)``, but a fix may be more involved, e.g. if
47
+ ``py::isinstance<T>`` appears in a template. Such situations will require
48
+ careful review and custom fixes.
49
+
50
+
51
+ .. _upgrade-guide-2.6:
52
+
53
+ v2.6
54
+ ====
55
+
56
+ Usage of the ``PYBIND11_OVERLOAD*`` macros and ``get_overload`` function should
57
+ be replaced by ``PYBIND11_OVERRIDE*`` and ``get_override``. In the future, the
58
+ old macros may be deprecated and removed.
59
+
60
+ ``py::module`` has been renamed ``py::module_``, but a backward compatible
61
+ typedef has been included. This change was to avoid a language change in C++20
62
+ that requires unqualified ``module`` not be placed at the start of a logical
63
+ line. Qualified usage is unaffected and the typedef will remain unless the
64
+ C++ language rules change again.
65
+
66
+ The public constructors of ``py::module_`` have been deprecated. Use
67
+ ``PYBIND11_MODULE`` or ``module_::create_extension_module`` instead.
68
+
69
+ An error is now thrown when ``__init__`` is forgotten on subclasses. This was
70
+ incorrect before, but was not checked. Add a call to ``__init__`` if it is
71
+ missing.
72
+
73
+ A ``py::type_error`` is now thrown when casting to a subclass (like
74
+ ``py::bytes`` from ``py::object``) if the conversion is not valid. Make a valid
75
+ conversion instead.
76
+
77
+ The undocumented ``h.get_type()`` method has been deprecated and replaced by
78
+ ``py::type::of(h)``.
79
+
80
+ Enums now have a ``__str__`` method pre-defined; if you want to override it,
81
+ the simplest fix is to add the new ``py::prepend()`` tag when defining
82
+ ``"__str__"``.
83
+
84
+ If ``__eq__`` defined but not ``__hash__``, ``__hash__`` is now set to
85
+ ``None``, as in normal CPython. You should add ``__hash__`` if you intended the
86
+ class to be hashable, possibly using the new ``py::hash`` shortcut.
87
+
88
+ The constructors for ``py::array`` now always take signed integers for size,
89
+ for consistency. This may lead to compiler warnings on some systems. Cast to
90
+ ``py::ssize_t`` instead of ``std::size_t``.
91
+
92
+ The ``tools/clang`` submodule and ``tools/mkdoc.py`` have been moved to a
93
+ standalone package, `pybind11-mkdoc`_. If you were using those tools, please
94
+ use them via a pip install from the new location.
95
+
96
+ The ``pybind11`` package on PyPI no longer fills the wheel "headers" slot - if
97
+ you were using the headers from this slot, they are available by requesting the
98
+ ``global`` extra, that is, ``pip install "pybind11[global]"``. (Most users will
99
+ be unaffected, as the ``pybind11/include`` location is reported by ``python -m
100
+ pybind11 --includes`` and ``pybind11.get_include()`` is still correct and has
101
+ not changed since 2.5).
102
+
103
+ .. _pybind11-mkdoc: https://github.com/pybind/pybind11-mkdoc
104
+
105
+ CMake support:
106
+ --------------
107
+
108
+ The minimum required version of CMake is now 3.4. Several details of the CMake
109
+ support have been deprecated; warnings will be shown if you need to change
110
+ something. The changes are:
111
+
112
+ * ``PYBIND11_CPP_STANDARD=<platform-flag>`` is deprecated, please use
113
+ ``CMAKE_CXX_STANDARD=<number>`` instead, or any other valid CMake CXX or CUDA
114
+ standard selection method, like ``target_compile_features``.
115
+
116
+ * If you do not request a standard, pybind11 targets will compile with the
117
+ compiler default, but not less than C++11, instead of forcing C++14 always.
118
+ If you depend on the old behavior, please use ``set(CMAKE_CXX_STANDARD 14 CACHE STRING "")``
119
+ instead.
120
+
121
+ * Direct ``pybind11::module`` usage should always be accompanied by at least
122
+ ``set(CMAKE_CXX_VISIBILITY_PRESET hidden)`` or similar - it used to try to
123
+ manually force this compiler flag (but not correctly on all compilers or with
124
+ CUDA).
125
+
126
+ * ``pybind11_add_module``'s ``SYSTEM`` argument is deprecated and does nothing;
127
+ linking now behaves like other imported libraries consistently in both
128
+ config and submodule mode, and behaves like a ``SYSTEM`` library by
129
+ default.
130
+
131
+ * If ``PYTHON_EXECUTABLE`` is not set, virtual environments (``venv``,
132
+ ``virtualenv``, and ``conda``) are prioritized over the standard search
133
+ (similar to the new FindPython mode).
134
+
135
+ In addition, the following changes may be of interest:
136
+
137
+ * ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` will be respected by
138
+ ``pybind11_add_module`` if set instead of linking to ``pybind11::lto`` or
139
+ ``pybind11::thin_lto``.
140
+
141
+ * Using ``find_package(Python COMPONENTS Interpreter Development)`` before
142
+ pybind11 will cause pybind11 to use the new Python mechanisms instead of its
143
+ own custom search, based on a patched version of classic ``FindPythonInterp``
144
+ / ``FindPythonLibs``. In the future, this may become the default. A recent
145
+ (3.15+ or 3.18.2+) version of CMake is recommended.
146
+
147
+
148
+
149
+ v2.5
150
+ ====
151
+
152
+ The Python package now includes the headers as data in the package itself, as
153
+ well as in the "headers" wheel slot. ``pybind11 --includes`` and
154
+ ``pybind11.get_include()`` report the new location, which is always correct
155
+ regardless of how pybind11 was installed, making the old ``user=`` argument
156
+ meaningless. If you are not using the function to get the location already, you
157
+ are encouraged to switch to the package location.
158
+
159
+
160
+ v2.2
161
+ ====
162
+
163
+ Deprecation of the ``PYBIND11_PLUGIN`` macro
164
+ --------------------------------------------
165
+
166
+ ``PYBIND11_MODULE`` is now the preferred way to create module entry points.
167
+ The old macro emits a compile-time deprecation warning.
168
+
169
+ .. code-block:: cpp
170
+
171
+ // old
172
+ PYBIND11_PLUGIN(example) {
173
+ py::module m("example", "documentation string");
174
+
175
+ m.def("add", [](int a, int b) { return a + b; });
176
+
177
+ return m.ptr();
178
+ }
179
+
180
+ // new
181
+ PYBIND11_MODULE(example, m) {
182
+ m.doc() = "documentation string"; // optional
183
+
184
+ m.def("add", [](int a, int b) { return a + b; });
185
+ }
186
+
187
+
188
+ New API for defining custom constructors and pickling functions
189
+ ---------------------------------------------------------------
190
+
191
+ The old placement-new custom constructors have been deprecated. The new approach
192
+ uses ``py::init()`` and factory functions to greatly improve type safety.
193
+
194
+ Placement-new can be called accidentally with an incompatible type (without any
195
+ compiler errors or warnings), or it can initialize the same object multiple times
196
+ if not careful with the Python-side ``__init__`` calls. The new-style custom
197
+ constructors prevent such mistakes. See :ref:`custom_constructors` for details.
198
+
199
+ .. code-block:: cpp
200
+
201
+ // old -- deprecated (runtime warning shown only in debug mode)
202
+ py::class<Foo>(m, "Foo")
203
+ .def("__init__", [](Foo &self, ...) {
204
+ new (&self) Foo(...); // uses placement-new
205
+ });
206
+
207
+ // new
208
+ py::class<Foo>(m, "Foo")
209
+ .def(py::init([](...) { // Note: no `self` argument
210
+ return new Foo(...); // return by raw pointer
211
+ // or: return std::make_unique<Foo>(...); // return by holder
212
+ // or: return Foo(...); // return by value (move constructor)
213
+ }));
214
+
215
+ Mirroring the custom constructor changes, ``py::pickle()`` is now the preferred
216
+ way to get and set object state. See :ref:`pickling` for details.
217
+
218
+ .. code-block:: cpp
219
+
220
+ // old -- deprecated (runtime warning shown only in debug mode)
221
+ py::class<Foo>(m, "Foo")
222
+ ...
223
+ .def("__getstate__", [](const Foo &self) {
224
+ return py::make_tuple(self.value1(), self.value2(), ...);
225
+ })
226
+ .def("__setstate__", [](Foo &self, py::tuple t) {
227
+ new (&self) Foo(t[0].cast<std::string>(), ...);
228
+ });
229
+
230
+ // new
231
+ py::class<Foo>(m, "Foo")
232
+ ...
233
+ .def(py::pickle(
234
+ [](const Foo &self) { // __getstate__
235
+ return py::make_tuple(self.value1(), self.value2(), ...); // unchanged
236
+ },
237
+ [](py::tuple t) { // __setstate__, note: no `self` argument
238
+ return new Foo(t[0].cast<std::string>(), ...);
239
+ // or: return std::make_unique<Foo>(...); // return by holder
240
+ // or: return Foo(...); // return by value (move constructor)
241
+ }
242
+ ));
243
+
244
+ For both the constructors and pickling, warnings are shown at module
245
+ initialization time (on import, not when the functions are called).
246
+ They're only visible when compiled in debug mode. Sample warning:
247
+
248
+ .. code-block:: none
249
+
250
+ pybind11-bound class 'mymodule.Foo' is using an old-style placement-new '__init__'
251
+ which has been deprecated. See the upgrade guide in pybind11's docs.
252
+
253
+
254
+ Stricter enforcement of hidden symbol visibility for pybind11 modules
255
+ ---------------------------------------------------------------------
256
+
257
+ pybind11 now tries to actively enforce hidden symbol visibility for modules.
258
+ If you're using either one of pybind11's :doc:`CMake or Python build systems
259
+ <compiling>` (the two example repositories) and you haven't been exporting any
260
+ symbols, there's nothing to be concerned about. All the changes have been done
261
+ transparently in the background. If you were building manually or relied on
262
+ specific default visibility, read on.
263
+
264
+ Setting default symbol visibility to *hidden* has always been recommended for
265
+ pybind11 (see :ref:`faq:symhidden`). On Linux and macOS, hidden symbol
266
+ visibility (in conjunction with the ``strip`` utility) yields much smaller
267
+ module binaries. `CPython's extension docs`_ also recommend hiding symbols
268
+ by default, with the goal of avoiding symbol name clashes between modules.
269
+ Starting with v2.2, pybind11 enforces this more strictly: (1) by declaring
270
+ all symbols inside the ``pybind11`` namespace as hidden and (2) by including
271
+ the ``-fvisibility=hidden`` flag on Linux and macOS (only for extension
272
+ modules, not for embedding the interpreter).
273
+
274
+ .. _CPython's extension docs: https://docs.python.org/3/extending/extending.html#providing-a-c-api-for-an-extension-module
275
+
276
+ The namespace-scope hidden visibility is done automatically in pybind11's
277
+ headers and it's generally transparent to users. It ensures that:
278
+
279
+ * Modules compiled with different pybind11 versions don't clash with each other.
280
+
281
+ * Some new features, like ``py::module_local`` bindings, can work as intended.
282
+
283
+ The ``-fvisibility=hidden`` flag applies the same visibility to user bindings
284
+ outside of the ``pybind11`` namespace. It's now set automatic by pybind11's
285
+ CMake and Python build systems, but this needs to be done manually by users
286
+ of other build systems. Adding this flag:
287
+
288
+ * Minimizes the chances of symbol conflicts between modules. E.g. if two
289
+ unrelated modules were statically linked to different (ABI-incompatible)
290
+ versions of the same third-party library, a symbol clash would be likely
291
+ (and would end with unpredictable results).
292
+
293
+ * Produces smaller binaries on Linux and macOS, as pointed out previously.
294
+
295
+ Within pybind11's CMake build system, ``pybind11_add_module`` has always been
296
+ setting the ``-fvisibility=hidden`` flag in release mode. From now on, it's
297
+ being applied unconditionally, even in debug mode and it can no longer be opted
298
+ out of with the ``NO_EXTRAS`` option. The ``pybind11::module`` target now also
299
+ adds this flag to its interface. The ``pybind11::embed`` target is unchanged.
300
+
301
+ The most significant change here is for the ``pybind11::module`` target. If you
302
+ were previously relying on default visibility, i.e. if your Python module was
303
+ doubling as a shared library with dependents, you'll need to either export
304
+ symbols manually (recommended for cross-platform libraries) or factor out the
305
+ shared library (and have the Python module link to it like the other
306
+ dependents). As a temporary workaround, you can also restore default visibility
307
+ using the CMake code below, but this is not recommended in the long run:
308
+
309
+ .. code-block:: cmake
310
+
311
+ target_link_libraries(mymodule PRIVATE pybind11::module)
312
+
313
+ add_library(restore_default_visibility INTERFACE)
314
+ target_compile_options(restore_default_visibility INTERFACE -fvisibility=default)
315
+ target_link_libraries(mymodule PRIVATE restore_default_visibility)
316
+
317
+
318
+ Local STL container bindings
319
+ ----------------------------
320
+
321
+ Previous pybind11 versions could only bind types globally -- all pybind11
322
+ modules, even unrelated ones, would have access to the same exported types.
323
+ However, this would also result in a conflict if two modules exported the
324
+ same C++ type, which is especially problematic for very common types, e.g.
325
+ ``std::vector<int>``. :ref:`module_local` were added to resolve this (see
326
+ that section for a complete usage guide).
327
+
328
+ ``py::class_`` still defaults to global bindings (because these types are
329
+ usually unique across modules), however in order to avoid clashes of opaque
330
+ types, ``py::bind_vector`` and ``py::bind_map`` will now bind STL containers
331
+ as ``py::module_local`` if their elements are: builtins (``int``, ``float``,
332
+ etc.), not bound using ``py::class_``, or bound as ``py::module_local``. For
333
+ example, this change allows multiple modules to bind ``std::vector<int>``
334
+ without causing conflicts. See :ref:`stl_bind` for more details.
335
+
336
+ When upgrading to this version, if you have multiple modules which depend on
337
+ a single global binding of an STL container, note that all modules can still
338
+ accept foreign ``py::module_local`` types in the direction of Python-to-C++.
339
+ The locality only affects the C++-to-Python direction. If this is needed in
340
+ multiple modules, you'll need to either:
341
+
342
+ * Add a copy of the same STL binding to all of the modules which need it.
343
+
344
+ * Restore the global status of that single binding by marking it
345
+ ``py::module_local(false)``.
346
+
347
+ The latter is an easy workaround, but in the long run it would be best to
348
+ localize all common type bindings in order to avoid conflicts with
349
+ third-party modules.
350
+
351
+
352
+ Negative strides for Python buffer objects and numpy arrays
353
+ -----------------------------------------------------------
354
+
355
+ Support for negative strides required changing the integer type from unsigned
356
+ to signed in the interfaces of ``py::buffer_info`` and ``py::array``. If you
357
+ have compiler warnings enabled, you may notice some new conversion warnings
358
+ after upgrading. These can be resolved using ``static_cast``.
359
+
360
+
361
+ Deprecation of some ``py::object`` APIs
362
+ ---------------------------------------
363
+
364
+ To compare ``py::object`` instances by pointer, you should now use
365
+ ``obj1.is(obj2)`` which is equivalent to ``obj1 is obj2`` in Python.
366
+ Previously, pybind11 used ``operator==`` for this (``obj1 == obj2``), but
367
+ that could be confusing and is now deprecated (so that it can eventually
368
+ be replaced with proper rich object comparison in a future release).
369
+
370
+ For classes which inherit from ``py::object``, ``borrowed`` and ``stolen``
371
+ were previously available as protected constructor tags. Now the types
372
+ should be used directly instead: ``borrowed_t{}`` and ``stolen_t{}``
373
+ (`#771 <https://github.com/pybind/pybind11/pull/771>`_).
374
+
375
+
376
+ Stricter compile-time error checking
377
+ ------------------------------------
378
+
379
+ Some error checks have been moved from run time to compile time. Notably,
380
+ automatic conversion of ``std::shared_ptr<T>`` is not possible when ``T`` is
381
+ not directly registered with ``py::class_<T>`` (e.g. ``std::shared_ptr<int>``
382
+ or ``std::shared_ptr<std::vector<T>>`` are not automatically convertible).
383
+ Attempting to bind a function with such arguments now results in a compile-time
384
+ error instead of waiting to fail at run time.
385
+
386
+ ``py::init<...>()`` constructor definitions are also stricter and now prevent
387
+ bindings which could cause unexpected behavior:
388
+
389
+ .. code-block:: cpp
390
+
391
+ struct Example {
392
+ Example(int &);
393
+ };
394
+
395
+ py::class_<Example>(m, "Example")
396
+ .def(py::init<int &>()); // OK, exact match
397
+ // .def(py::init<int>()); // compile-time error, mismatch
398
+
399
+ A non-``const`` lvalue reference is not allowed to bind to an rvalue. However,
400
+ note that a constructor taking ``const T &`` can still be registered using
401
+ ``py::init<T>()`` because a ``const`` lvalue reference can bind to an rvalue.
402
+
403
+ v2.1
404
+ ====
405
+
406
+ Minimum compiler versions are enforced at compile time
407
+ ------------------------------------------------------
408
+
409
+ The minimums also apply to v2.0 but the check is now explicit and a compile-time
410
+ error is raised if the compiler does not meet the requirements:
411
+
412
+ * GCC >= 4.8
413
+ * clang >= 3.3 (appleclang >= 5.0)
414
+ * MSVC >= 2015u3
415
+ * Intel C++ >= 15.0
416
+
417
+
418
+ The ``py::metaclass`` attribute is not required for static properties
419
+ ---------------------------------------------------------------------
420
+
421
+ Binding classes with static properties is now possible by default. The
422
+ zero-parameter version of ``py::metaclass()`` is deprecated. However, a new
423
+ one-parameter ``py::metaclass(python_type)`` version was added for rare
424
+ cases when a custom metaclass is needed to override pybind11's default.
425
+
426
+ .. code-block:: cpp
427
+
428
+ // old -- emits a deprecation warning
429
+ py::class_<Foo>(m, "Foo", py::metaclass())
430
+ .def_property_readonly_static("foo", ...);
431
+
432
+ // new -- static properties work without the attribute
433
+ py::class_<Foo>(m, "Foo")
434
+ .def_property_readonly_static("foo", ...);
435
+
436
+ // new -- advanced feature, override pybind11's default metaclass
437
+ py::class_<Bar>(m, "Bar", py::metaclass(custom_python_type))
438
+ ...
439
+
440
+
441
+ v2.0
442
+ ====
443
+
444
+ Breaking changes in ``py::class_``
445
+ ----------------------------------
446
+
447
+ These changes were necessary to make type definitions in pybind11
448
+ future-proof, to support PyPy via its ``cpyext`` mechanism (`#527
449
+ <https://github.com/pybind/pybind11/pull/527>`_), and to improve efficiency
450
+ (`rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_).
451
+
452
+ 1. Declarations of types that provide access via the buffer protocol must
453
+ now include the ``py::buffer_protocol()`` annotation as an argument to
454
+ the ``py::class_`` constructor.
455
+
456
+ .. code-block:: cpp
457
+
458
+ py::class_<Matrix>("Matrix", py::buffer_protocol())
459
+ .def(py::init<...>())
460
+ .def_buffer(...);
461
+
462
+ 2. Classes which include static properties (e.g. ``def_readwrite_static()``)
463
+ must now include the ``py::metaclass()`` attribute. Note: this requirement
464
+ has since been removed in v2.1. If you're upgrading from 1.x, it's
465
+ recommended to skip directly to v2.1 or newer.
466
+
467
+ 3. This version of pybind11 uses a redesigned mechanism for instantiating
468
+ trampoline classes that are used to override virtual methods from within
469
+ Python. This led to the following user-visible syntax change:
470
+
471
+ .. code-block:: cpp
472
+
473
+ // old v1.x syntax
474
+ py::class_<TrampolineClass>("MyClass")
475
+ .alias<MyClass>()
476
+ ...
477
+
478
+ // new v2.x syntax
479
+ py::class_<MyClass, TrampolineClass>("MyClass")
480
+ ...
481
+
482
+ Importantly, both the original and the trampoline class are now specified
483
+ as arguments to the ``py::class_`` template, and the ``alias<..>()`` call
484
+ is gone. The new scheme has zero overhead in cases when Python doesn't
485
+ override any functions of the underlying C++ class.
486
+ `rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_.
487
+
488
+ The class type must be the first template argument given to ``py::class_``
489
+ while the trampoline can be mixed in arbitrary order with other arguments
490
+ (see the following section).
491
+
492
+
493
+ Deprecation of the ``py::base<T>()`` attribute
494
+ ----------------------------------------------
495
+
496
+ ``py::base<T>()`` was deprecated in favor of specifying ``T`` as a template
497
+ argument to ``py::class_``. This new syntax also supports multiple inheritance.
498
+ Note that, while the type being exported must be the first argument in the
499
+ ``py::class_<Class, ...>`` template, the order of the following types (bases,
500
+ holder and/or trampoline) is not important.
501
+
502
+ .. code-block:: cpp
503
+
504
+ // old v1.x
505
+ py::class_<Derived>("Derived", py::base<Base>());
506
+
507
+ // new v2.x
508
+ py::class_<Derived, Base>("Derived");
509
+
510
+ // new -- multiple inheritance
511
+ py::class_<Derived, Base1, Base2>("Derived");
512
+
513
+ // new -- apart from `Derived` the argument order can be arbitrary
514
+ py::class_<Derived, Base1, Holder, Base2, Trampoline>("Derived");
515
+
516
+
517
+ Out-of-the-box support for ``std::shared_ptr``
518
+ ----------------------------------------------
519
+
520
+ The relevant type caster is now built in, so it's no longer necessary to
521
+ include a declaration of the form:
522
+
523
+ .. code-block:: cpp
524
+
525
+ PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
526
+
527
+ Continuing to do so won’t cause an error or even a deprecation warning,
528
+ but it's completely redundant.
529
+
530
+
531
+ Deprecation of a few ``py::object`` APIs
532
+ ----------------------------------------
533
+
534
+ All of the old-style calls emit deprecation warnings.
535
+
536
+ +---------------------------------------+---------------------------------------------+
537
+ | Old syntax | New syntax |
538
+ +=======================================+=============================================+
539
+ | ``obj.call(args...)`` | ``obj(args...)`` |
540
+ +---------------------------------------+---------------------------------------------+
541
+ | ``obj.str()`` | ``py::str(obj)`` |
542
+ +---------------------------------------+---------------------------------------------+
543
+ | ``auto l = py::list(obj); l.check()`` | ``py::isinstance<py::list>(obj)`` |
544
+ +---------------------------------------+---------------------------------------------+
545
+ | ``py::object(ptr, true)`` | ``py::reinterpret_borrow<py::object>(ptr)`` |
546
+ +---------------------------------------+---------------------------------------------+
547
+ | ``py::object(ptr, false)`` | ``py::reinterpret_steal<py::object>(ptr)`` |
548
+ +---------------------------------------+---------------------------------------------+
549
+ | ``if (obj.attr("foo"))`` | ``if (py::hasattr(obj, "foo"))`` |
550
+ +---------------------------------------+---------------------------------------------+
551
+ | ``if (obj["bar"])`` | ``if (obj.contains("bar"))`` |
552
+ +---------------------------------------+---------------------------------------------+
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/attr.h ADDED
@@ -0,0 +1,675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/attr.h: Infrastructure for processing custom
3
+ type and function attributes
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "cast.h"
14
+
15
+ #include <functional>
16
+
17
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
18
+
19
+ /// \addtogroup annotations
20
+ /// @{
21
+
22
+ /// Annotation for methods
23
+ struct is_method {
24
+ handle class_;
25
+ explicit is_method(const handle &c) : class_(c) {}
26
+ };
27
+
28
+ /// Annotation for operators
29
+ struct is_operator {};
30
+
31
+ /// Annotation for classes that cannot be subclassed
32
+ struct is_final {};
33
+
34
+ /// Annotation for parent scope
35
+ struct scope {
36
+ handle value;
37
+ explicit scope(const handle &s) : value(s) {}
38
+ };
39
+
40
+ /// Annotation for documentation
41
+ struct doc {
42
+ const char *value;
43
+ explicit doc(const char *value) : value(value) {}
44
+ };
45
+
46
+ /// Annotation for function names
47
+ struct name {
48
+ const char *value;
49
+ explicit name(const char *value) : value(value) {}
50
+ };
51
+
52
+ /// Annotation indicating that a function is an overload associated with a given "sibling"
53
+ struct sibling {
54
+ handle value;
55
+ explicit sibling(const handle &value) : value(value.ptr()) {}
56
+ };
57
+
58
+ /// Annotation indicating that a class derives from another given type
59
+ template <typename T>
60
+ struct base {
61
+
62
+ PYBIND11_DEPRECATED(
63
+ "base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
64
+ base() {} // NOLINT(modernize-use-equals-default): breaks MSVC 2015 when adding an attribute
65
+ };
66
+
67
+ /// Keep patient alive while nurse lives
68
+ template <size_t Nurse, size_t Patient>
69
+ struct keep_alive {};
70
+
71
+ /// Annotation indicating that a class is involved in a multiple inheritance relationship
72
+ struct multiple_inheritance {};
73
+
74
+ /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
75
+ struct dynamic_attr {};
76
+
77
+ /// Annotation which enables the buffer protocol for a type
78
+ struct buffer_protocol {};
79
+
80
+ /// Annotation which requests that a special metaclass is created for a type
81
+ struct metaclass {
82
+ handle value;
83
+
84
+ PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
85
+ // NOLINTNEXTLINE(modernize-use-equals-default): breaks MSVC 2015 when adding an attribute
86
+ metaclass() {}
87
+
88
+ /// Override pybind11's default metaclass
89
+ explicit metaclass(handle value) : value(value) {}
90
+ };
91
+
92
+ /// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that
93
+ /// may be used to customize the Python type.
94
+ ///
95
+ /// The callback is invoked immediately before `PyType_Ready`.
96
+ ///
97
+ /// Note: This is an advanced interface, and uses of it may require changes to
98
+ /// work with later versions of pybind11. You may wish to consult the
99
+ /// implementation of `make_new_python_type` in `detail/classes.h` to understand
100
+ /// the context in which the callback will be run.
101
+ struct custom_type_setup {
102
+ using callback = std::function<void(PyHeapTypeObject *heap_type)>;
103
+
104
+ explicit custom_type_setup(callback value) : value(std::move(value)) {}
105
+
106
+ callback value;
107
+ };
108
+
109
+ /// Annotation that marks a class as local to the module:
110
+ struct module_local {
111
+ const bool value;
112
+ constexpr explicit module_local(bool v = true) : value(v) {}
113
+ };
114
+
115
+ /// Annotation to mark enums as an arithmetic type
116
+ struct arithmetic {};
117
+
118
+ /// Mark a function for addition at the beginning of the existing overload chain instead of the end
119
+ struct prepend {};
120
+
121
+ /** \rst
122
+ A call policy which places one or more guard variables (``Ts...``) around the function call.
123
+
124
+ For example, this definition:
125
+
126
+ .. code-block:: cpp
127
+
128
+ m.def("foo", foo, py::call_guard<T>());
129
+
130
+ is equivalent to the following pseudocode:
131
+
132
+ .. code-block:: cpp
133
+
134
+ m.def("foo", [](args...) {
135
+ T scope_guard;
136
+ return foo(args...); // forwarded arguments
137
+ });
138
+ \endrst */
139
+ template <typename... Ts>
140
+ struct call_guard;
141
+
142
+ template <>
143
+ struct call_guard<> {
144
+ using type = detail::void_type;
145
+ };
146
+
147
+ template <typename T>
148
+ struct call_guard<T> {
149
+ static_assert(std::is_default_constructible<T>::value,
150
+ "The guard type must be default constructible");
151
+
152
+ using type = T;
153
+ };
154
+
155
+ template <typename T, typename... Ts>
156
+ struct call_guard<T, Ts...> {
157
+ struct type {
158
+ T guard{}; // Compose multiple guard types with left-to-right default-constructor order
159
+ typename call_guard<Ts...>::type next{};
160
+ };
161
+ };
162
+
163
+ /// @} annotations
164
+
165
+ PYBIND11_NAMESPACE_BEGIN(detail)
166
+ /* Forward declarations */
167
+ enum op_id : int;
168
+ enum op_type : int;
169
+ struct undefined_t;
170
+ template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t>
171
+ struct op_;
172
+ void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
173
+
174
+ /// Internal data structure which holds metadata about a keyword argument
175
+ struct argument_record {
176
+ const char *name; ///< Argument name
177
+ const char *descr; ///< Human-readable version of the argument value
178
+ handle value; ///< Associated Python object
179
+ bool convert : 1; ///< True if the argument is allowed to convert when loading
180
+ bool none : 1; ///< True if None is allowed when loading
181
+
182
+ argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
183
+ : name(name), descr(descr), value(value), convert(convert), none(none) {}
184
+ };
185
+
186
+ /// Internal data structure which holds metadata about a bound function (signature, overloads,
187
+ /// etc.)
188
+ struct function_record {
189
+ function_record()
190
+ : is_constructor(false), is_new_style_constructor(false), is_stateless(false),
191
+ is_operator(false), is_method(false), has_args(false), has_kwargs(false),
192
+ prepend(false) {}
193
+
194
+ /// Function name
195
+ char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
196
+
197
+ // User-specified documentation string
198
+ char *doc = nullptr;
199
+
200
+ /// Human-readable version of the function signature
201
+ char *signature = nullptr;
202
+
203
+ /// List of registered keyword arguments
204
+ std::vector<argument_record> args;
205
+
206
+ /// Pointer to lambda function which converts arguments and performs the actual call
207
+ handle (*impl)(function_call &) = nullptr;
208
+
209
+ /// Storage for the wrapped function pointer and captured data, if any
210
+ void *data[3] = {};
211
+
212
+ /// Pointer to custom destructor for 'data' (if needed)
213
+ void (*free_data)(function_record *ptr) = nullptr;
214
+
215
+ /// Return value policy associated with this function
216
+ return_value_policy policy = return_value_policy::automatic;
217
+
218
+ /// True if name == '__init__'
219
+ bool is_constructor : 1;
220
+
221
+ /// True if this is a new-style `__init__` defined in `detail/init.h`
222
+ bool is_new_style_constructor : 1;
223
+
224
+ /// True if this is a stateless function pointer
225
+ bool is_stateless : 1;
226
+
227
+ /// True if this is an operator (__add__), etc.
228
+ bool is_operator : 1;
229
+
230
+ /// True if this is a method
231
+ bool is_method : 1;
232
+
233
+ /// True if the function has a '*args' argument
234
+ bool has_args : 1;
235
+
236
+ /// True if the function has a '**kwargs' argument
237
+ bool has_kwargs : 1;
238
+
239
+ /// True if this function is to be inserted at the beginning of the overload resolution chain
240
+ bool prepend : 1;
241
+
242
+ /// Number of arguments (including py::args and/or py::kwargs, if present)
243
+ std::uint16_t nargs;
244
+
245
+ /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs
246
+ /// argument or by a py::kw_only annotation.
247
+ std::uint16_t nargs_pos = 0;
248
+
249
+ /// Number of leading arguments (counted in `nargs`) that are positional-only
250
+ std::uint16_t nargs_pos_only = 0;
251
+
252
+ /// Python method object
253
+ PyMethodDef *def = nullptr;
254
+
255
+ /// Python handle to the parent scope (a class or a module)
256
+ handle scope;
257
+
258
+ /// Python handle to the sibling function representing an overload chain
259
+ handle sibling;
260
+
261
+ /// Pointer to next overload
262
+ function_record *next = nullptr;
263
+ };
264
+
265
+ /// Special data structure which (temporarily) holds metadata about a bound class
266
+ struct type_record {
267
+ PYBIND11_NOINLINE type_record()
268
+ : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),
269
+ default_holder(true), module_local(false), is_final(false) {}
270
+
271
+ /// Handle to the parent scope
272
+ handle scope;
273
+
274
+ /// Name of the class
275
+ const char *name = nullptr;
276
+
277
+ // Pointer to RTTI type_info data structure
278
+ const std::type_info *type = nullptr;
279
+
280
+ /// How large is the underlying C++ type?
281
+ size_t type_size = 0;
282
+
283
+ /// What is the alignment of the underlying C++ type?
284
+ size_t type_align = 0;
285
+
286
+ /// How large is the type's holder?
287
+ size_t holder_size = 0;
288
+
289
+ /// The global operator new can be overridden with a class-specific variant
290
+ void *(*operator_new)(size_t) = nullptr;
291
+
292
+ /// Function pointer to class_<..>::init_instance
293
+ void (*init_instance)(instance *, const void *) = nullptr;
294
+
295
+ /// Function pointer to class_<..>::dealloc
296
+ void (*dealloc)(detail::value_and_holder &) = nullptr;
297
+
298
+ /// List of base classes of the newly created type
299
+ list bases;
300
+
301
+ /// Optional docstring
302
+ const char *doc = nullptr;
303
+
304
+ /// Custom metaclass (optional)
305
+ handle metaclass;
306
+
307
+ /// Custom type setup.
308
+ custom_type_setup::callback custom_type_setup_callback;
309
+
310
+ /// Multiple inheritance marker
311
+ bool multiple_inheritance : 1;
312
+
313
+ /// Does the class manage a __dict__?
314
+ bool dynamic_attr : 1;
315
+
316
+ /// Does the class implement the buffer protocol?
317
+ bool buffer_protocol : 1;
318
+
319
+ /// Is the default (unique_ptr) holder type used?
320
+ bool default_holder : 1;
321
+
322
+ /// Is the class definition local to the module shared object?
323
+ bool module_local : 1;
324
+
325
+ /// Is the class inheritable from python classes?
326
+ bool is_final : 1;
327
+
328
+ PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) {
329
+ auto *base_info = detail::get_type_info(base, false);
330
+ if (!base_info) {
331
+ std::string tname(base.name());
332
+ detail::clean_type_id(tname);
333
+ pybind11_fail("generic_type: type \"" + std::string(name)
334
+ + "\" referenced unknown base type \"" + tname + "\"");
335
+ }
336
+
337
+ if (default_holder != base_info->default_holder) {
338
+ std::string tname(base.name());
339
+ detail::clean_type_id(tname);
340
+ pybind11_fail("generic_type: type \"" + std::string(name) + "\" "
341
+ + (default_holder ? "does not have" : "has")
342
+ + " a non-default holder type while its base \"" + tname + "\" "
343
+ + (base_info->default_holder ? "does not" : "does"));
344
+ }
345
+
346
+ bases.append((PyObject *) base_info->type);
347
+
348
+ if (base_info->type->tp_dictoffset != 0) {
349
+ dynamic_attr = true;
350
+ }
351
+
352
+ if (caster) {
353
+ base_info->implicit_casts.emplace_back(type, caster);
354
+ }
355
+ }
356
+ };
357
+
358
+ inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) {
359
+ args.reserve(f.nargs);
360
+ args_convert.reserve(f.nargs);
361
+ }
362
+
363
+ /// Tag for a new-style `__init__` defined in `detail/init.h`
364
+ struct is_new_style_constructor {};
365
+
366
+ /**
367
+ * Partial template specializations to process custom attributes provided to
368
+ * cpp_function_ and class_. These are either used to initialize the respective
369
+ * fields in the type_record and function_record data structures or executed at
370
+ * runtime to deal with custom call policies (e.g. keep_alive).
371
+ */
372
+ template <typename T, typename SFINAE = void>
373
+ struct process_attribute;
374
+
375
+ template <typename T>
376
+ struct process_attribute_default {
377
+ /// Default implementation: do nothing
378
+ static void init(const T &, function_record *) {}
379
+ static void init(const T &, type_record *) {}
380
+ static void precall(function_call &) {}
381
+ static void postcall(function_call &, handle) {}
382
+ };
383
+
384
+ /// Process an attribute specifying the function's name
385
+ template <>
386
+ struct process_attribute<name> : process_attribute_default<name> {
387
+ static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
388
+ };
389
+
390
+ /// Process an attribute specifying the function's docstring
391
+ template <>
392
+ struct process_attribute<doc> : process_attribute_default<doc> {
393
+ static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
394
+ };
395
+
396
+ /// Process an attribute specifying the function's docstring (provided as a C-style string)
397
+ template <>
398
+ struct process_attribute<const char *> : process_attribute_default<const char *> {
399
+ static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
400
+ static void init(const char *d, type_record *r) { r->doc = const_cast<char *>(d); }
401
+ };
402
+ template <>
403
+ struct process_attribute<char *> : process_attribute<const char *> {};
404
+
405
+ /// Process an attribute indicating the function's return value policy
406
+ template <>
407
+ struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
408
+ static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
409
+ };
410
+
411
+ /// Process an attribute which indicates that this is an overloaded function associated with a
412
+ /// given sibling
413
+ template <>
414
+ struct process_attribute<sibling> : process_attribute_default<sibling> {
415
+ static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
416
+ };
417
+
418
+ /// Process an attribute which indicates that this function is a method
419
+ template <>
420
+ struct process_attribute<is_method> : process_attribute_default<is_method> {
421
+ static void init(const is_method &s, function_record *r) {
422
+ r->is_method = true;
423
+ r->scope = s.class_;
424
+ }
425
+ };
426
+
427
+ /// Process an attribute which indicates the parent scope of a method
428
+ template <>
429
+ struct process_attribute<scope> : process_attribute_default<scope> {
430
+ static void init(const scope &s, function_record *r) { r->scope = s.value; }
431
+ };
432
+
433
+ /// Process an attribute which indicates that this function is an operator
434
+ template <>
435
+ struct process_attribute<is_operator> : process_attribute_default<is_operator> {
436
+ static void init(const is_operator &, function_record *r) { r->is_operator = true; }
437
+ };
438
+
439
+ template <>
440
+ struct process_attribute<is_new_style_constructor>
441
+ : process_attribute_default<is_new_style_constructor> {
442
+ static void init(const is_new_style_constructor &, function_record *r) {
443
+ r->is_new_style_constructor = true;
444
+ }
445
+ };
446
+
447
+ inline void check_kw_only_arg(const arg &a, function_record *r) {
448
+ if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) {
449
+ pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or "
450
+ "args() argument");
451
+ }
452
+ }
453
+
454
+ inline void append_self_arg_if_needed(function_record *r) {
455
+ if (r->is_method && r->args.empty()) {
456
+ r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false);
457
+ }
458
+ }
459
+
460
+ /// Process a keyword argument attribute (*without* a default value)
461
+ template <>
462
+ struct process_attribute<arg> : process_attribute_default<arg> {
463
+ static void init(const arg &a, function_record *r) {
464
+ append_self_arg_if_needed(r);
465
+ r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
466
+
467
+ check_kw_only_arg(a, r);
468
+ }
469
+ };
470
+
471
+ /// Process a keyword argument attribute (*with* a default value)
472
+ template <>
473
+ struct process_attribute<arg_v> : process_attribute_default<arg_v> {
474
+ static void init(const arg_v &a, function_record *r) {
475
+ if (r->is_method && r->args.empty()) {
476
+ r->args.emplace_back(
477
+ "self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false);
478
+ }
479
+
480
+ if (!a.value) {
481
+ #if !defined(NDEBUG)
482
+ std::string descr("'");
483
+ if (a.name) {
484
+ descr += std::string(a.name) + ": ";
485
+ }
486
+ descr += a.type + "'";
487
+ if (r->is_method) {
488
+ if (r->name) {
489
+ descr += " in method '" + (std::string) str(r->scope) + "."
490
+ + (std::string) r->name + "'";
491
+ } else {
492
+ descr += " in method of '" + (std::string) str(r->scope) + "'";
493
+ }
494
+ } else if (r->name) {
495
+ descr += " in function '" + (std::string) r->name + "'";
496
+ }
497
+ pybind11_fail("arg(): could not convert default argument " + descr
498
+ + " into a Python object (type not registered yet?)");
499
+ #else
500
+ pybind11_fail("arg(): could not convert default argument "
501
+ "into a Python object (type not registered yet?). "
502
+ "Compile in debug mode for more information.");
503
+ #endif
504
+ }
505
+ r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
506
+
507
+ check_kw_only_arg(a, r);
508
+ }
509
+ };
510
+
511
+ /// Process a keyword-only-arguments-follow pseudo argument
512
+ template <>
513
+ struct process_attribute<kw_only> : process_attribute_default<kw_only> {
514
+ static void init(const kw_only &, function_record *r) {
515
+ append_self_arg_if_needed(r);
516
+ if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) {
517
+ pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative "
518
+ "argument location (or omit kw_only() entirely)");
519
+ }
520
+ r->nargs_pos = static_cast<std::uint16_t>(r->args.size());
521
+ }
522
+ };
523
+
524
+ /// Process a positional-only-argument maker
525
+ template <>
526
+ struct process_attribute<pos_only> : process_attribute_default<pos_only> {
527
+ static void init(const pos_only &, function_record *r) {
528
+ append_self_arg_if_needed(r);
529
+ r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
530
+ if (r->nargs_pos_only > r->nargs_pos) {
531
+ pybind11_fail("pos_only(): cannot follow a py::args() argument");
532
+ }
533
+ // It also can't follow a kw_only, but a static_assert in pybind11.h checks that
534
+ }
535
+ };
536
+
537
+ /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees
538
+ /// that)
539
+ template <typename T>
540
+ struct process_attribute<T, enable_if_t<is_pyobject<T>::value>>
541
+ : process_attribute_default<handle> {
542
+ static void init(const handle &h, type_record *r) { r->bases.append(h); }
543
+ };
544
+
545
+ /// Process a parent class attribute (deprecated, does not support multiple inheritance)
546
+ template <typename T>
547
+ struct process_attribute<base<T>> : process_attribute_default<base<T>> {
548
+ static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
549
+ };
550
+
551
+ /// Process a multiple inheritance attribute
552
+ template <>
553
+ struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
554
+ static void init(const multiple_inheritance &, type_record *r) {
555
+ r->multiple_inheritance = true;
556
+ }
557
+ };
558
+
559
+ template <>
560
+ struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
561
+ static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
562
+ };
563
+
564
+ template <>
565
+ struct process_attribute<custom_type_setup> {
566
+ static void init(const custom_type_setup &value, type_record *r) {
567
+ r->custom_type_setup_callback = value.value;
568
+ }
569
+ };
570
+
571
+ template <>
572
+ struct process_attribute<is_final> : process_attribute_default<is_final> {
573
+ static void init(const is_final &, type_record *r) { r->is_final = true; }
574
+ };
575
+
576
+ template <>
577
+ struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
578
+ static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
579
+ };
580
+
581
+ template <>
582
+ struct process_attribute<metaclass> : process_attribute_default<metaclass> {
583
+ static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
584
+ };
585
+
586
+ template <>
587
+ struct process_attribute<module_local> : process_attribute_default<module_local> {
588
+ static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
589
+ };
590
+
591
+ /// Process a 'prepend' attribute, putting this at the beginning of the overload chain
592
+ template <>
593
+ struct process_attribute<prepend> : process_attribute_default<prepend> {
594
+ static void init(const prepend &, function_record *r) { r->prepend = true; }
595
+ };
596
+
597
+ /// Process an 'arithmetic' attribute for enums (does nothing here)
598
+ template <>
599
+ struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
600
+
601
+ template <typename... Ts>
602
+ struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {};
603
+
604
+ /**
605
+ * Process a keep_alive call policy -- invokes keep_alive_impl during the
606
+ * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
607
+ * otherwise
608
+ */
609
+ template <size_t Nurse, size_t Patient>
610
+ struct process_attribute<keep_alive<Nurse, Patient>>
611
+ : public process_attribute_default<keep_alive<Nurse, Patient>> {
612
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
613
+ static void precall(function_call &call) {
614
+ keep_alive_impl(Nurse, Patient, call, handle());
615
+ }
616
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
617
+ static void postcall(function_call &, handle) {}
618
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
619
+ static void precall(function_call &) {}
620
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
621
+ static void postcall(function_call &call, handle ret) {
622
+ keep_alive_impl(Nurse, Patient, call, ret);
623
+ }
624
+ };
625
+
626
+ /// Recursively iterate over variadic template arguments
627
+ template <typename... Args>
628
+ struct process_attributes {
629
+ static void init(const Args &...args, function_record *r) {
630
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
631
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
632
+ using expander = int[];
633
+ (void) expander{
634
+ 0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
635
+ }
636
+ static void init(const Args &...args, type_record *r) {
637
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
638
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
639
+ using expander = int[];
640
+ (void) expander{0,
641
+ (process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
642
+ }
643
+ static void precall(function_call &call) {
644
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call);
645
+ using expander = int[];
646
+ (void) expander{0,
647
+ (process_attribute<typename std::decay<Args>::type>::precall(call), 0)...};
648
+ }
649
+ static void postcall(function_call &call, handle fn_ret) {
650
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret);
651
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret);
652
+ using expander = int[];
653
+ (void) expander{
654
+ 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...};
655
+ }
656
+ };
657
+
658
+ template <typename T>
659
+ using is_call_guard = is_instantiation<call_guard, T>;
660
+
661
+ /// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
662
+ template <typename... Extra>
663
+ using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
664
+
665
+ /// Check the number of named arguments at compile time
666
+ template <typename... Extra,
667
+ size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
668
+ size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
669
+ constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
670
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);
671
+ return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs;
672
+ }
673
+
674
+ PYBIND11_NAMESPACE_END(detail)
675
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/buffer_info.h ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/buffer_info.h: Python buffer object interface
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "detail/common.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+
16
+ PYBIND11_NAMESPACE_BEGIN(detail)
17
+
18
+ // Default, C-style strides
19
+ inline std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
20
+ auto ndim = shape.size();
21
+ std::vector<ssize_t> strides(ndim, itemsize);
22
+ if (ndim > 0) {
23
+ for (size_t i = ndim - 1; i > 0; --i) {
24
+ strides[i - 1] = strides[i] * shape[i];
25
+ }
26
+ }
27
+ return strides;
28
+ }
29
+
30
+ // F-style strides; default when constructing an array_t with `ExtraFlags & f_style`
31
+ inline std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
32
+ auto ndim = shape.size();
33
+ std::vector<ssize_t> strides(ndim, itemsize);
34
+ for (size_t i = 1; i < ndim; ++i) {
35
+ strides[i] = strides[i - 1] * shape[i - 1];
36
+ }
37
+ return strides;
38
+ }
39
+
40
+ PYBIND11_NAMESPACE_END(detail)
41
+
42
+ /// Information record describing a Python buffer object
43
+ struct buffer_info {
44
+ void *ptr = nullptr; // Pointer to the underlying storage
45
+ ssize_t itemsize = 0; // Size of individual items in bytes
46
+ ssize_t size = 0; // Total number of entries
47
+ std::string format; // For homogeneous buffers, this should be set to
48
+ // format_descriptor<T>::format()
49
+ ssize_t ndim = 0; // Number of dimensions
50
+ std::vector<ssize_t> shape; // Shape of the tensor (1 entry per dimension)
51
+ std::vector<ssize_t> strides; // Number of bytes between adjacent entries
52
+ // (for each per dimension)
53
+ bool readonly = false; // flag to indicate if the underlying storage may be written to
54
+
55
+ buffer_info() = default;
56
+
57
+ buffer_info(void *ptr,
58
+ ssize_t itemsize,
59
+ const std::string &format,
60
+ ssize_t ndim,
61
+ detail::any_container<ssize_t> shape_in,
62
+ detail::any_container<ssize_t> strides_in,
63
+ bool readonly = false)
64
+ : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim),
65
+ shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) {
66
+ if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size()) {
67
+ pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length");
68
+ }
69
+ for (size_t i = 0; i < (size_t) ndim; ++i) {
70
+ size *= shape[i];
71
+ }
72
+ }
73
+
74
+ template <typename T>
75
+ buffer_info(T *ptr,
76
+ detail::any_container<ssize_t> shape_in,
77
+ detail::any_container<ssize_t> strides_in,
78
+ bool readonly = false)
79
+ : buffer_info(private_ctr_tag(),
80
+ ptr,
81
+ sizeof(T),
82
+ format_descriptor<T>::format(),
83
+ static_cast<ssize_t>(shape_in->size()),
84
+ std::move(shape_in),
85
+ std::move(strides_in),
86
+ readonly) {}
87
+
88
+ buffer_info(void *ptr,
89
+ ssize_t itemsize,
90
+ const std::string &format,
91
+ ssize_t size,
92
+ bool readonly = false)
93
+ : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) {}
94
+
95
+ template <typename T>
96
+ buffer_info(T *ptr, ssize_t size, bool readonly = false)
97
+ : buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size, readonly) {}
98
+
99
+ template <typename T>
100
+ buffer_info(const T *ptr, ssize_t size, bool readonly = true)
101
+ : buffer_info(
102
+ const_cast<T *>(ptr), sizeof(T), format_descriptor<T>::format(), size, readonly) {}
103
+
104
+ explicit buffer_info(Py_buffer *view, bool ownview = true)
105
+ : buffer_info(
106
+ view->buf,
107
+ view->itemsize,
108
+ view->format,
109
+ view->ndim,
110
+ {view->shape, view->shape + view->ndim},
111
+ /* Though buffer::request() requests PyBUF_STRIDES, ctypes objects
112
+ * ignore this flag and return a view with NULL strides.
113
+ * When strides are NULL, build them manually. */
114
+ view->strides
115
+ ? std::vector<ssize_t>(view->strides, view->strides + view->ndim)
116
+ : detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize),
117
+ (view->readonly != 0)) {
118
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
119
+ this->m_view = view;
120
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
121
+ this->ownview = ownview;
122
+ }
123
+
124
+ buffer_info(const buffer_info &) = delete;
125
+ buffer_info &operator=(const buffer_info &) = delete;
126
+
127
+ buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); }
128
+
129
+ buffer_info &operator=(buffer_info &&rhs) noexcept {
130
+ ptr = rhs.ptr;
131
+ itemsize = rhs.itemsize;
132
+ size = rhs.size;
133
+ format = std::move(rhs.format);
134
+ ndim = rhs.ndim;
135
+ shape = std::move(rhs.shape);
136
+ strides = std::move(rhs.strides);
137
+ std::swap(m_view, rhs.m_view);
138
+ std::swap(ownview, rhs.ownview);
139
+ readonly = rhs.readonly;
140
+ return *this;
141
+ }
142
+
143
+ ~buffer_info() {
144
+ if (m_view && ownview) {
145
+ PyBuffer_Release(m_view);
146
+ delete m_view;
147
+ }
148
+ }
149
+
150
+ Py_buffer *view() const { return m_view; }
151
+ Py_buffer *&view() { return m_view; }
152
+
153
+ private:
154
+ struct private_ctr_tag {};
155
+
156
+ buffer_info(private_ctr_tag,
157
+ void *ptr,
158
+ ssize_t itemsize,
159
+ const std::string &format,
160
+ ssize_t ndim,
161
+ detail::any_container<ssize_t> &&shape_in,
162
+ detail::any_container<ssize_t> &&strides_in,
163
+ bool readonly)
164
+ : buffer_info(
165
+ ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) {}
166
+
167
+ Py_buffer *m_view = nullptr;
168
+ bool ownview = false;
169
+ };
170
+
171
+ PYBIND11_NAMESPACE_BEGIN(detail)
172
+
173
+ template <typename T, typename SFINAE = void>
174
+ struct compare_buffer_info {
175
+ static bool compare(const buffer_info &b) {
176
+ return b.format == format_descriptor<T>::format() && b.itemsize == (ssize_t) sizeof(T);
177
+ }
178
+ };
179
+
180
+ template <typename T>
181
+ struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
182
+ static bool compare(const buffer_info &b) {
183
+ return (size_t) b.itemsize == sizeof(T)
184
+ && (b.format == format_descriptor<T>::value
185
+ || ((sizeof(T) == sizeof(long))
186
+ && b.format == (std::is_unsigned<T>::value ? "L" : "l"))
187
+ || ((sizeof(T) == sizeof(size_t))
188
+ && b.format == (std::is_unsigned<T>::value ? "N" : "n")));
189
+ }
190
+ };
191
+
192
+ PYBIND11_NAMESPACE_END(detail)
193
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/cast.h ADDED
@@ -0,0 +1,1663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/cast.h: Partial template specializations to cast between
3
+ C++ and Python types
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "detail/common.h"
14
+ #include "detail/descr.h"
15
+ #include "detail/type_caster_base.h"
16
+ #include "detail/typeid.h"
17
+ #include "pytypes.h"
18
+
19
+ #include <array>
20
+ #include <cstring>
21
+ #include <functional>
22
+ #include <iosfwd>
23
+ #include <iterator>
24
+ #include <memory>
25
+ #include <string>
26
+ #include <tuple>
27
+ #include <type_traits>
28
+ #include <utility>
29
+ #include <vector>
30
+
31
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
32
+ PYBIND11_NAMESPACE_BEGIN(detail)
33
+
34
+ template <typename type, typename SFINAE = void>
35
+ class type_caster : public type_caster_base<type> {};
36
+ template <typename type>
37
+ using make_caster = type_caster<intrinsic_t<type>>;
38
+
39
+ // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
40
+ template <typename T>
41
+ typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
42
+ return caster.operator typename make_caster<T>::template cast_op_type<T>();
43
+ }
44
+ template <typename T>
45
+ typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
46
+ cast_op(make_caster<T> &&caster) {
47
+ return std::move(caster).operator typename make_caster<T>::
48
+ template cast_op_type<typename std::add_rvalue_reference<T>::type>();
49
+ }
50
+
51
+ template <typename type>
52
+ class type_caster<std::reference_wrapper<type>> {
53
+ private:
54
+ using caster_t = make_caster<type>;
55
+ caster_t subcaster;
56
+ using reference_t = type &;
57
+ using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
58
+
59
+ static_assert(
60
+ std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
61
+ || std::is_same<reference_t, subcaster_cast_op_type>::value,
62
+ "std::reference_wrapper<T> caster requires T to have a caster with an "
63
+ "`operator T &()` or `operator const T &()`");
64
+
65
+ public:
66
+ bool load(handle src, bool convert) { return subcaster.load(src, convert); }
67
+ static constexpr auto name = caster_t::name;
68
+ static handle
69
+ cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
70
+ // It is definitely wrong to take ownership of this pointer, so mask that rvp
71
+ if (policy == return_value_policy::take_ownership
72
+ || policy == return_value_policy::automatic) {
73
+ policy = return_value_policy::automatic_reference;
74
+ }
75
+ return caster_t::cast(&src.get(), policy, parent);
76
+ }
77
+ template <typename T>
78
+ using cast_op_type = std::reference_wrapper<type>;
79
+ explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
80
+ };
81
+
82
+ #define PYBIND11_TYPE_CASTER(type, py_name) \
83
+ protected: \
84
+ type value; \
85
+ \
86
+ public: \
87
+ static constexpr auto name = py_name; \
88
+ template <typename T_, \
89
+ ::pybind11::detail::enable_if_t< \
90
+ std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
91
+ int> = 0> \
92
+ static ::pybind11::handle cast( \
93
+ T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
94
+ if (!src) \
95
+ return ::pybind11::none().release(); \
96
+ if (policy == ::pybind11::return_value_policy::take_ownership) { \
97
+ auto h = cast(std::move(*src), policy, parent); \
98
+ delete src; \
99
+ return h; \
100
+ } \
101
+ return cast(*src, policy, parent); \
102
+ } \
103
+ operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \
104
+ operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \
105
+ operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \
106
+ template <typename T_> \
107
+ using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
108
+
109
+ template <typename CharT>
110
+ using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
111
+ #if defined(PYBIND11_HAS_U8STRING)
112
+ std::is_same<CharT, char8_t>, /* std::u8string */
113
+ #endif
114
+ std::is_same<CharT, char16_t>, /* std::u16string */
115
+ std::is_same<CharT, char32_t>, /* std::u32string */
116
+ std::is_same<CharT, wchar_t> /* std::wstring */
117
+ >;
118
+
119
+ template <typename T>
120
+ struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
121
+ using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
122
+ using _py_type_1 = conditional_t<std::is_signed<T>::value,
123
+ _py_type_0,
124
+ typename std::make_unsigned<_py_type_0>::type>;
125
+ using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
126
+
127
+ public:
128
+ bool load(handle src, bool convert) {
129
+ py_type py_value;
130
+
131
+ if (!src) {
132
+ return false;
133
+ }
134
+
135
+ #if !defined(PYPY_VERSION)
136
+ auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
137
+ #else
138
+ // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
139
+ // while CPython only considers the existence of `nb_index`/`__index__`.
140
+ auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
141
+ #endif
142
+
143
+ if (std::is_floating_point<T>::value) {
144
+ if (convert || PyFloat_Check(src.ptr())) {
145
+ py_value = (py_type) PyFloat_AsDouble(src.ptr());
146
+ } else {
147
+ return false;
148
+ }
149
+ } else if (PyFloat_Check(src.ptr())
150
+ || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
151
+ return false;
152
+ } else {
153
+ handle src_or_index = src;
154
+ // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
155
+ #if PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
156
+ object index;
157
+ if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
158
+ index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
159
+ if (!index) {
160
+ PyErr_Clear();
161
+ if (!convert)
162
+ return false;
163
+ } else {
164
+ src_or_index = index;
165
+ }
166
+ }
167
+ #endif
168
+ if (std::is_unsigned<py_type>::value) {
169
+ py_value = as_unsigned<py_type>(src_or_index.ptr());
170
+ } else { // signed integer:
171
+ py_value = sizeof(T) <= sizeof(long)
172
+ ? (py_type) PyLong_AsLong(src_or_index.ptr())
173
+ : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
174
+ }
175
+ }
176
+
177
+ // Python API reported an error
178
+ bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
179
+
180
+ // Check to see if the conversion is valid (integers should match exactly)
181
+ // Signed/unsigned checks happen elsewhere
182
+ if (py_err
183
+ || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
184
+ && py_value != (py_type) (T) py_value)) {
185
+ PyErr_Clear();
186
+ if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
187
+ auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
188
+ ? PyNumber_Float(src.ptr())
189
+ : PyNumber_Long(src.ptr()));
190
+ PyErr_Clear();
191
+ return load(tmp, false);
192
+ }
193
+ return false;
194
+ }
195
+
196
+ value = (T) py_value;
197
+ return true;
198
+ }
199
+
200
+ template <typename U = T>
201
+ static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
202
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
203
+ return PyFloat_FromDouble((double) src);
204
+ }
205
+
206
+ template <typename U = T>
207
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
208
+ && (sizeof(U) <= sizeof(long)),
209
+ handle>::type
210
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
211
+ return PYBIND11_LONG_FROM_SIGNED((long) src);
212
+ }
213
+
214
+ template <typename U = T>
215
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
216
+ && (sizeof(U) <= sizeof(unsigned long)),
217
+ handle>::type
218
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
219
+ return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
220
+ }
221
+
222
+ template <typename U = T>
223
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
224
+ && (sizeof(U) > sizeof(long)),
225
+ handle>::type
226
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
227
+ return PyLong_FromLongLong((long long) src);
228
+ }
229
+
230
+ template <typename U = T>
231
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
232
+ && (sizeof(U) > sizeof(unsigned long)),
233
+ handle>::type
234
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
235
+ return PyLong_FromUnsignedLongLong((unsigned long long) src);
236
+ }
237
+
238
+ PYBIND11_TYPE_CASTER(T, const_name<std::is_integral<T>::value>("int", "float"));
239
+ };
240
+
241
+ template <typename T>
242
+ struct void_caster {
243
+ public:
244
+ bool load(handle src, bool) {
245
+ if (src && src.is_none()) {
246
+ return true;
247
+ }
248
+ return false;
249
+ }
250
+ static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
251
+ return none().inc_ref();
252
+ }
253
+ PYBIND11_TYPE_CASTER(T, const_name("None"));
254
+ };
255
+
256
+ template <>
257
+ class type_caster<void_type> : public void_caster<void_type> {};
258
+
259
+ template <>
260
+ class type_caster<void> : public type_caster<void_type> {
261
+ public:
262
+ using type_caster<void_type>::cast;
263
+
264
+ bool load(handle h, bool) {
265
+ if (!h) {
266
+ return false;
267
+ }
268
+ if (h.is_none()) {
269
+ value = nullptr;
270
+ return true;
271
+ }
272
+
273
+ /* Check if this is a capsule */
274
+ if (isinstance<capsule>(h)) {
275
+ value = reinterpret_borrow<capsule>(h);
276
+ return true;
277
+ }
278
+
279
+ /* Check if this is a C++ type */
280
+ const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
281
+ if (bases.size() == 1) { // Only allowing loading from a single-value type
282
+ value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
283
+ return true;
284
+ }
285
+
286
+ /* Fail */
287
+ return false;
288
+ }
289
+
290
+ static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
291
+ if (ptr) {
292
+ return capsule(ptr).release();
293
+ }
294
+ return none().inc_ref();
295
+ }
296
+
297
+ template <typename T>
298
+ using cast_op_type = void *&;
299
+ explicit operator void *&() { return value; }
300
+ static constexpr auto name = const_name("capsule");
301
+
302
+ private:
303
+ void *value = nullptr;
304
+ };
305
+
306
+ template <>
307
+ class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
308
+
309
+ template <>
310
+ class type_caster<bool> {
311
+ public:
312
+ bool load(handle src, bool convert) {
313
+ if (!src) {
314
+ return false;
315
+ }
316
+ if (src.ptr() == Py_True) {
317
+ value = true;
318
+ return true;
319
+ }
320
+ if (src.ptr() == Py_False) {
321
+ value = false;
322
+ return true;
323
+ }
324
+ if (convert || (std::strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name) == 0)) {
325
+ // (allow non-implicit conversion for numpy booleans)
326
+
327
+ Py_ssize_t res = -1;
328
+ if (src.is_none()) {
329
+ res = 0; // None is implicitly converted to False
330
+ }
331
+ #if defined(PYPY_VERSION)
332
+ // On PyPy, check that "__bool__" (or "__nonzero__" on Python 2.7) attr exists
333
+ else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
334
+ res = PyObject_IsTrue(src.ptr());
335
+ }
336
+ #else
337
+ // Alternate approach for CPython: this does the same as the above, but optimized
338
+ // using the CPython API so as to avoid an unneeded attribute lookup.
339
+ else if (auto *tp_as_number = src.ptr()->ob_type->tp_as_number) {
340
+ if (PYBIND11_NB_BOOL(tp_as_number)) {
341
+ res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
342
+ }
343
+ }
344
+ #endif
345
+ if (res == 0 || res == 1) {
346
+ value = (res != 0);
347
+ return true;
348
+ }
349
+ PyErr_Clear();
350
+ }
351
+ return false;
352
+ }
353
+ static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
354
+ return handle(src ? Py_True : Py_False).inc_ref();
355
+ }
356
+ PYBIND11_TYPE_CASTER(bool, const_name("bool"));
357
+ };
358
+
359
+ // Helper class for UTF-{8,16,32} C++ stl strings:
360
+ template <typename StringType, bool IsView = false>
361
+ struct string_caster {
362
+ using CharT = typename StringType::value_type;
363
+
364
+ // Simplify life by being able to assume standard char sizes (the standard only guarantees
365
+ // minimums, but Python requires exact sizes)
366
+ static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
367
+ "Unsupported char size != 1");
368
+ #if defined(PYBIND11_HAS_U8STRING)
369
+ static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
370
+ "Unsupported char8_t size != 1");
371
+ #endif
372
+ static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
373
+ "Unsupported char16_t size != 2");
374
+ static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
375
+ "Unsupported char32_t size != 4");
376
+ // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
377
+ static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
378
+ "Unsupported wchar_t size != 2/4");
379
+ static constexpr size_t UTF_N = 8 * sizeof(CharT);
380
+
381
+ bool load(handle src, bool) {
382
+ #if PY_MAJOR_VERSION < 3
383
+ object temp;
384
+ #endif
385
+ handle load_src = src;
386
+ if (!src) {
387
+ return false;
388
+ }
389
+ if (!PyUnicode_Check(load_src.ptr())) {
390
+ #if PY_MAJOR_VERSION >= 3
391
+ return load_bytes(load_src);
392
+ #else
393
+ if (std::is_same<CharT, char>::value) {
394
+ return load_bytes(load_src);
395
+ }
396
+
397
+ // The below is a guaranteed failure in Python 3 when PyUnicode_Check returns false
398
+ if (!PYBIND11_BYTES_CHECK(load_src.ptr()))
399
+ return false;
400
+
401
+ temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
402
+ if (!temp) {
403
+ PyErr_Clear();
404
+ return false;
405
+ }
406
+ load_src = temp;
407
+ #endif
408
+ }
409
+
410
+ #if PY_VERSION_HEX >= 0x03030000
411
+ // On Python >= 3.3, for UTF-8 we avoid the need for a temporary `bytes`
412
+ // object by using `PyUnicode_AsUTF8AndSize`.
413
+ if (PYBIND11_SILENCE_MSVC_C4127(UTF_N == 8)) {
414
+ Py_ssize_t size = -1;
415
+ const auto *buffer
416
+ = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
417
+ if (!buffer) {
418
+ PyErr_Clear();
419
+ return false;
420
+ }
421
+ value = StringType(buffer, static_cast<size_t>(size));
422
+ return true;
423
+ }
424
+ #endif
425
+
426
+ auto utfNbytes
427
+ = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
428
+ UTF_N == 8 ? "utf-8"
429
+ : UTF_N == 16 ? "utf-16"
430
+ : "utf-32",
431
+ nullptr));
432
+ if (!utfNbytes) {
433
+ PyErr_Clear();
434
+ return false;
435
+ }
436
+
437
+ const auto *buffer
438
+ = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
439
+ size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
440
+ // Skip BOM for UTF-16/32
441
+ if (PYBIND11_SILENCE_MSVC_C4127(UTF_N > 8)) {
442
+ buffer++;
443
+ length--;
444
+ }
445
+ value = StringType(buffer, length);
446
+
447
+ // If we're loading a string_view we need to keep the encoded Python object alive:
448
+ if (IsView) {
449
+ loader_life_support::add_patient(utfNbytes);
450
+ }
451
+
452
+ return true;
453
+ }
454
+
455
+ static handle
456
+ cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
457
+ const char *buffer = reinterpret_cast<const char *>(src.data());
458
+ auto nbytes = ssize_t(src.size() * sizeof(CharT));
459
+ handle s = decode_utfN(buffer, nbytes);
460
+ if (!s) {
461
+ throw error_already_set();
462
+ }
463
+ return s;
464
+ }
465
+
466
+ PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
467
+
468
+ private:
469
+ static handle decode_utfN(const char *buffer, ssize_t nbytes) {
470
+ #if !defined(PYPY_VERSION)
471
+ return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
472
+ : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
473
+ : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
474
+ #else
475
+ // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
476
+ // well), so bypass the whole thing by just passing the encoding as a string value, which
477
+ // works properly:
478
+ return PyUnicode_Decode(buffer,
479
+ nbytes,
480
+ UTF_N == 8 ? "utf-8"
481
+ : UTF_N == 16 ? "utf-16"
482
+ : "utf-32",
483
+ nullptr);
484
+ #endif
485
+ }
486
+
487
+ // When loading into a std::string or char*, accept a bytes object as-is (i.e.
488
+ // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
489
+ // which supports loading a unicode from a str, doesn't take this path.
490
+ template <typename C = CharT>
491
+ bool load_bytes(enable_if_t<std::is_same<C, char>::value, handle> src) {
492
+ if (PYBIND11_BYTES_CHECK(src.ptr())) {
493
+ // We were passed a Python 3 raw bytes; accept it into a std::string or char*
494
+ // without any encoding attempt.
495
+ const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
496
+ if (bytes) {
497
+ value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
498
+ return true;
499
+ }
500
+ }
501
+
502
+ return false;
503
+ }
504
+
505
+ template <typename C = CharT>
506
+ bool load_bytes(enable_if_t<!std::is_same<C, char>::value, handle>) {
507
+ return false;
508
+ }
509
+ };
510
+
511
+ template <typename CharT, class Traits, class Allocator>
512
+ struct type_caster<std::basic_string<CharT, Traits, Allocator>,
513
+ enable_if_t<is_std_char_type<CharT>::value>>
514
+ : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
515
+
516
+ #ifdef PYBIND11_HAS_STRING_VIEW
517
+ template <typename CharT, class Traits>
518
+ struct type_caster<std::basic_string_view<CharT, Traits>,
519
+ enable_if_t<is_std_char_type<CharT>::value>>
520
+ : string_caster<std::basic_string_view<CharT, Traits>, true> {};
521
+ #endif
522
+
523
+ // Type caster for C-style strings. We basically use a std::string type caster, but also add the
524
+ // ability to use None as a nullptr char* (which the string caster doesn't allow).
525
+ template <typename CharT>
526
+ struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
527
+ using StringType = std::basic_string<CharT>;
528
+ using StringCaster = type_caster<StringType>;
529
+ StringCaster str_caster;
530
+ bool none = false;
531
+ CharT one_char = 0;
532
+
533
+ public:
534
+ bool load(handle src, bool convert) {
535
+ if (!src) {
536
+ return false;
537
+ }
538
+ if (src.is_none()) {
539
+ // Defer accepting None to other overloads (if we aren't in convert mode):
540
+ if (!convert) {
541
+ return false;
542
+ }
543
+ none = true;
544
+ return true;
545
+ }
546
+ return str_caster.load(src, convert);
547
+ }
548
+
549
+ static handle cast(const CharT *src, return_value_policy policy, handle parent) {
550
+ if (src == nullptr) {
551
+ return pybind11::none().inc_ref();
552
+ }
553
+ return StringCaster::cast(StringType(src), policy, parent);
554
+ }
555
+
556
+ static handle cast(CharT src, return_value_policy policy, handle parent) {
557
+ if (std::is_same<char, CharT>::value) {
558
+ handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
559
+ if (!s) {
560
+ throw error_already_set();
561
+ }
562
+ return s;
563
+ }
564
+ return StringCaster::cast(StringType(1, src), policy, parent);
565
+ }
566
+
567
+ explicit operator CharT *() {
568
+ return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
569
+ }
570
+ explicit operator CharT &() {
571
+ if (none) {
572
+ throw value_error("Cannot convert None to a character");
573
+ }
574
+
575
+ auto &value = static_cast<StringType &>(str_caster);
576
+ size_t str_len = value.size();
577
+ if (str_len == 0) {
578
+ throw value_error("Cannot convert empty string to a character");
579
+ }
580
+
581
+ // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
582
+ // is too high, and one for multiple unicode characters (caught later), so we need to
583
+ // figure out how long the first encoded character is in bytes to distinguish between these
584
+ // two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
585
+ // those can fit into a single char value.
586
+ if (PYBIND11_SILENCE_MSVC_C4127(StringCaster::UTF_N == 8) && str_len > 1 && str_len <= 4) {
587
+ auto v0 = static_cast<unsigned char>(value[0]);
588
+ // low bits only: 0-127
589
+ // 0b110xxxxx - start of 2-byte sequence
590
+ // 0b1110xxxx - start of 3-byte sequence
591
+ // 0b11110xxx - start of 4-byte sequence
592
+ size_t char0_bytes = (v0 & 0x80) == 0 ? 1
593
+ : (v0 & 0xE0) == 0xC0 ? 2
594
+ : (v0 & 0xF0) == 0xE0 ? 3
595
+ : 4;
596
+
597
+ if (char0_bytes == str_len) {
598
+ // If we have a 128-255 value, we can decode it into a single char:
599
+ if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
600
+ one_char = static_cast<CharT>(((v0 & 3) << 6)
601
+ + (static_cast<unsigned char>(value[1]) & 0x3F));
602
+ return one_char;
603
+ }
604
+ // Otherwise we have a single character, but it's > U+00FF
605
+ throw value_error("Character code point not in range(0x100)");
606
+ }
607
+ }
608
+
609
+ // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
610
+ // surrogate pair with total length 2 instantly indicates a range error (but not a "your
611
+ // string was too long" error).
612
+ else if (PYBIND11_SILENCE_MSVC_C4127(StringCaster::UTF_N == 16) && str_len == 2) {
613
+ one_char = static_cast<CharT>(value[0]);
614
+ if (one_char >= 0xD800 && one_char < 0xE000) {
615
+ throw value_error("Character code point not in range(0x10000)");
616
+ }
617
+ }
618
+
619
+ if (str_len != 1) {
620
+ throw value_error("Expected a character, but multi-character string found");
621
+ }
622
+
623
+ one_char = value[0];
624
+ return one_char;
625
+ }
626
+
627
+ static constexpr auto name = const_name(PYBIND11_STRING_NAME);
628
+ template <typename _T>
629
+ using cast_op_type = pybind11::detail::cast_op_type<_T>;
630
+ };
631
+
632
+ // Base implementation for std::tuple and std::pair
633
+ template <template <typename...> class Tuple, typename... Ts>
634
+ class tuple_caster {
635
+ using type = Tuple<Ts...>;
636
+ static constexpr auto size = sizeof...(Ts);
637
+ using indices = make_index_sequence<size>;
638
+
639
+ public:
640
+ bool load(handle src, bool convert) {
641
+ if (!isinstance<sequence>(src)) {
642
+ return false;
643
+ }
644
+ const auto seq = reinterpret_borrow<sequence>(src);
645
+ if (seq.size() != size) {
646
+ return false;
647
+ }
648
+ return load_impl(seq, convert, indices{});
649
+ }
650
+
651
+ template <typename T>
652
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
653
+ return cast_impl(std::forward<T>(src), policy, parent, indices{});
654
+ }
655
+
656
+ // copied from the PYBIND11_TYPE_CASTER macro
657
+ template <typename T>
658
+ static handle cast(T *src, return_value_policy policy, handle parent) {
659
+ if (!src) {
660
+ return none().release();
661
+ }
662
+ if (policy == return_value_policy::take_ownership) {
663
+ auto h = cast(std::move(*src), policy, parent);
664
+ delete src;
665
+ return h;
666
+ }
667
+ return cast(*src, policy, parent);
668
+ }
669
+
670
+ static constexpr auto name
671
+ = const_name("Tuple[") + concat(make_caster<Ts>::name...) + const_name("]");
672
+
673
+ template <typename T>
674
+ using cast_op_type = type;
675
+
676
+ explicit operator type() & { return implicit_cast(indices{}); }
677
+ explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
678
+
679
+ protected:
680
+ template <size_t... Is>
681
+ type implicit_cast(index_sequence<Is...>) & {
682
+ return type(cast_op<Ts>(std::get<Is>(subcasters))...);
683
+ }
684
+ template <size_t... Is>
685
+ type implicit_cast(index_sequence<Is...>) && {
686
+ return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
687
+ }
688
+
689
+ static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
690
+
691
+ template <size_t... Is>
692
+ bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
693
+ #ifdef __cpp_fold_expressions
694
+ if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
695
+ return false;
696
+ }
697
+ #else
698
+ for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
699
+ if (!r) {
700
+ return false;
701
+ }
702
+ }
703
+ #endif
704
+ return true;
705
+ }
706
+
707
+ /* Implementation: Convert a C++ tuple into a Python tuple */
708
+ template <typename T, size_t... Is>
709
+ static handle
710
+ cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
711
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
712
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
713
+ std::array<object, size> entries{{reinterpret_steal<object>(
714
+ make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
715
+ for (const auto &entry : entries) {
716
+ if (!entry) {
717
+ return handle();
718
+ }
719
+ }
720
+ tuple result(size);
721
+ int counter = 0;
722
+ for (auto &entry : entries) {
723
+ PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
724
+ }
725
+ return result.release();
726
+ }
727
+
728
+ Tuple<make_caster<Ts>...> subcasters;
729
+ };
730
+
731
+ template <typename T1, typename T2>
732
+ class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
733
+
734
+ template <typename... Ts>
735
+ class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
736
+
737
+ /// Helper class which abstracts away certain actions. Users can provide specializations for
738
+ /// custom holders, but it's only necessary if the type has a non-standard interface.
739
+ template <typename T>
740
+ struct holder_helper {
741
+ static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
742
+ };
743
+
744
+ /// Type caster for holder types like std::shared_ptr, etc.
745
+ /// The SFINAE hook is provided to help work around the current lack of support
746
+ /// for smart-pointer interoperability. Please consider it an implementation
747
+ /// detail that may change in the future, as formal support for smart-pointer
748
+ /// interoperability is added into pybind11.
749
+ template <typename type, typename holder_type, typename SFINAE = void>
750
+ struct copyable_holder_caster : public type_caster_base<type> {
751
+ public:
752
+ using base = type_caster_base<type>;
753
+ static_assert(std::is_base_of<base, type_caster<type>>::value,
754
+ "Holder classes are only supported for custom types");
755
+ using base::base;
756
+ using base::cast;
757
+ using base::typeinfo;
758
+ using base::value;
759
+
760
+ bool load(handle src, bool convert) {
761
+ return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
762
+ }
763
+
764
+ explicit operator type *() { return this->value; }
765
+ // static_cast works around compiler error with MSVC 17 and CUDA 10.2
766
+ // see issue #2180
767
+ explicit operator type &() { return *(static_cast<type *>(this->value)); }
768
+ explicit operator holder_type *() { return std::addressof(holder); }
769
+ explicit operator holder_type &() { return holder; }
770
+
771
+ static handle cast(const holder_type &src, return_value_policy, handle) {
772
+ const auto *ptr = holder_helper<holder_type>::get(src);
773
+ return type_caster_base<type>::cast_holder(ptr, &src);
774
+ }
775
+
776
+ protected:
777
+ friend class type_caster_generic;
778
+ void check_holder_compat() {
779
+ if (typeinfo->default_holder) {
780
+ throw cast_error("Unable to load a custom holder type from a default-holder instance");
781
+ }
782
+ }
783
+
784
+ bool load_value(value_and_holder &&v_h) {
785
+ if (v_h.holder_constructed()) {
786
+ value = v_h.value_ptr();
787
+ holder = v_h.template holder<holder_type>();
788
+ return true;
789
+ }
790
+ throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
791
+ #if defined(NDEBUG)
792
+ "(compile in debug mode for type information)");
793
+ #else
794
+ "of type '"
795
+ + type_id<holder_type>() + "''");
796
+ #endif
797
+ }
798
+
799
+ template <typename T = holder_type,
800
+ detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
801
+ bool try_implicit_casts(handle, bool) {
802
+ return false;
803
+ }
804
+
805
+ template <typename T = holder_type,
806
+ detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
807
+ bool try_implicit_casts(handle src, bool convert) {
808
+ for (auto &cast : typeinfo->implicit_casts) {
809
+ copyable_holder_caster sub_caster(*cast.first);
810
+ if (sub_caster.load(src, convert)) {
811
+ value = cast.second(sub_caster.value);
812
+ holder = holder_type(sub_caster.holder, (type *) value);
813
+ return true;
814
+ }
815
+ }
816
+ return false;
817
+ }
818
+
819
+ static bool try_direct_conversions(handle) { return false; }
820
+
821
+ holder_type holder;
822
+ };
823
+
824
+ /// Specialize for the common std::shared_ptr, so users don't need to
825
+ template <typename T>
826
+ class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
827
+
828
+ /// Type caster for holder types like std::unique_ptr.
829
+ /// Please consider the SFINAE hook an implementation detail, as explained
830
+ /// in the comment for the copyable_holder_caster.
831
+ template <typename type, typename holder_type, typename SFINAE = void>
832
+ struct move_only_holder_caster {
833
+ static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
834
+ "Holder classes are only supported for custom types");
835
+
836
+ static handle cast(holder_type &&src, return_value_policy, handle) {
837
+ auto *ptr = holder_helper<holder_type>::get(src);
838
+ return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
839
+ }
840
+ static constexpr auto name = type_caster_base<type>::name;
841
+ };
842
+
843
+ template <typename type, typename deleter>
844
+ class type_caster<std::unique_ptr<type, deleter>>
845
+ : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
846
+
847
+ template <typename type, typename holder_type>
848
+ using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
849
+ copyable_holder_caster<type, holder_type>,
850
+ move_only_holder_caster<type, holder_type>>;
851
+
852
+ template <typename T, bool Value = false>
853
+ struct always_construct_holder {
854
+ static constexpr bool value = Value;
855
+ };
856
+
857
+ /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
858
+ #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
859
+ namespace pybind11 { \
860
+ namespace detail { \
861
+ template <typename type> \
862
+ struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { \
863
+ }; \
864
+ template <typename type> \
865
+ class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
866
+ : public type_caster_holder<type, holder_type> {}; \
867
+ } \
868
+ }
869
+
870
+ // PYBIND11_DECLARE_HOLDER_TYPE holder types:
871
+ template <typename base, typename holder>
872
+ struct is_holder_type
873
+ : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
874
+ // Specialization for always-supported unique_ptr holders:
875
+ template <typename base, typename deleter>
876
+ struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
877
+
878
+ template <typename T>
879
+ struct handle_type_name {
880
+ static constexpr auto name = const_name<T>();
881
+ };
882
+ template <>
883
+ struct handle_type_name<bool_> {
884
+ static constexpr auto name = const_name("bool");
885
+ };
886
+ template <>
887
+ struct handle_type_name<bytes> {
888
+ static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
889
+ };
890
+ template <>
891
+ struct handle_type_name<int_> {
892
+ static constexpr auto name = const_name("int");
893
+ };
894
+ template <>
895
+ struct handle_type_name<iterable> {
896
+ static constexpr auto name = const_name("Iterable");
897
+ };
898
+ template <>
899
+ struct handle_type_name<iterator> {
900
+ static constexpr auto name = const_name("Iterator");
901
+ };
902
+ template <>
903
+ struct handle_type_name<float_> {
904
+ static constexpr auto name = const_name("float");
905
+ };
906
+ template <>
907
+ struct handle_type_name<none> {
908
+ static constexpr auto name = const_name("None");
909
+ };
910
+ template <>
911
+ struct handle_type_name<args> {
912
+ static constexpr auto name = const_name("*args");
913
+ };
914
+ template <>
915
+ struct handle_type_name<kwargs> {
916
+ static constexpr auto name = const_name("**kwargs");
917
+ };
918
+
919
+ template <typename type>
920
+ struct pyobject_caster {
921
+ template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
922
+ bool load(handle src, bool /* convert */) {
923
+ value = src;
924
+ return static_cast<bool>(value);
925
+ }
926
+
927
+ template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
928
+ bool load(handle src, bool /* convert */) {
929
+ #if PY_MAJOR_VERSION < 3 && !defined(PYBIND11_STR_LEGACY_PERMISSIVE)
930
+ // For Python 2, without this implicit conversion, Python code would
931
+ // need to be cluttered with six.ensure_text() or similar, only to be
932
+ // un-cluttered later after Python 2 support is dropped.
933
+ if (PYBIND11_SILENCE_MSVC_C4127(std::is_same<T, str>::value) && isinstance<bytes>(src)) {
934
+ PyObject *str_from_bytes = PyUnicode_FromEncodedObject(src.ptr(), "utf-8", nullptr);
935
+ if (!str_from_bytes)
936
+ throw error_already_set();
937
+ value = reinterpret_steal<type>(str_from_bytes);
938
+ return true;
939
+ }
940
+ #endif
941
+ if (!isinstance<type>(src)) {
942
+ return false;
943
+ }
944
+ value = reinterpret_borrow<type>(src);
945
+ return true;
946
+ }
947
+
948
+ static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
949
+ return src.inc_ref();
950
+ }
951
+ PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
952
+ };
953
+
954
+ template <typename T>
955
+ class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
956
+
957
+ // Our conditions for enabling moving are quite restrictive:
958
+ // At compile time:
959
+ // - T needs to be a non-const, non-pointer, non-reference type
960
+ // - type_caster<T>::operator T&() must exist
961
+ // - the type must be move constructible (obviously)
962
+ // At run-time:
963
+ // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
964
+ // must have ref_count() == 1)h
965
+ // If any of the above are not satisfied, we fall back to copying.
966
+ template <typename T>
967
+ using move_is_plain_type
968
+ = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
969
+ template <typename T, typename SFINAE = void>
970
+ struct move_always : std::false_type {};
971
+ template <typename T>
972
+ struct move_always<
973
+ T,
974
+ enable_if_t<
975
+ all_of<move_is_plain_type<T>,
976
+ negation<is_copy_constructible<T>>,
977
+ std::is_move_constructible<T>,
978
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
979
+ : std::true_type {};
980
+ template <typename T, typename SFINAE = void>
981
+ struct move_if_unreferenced : std::false_type {};
982
+ template <typename T>
983
+ struct move_if_unreferenced<
984
+ T,
985
+ enable_if_t<
986
+ all_of<move_is_plain_type<T>,
987
+ negation<move_always<T>>,
988
+ std::is_move_constructible<T>,
989
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
990
+ : std::true_type {};
991
+ template <typename T>
992
+ using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
993
+
994
+ // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
995
+ // reference or pointer to a local variable of the type_caster. Basically, only
996
+ // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
997
+ // everything else returns a reference/pointer to a local variable.
998
+ template <typename type>
999
+ using cast_is_temporary_value_reference
1000
+ = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
1001
+ && !std::is_base_of<type_caster_generic, make_caster<type>>::value
1002
+ && !std::is_same<intrinsic_t<type>, void>::value>;
1003
+
1004
+ // When a value returned from a C++ function is being cast back to Python, we almost always want to
1005
+ // force `policy = move`, regardless of the return value policy the function/method was declared
1006
+ // with.
1007
+ template <typename Return, typename SFINAE = void>
1008
+ struct return_value_policy_override {
1009
+ static return_value_policy policy(return_value_policy p) { return p; }
1010
+ };
1011
+
1012
+ template <typename Return>
1013
+ struct return_value_policy_override<
1014
+ Return,
1015
+ detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1016
+ static return_value_policy policy(return_value_policy p) {
1017
+ return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
1018
+ ? return_value_policy::move
1019
+ : p;
1020
+ }
1021
+ };
1022
+
1023
+ // Basic python -> C++ casting; throws if casting fails
1024
+ template <typename T, typename SFINAE>
1025
+ type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
1026
+ if (!conv.load(handle, true)) {
1027
+ #if defined(NDEBUG)
1028
+ throw cast_error(
1029
+ "Unable to cast Python instance to C++ type (compile in debug mode for details)");
1030
+ #else
1031
+ throw cast_error("Unable to cast Python instance of type "
1032
+ + (std::string) str(type::handle_of(handle)) + " to C++ type '"
1033
+ + type_id<T>() + "'");
1034
+ #endif
1035
+ }
1036
+ return conv;
1037
+ }
1038
+ // Wrapper around the above that also constructs and returns a type_caster
1039
+ template <typename T>
1040
+ make_caster<T> load_type(const handle &handle) {
1041
+ make_caster<T> conv;
1042
+ load_type(conv, handle);
1043
+ return conv;
1044
+ }
1045
+
1046
+ PYBIND11_NAMESPACE_END(detail)
1047
+
1048
+ // pytype -> C++ type
1049
+ template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1050
+ T cast(const handle &handle) {
1051
+ using namespace detail;
1052
+ static_assert(!cast_is_temporary_value_reference<T>::value,
1053
+ "Unable to cast type to reference: value is local to type caster");
1054
+ return cast_op<T>(load_type<T>(handle));
1055
+ }
1056
+
1057
+ // pytype -> pytype (calls converting constructor)
1058
+ template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
1059
+ T cast(const handle &handle) {
1060
+ return T(reinterpret_borrow<object>(handle));
1061
+ }
1062
+
1063
+ // C++ type -> py::object
1064
+ template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1065
+ object cast(T &&value,
1066
+ return_value_policy policy = return_value_policy::automatic_reference,
1067
+ handle parent = handle()) {
1068
+ using no_ref_T = typename std::remove_reference<T>::type;
1069
+ if (policy == return_value_policy::automatic) {
1070
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
1071
+ : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1072
+ : return_value_policy::move;
1073
+ } else if (policy == return_value_policy::automatic_reference) {
1074
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
1075
+ : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1076
+ : return_value_policy::move;
1077
+ }
1078
+ return reinterpret_steal<object>(
1079
+ detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1080
+ }
1081
+
1082
+ template <typename T>
1083
+ T handle::cast() const {
1084
+ return pybind11::cast<T>(*this);
1085
+ }
1086
+ template <>
1087
+ inline void handle::cast() const {
1088
+ return;
1089
+ }
1090
+
1091
+ template <typename T>
1092
+ detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
1093
+ if (obj.ref_count() > 1) {
1094
+ #if defined(NDEBUG)
1095
+ throw cast_error(
1096
+ "Unable to cast Python instance to C++ rvalue: instance has multiple references"
1097
+ " (compile in debug mode for details)");
1098
+ #else
1099
+ throw cast_error("Unable to move from Python " + (std::string) str(type::handle_of(obj))
1100
+ + " instance to C++ " + type_id<T>()
1101
+ + " instance: instance has multiple references");
1102
+ #endif
1103
+ }
1104
+
1105
+ // Move into a temporary and return that, because the reference may be a local value of `conv`
1106
+ T ret = std::move(detail::load_type<T>(obj).operator T &());
1107
+ return ret;
1108
+ }
1109
+
1110
+ // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
1111
+ // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
1112
+ // object has multiple references, but trying to copy will fail to compile.
1113
+ // - If both movable and copyable, check ref count: if 1, move; otherwise copy
1114
+ // - Otherwise (not movable), copy.
1115
+ template <typename T>
1116
+ detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) {
1117
+ return move<T>(std::move(object));
1118
+ }
1119
+ template <typename T>
1120
+ detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) {
1121
+ if (object.ref_count() > 1) {
1122
+ return cast<T>(object);
1123
+ }
1124
+ return move<T>(std::move(object));
1125
+ }
1126
+ template <typename T>
1127
+ detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) {
1128
+ return cast<T>(object);
1129
+ }
1130
+
1131
+ template <typename T>
1132
+ T object::cast() const & {
1133
+ return pybind11::cast<T>(*this);
1134
+ }
1135
+ template <typename T>
1136
+ T object::cast() && {
1137
+ return pybind11::cast<T>(std::move(*this));
1138
+ }
1139
+ template <>
1140
+ inline void object::cast() const & {
1141
+ return;
1142
+ }
1143
+ template <>
1144
+ inline void object::cast() && {
1145
+ return;
1146
+ }
1147
+
1148
+ PYBIND11_NAMESPACE_BEGIN(detail)
1149
+
1150
+ // Declared in pytypes.h:
1151
+ template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
1152
+ object object_or_cast(T &&o) {
1153
+ return pybind11::cast(std::forward<T>(o));
1154
+ }
1155
+
1156
+ // Placeholder type for the unneeded (and dead code) static variable in the
1157
+ // PYBIND11_OVERRIDE_OVERRIDE macro
1158
+ struct override_unused {};
1159
+ template <typename ret_type>
1160
+ using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
1161
+ make_caster<ret_type>,
1162
+ override_unused>;
1163
+
1164
+ // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
1165
+ // store the result in the given variable. For other types, this is a no-op.
1166
+ template <typename T>
1167
+ enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
1168
+ make_caster<T> &caster) {
1169
+ return cast_op<T>(load_type(caster, o));
1170
+ }
1171
+ template <typename T>
1172
+ enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
1173
+ override_unused &) {
1174
+ pybind11_fail("Internal error: cast_ref fallback invoked");
1175
+ }
1176
+
1177
+ // Trampoline use: Having a pybind11::cast with an invalid reference type is going to
1178
+ // static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
1179
+ // that only does anything in cases where pybind11::cast is valid.
1180
+ template <typename T>
1181
+ enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&o) {
1182
+ return pybind11::cast<T>(std::move(o));
1183
+ }
1184
+ template <typename T>
1185
+ enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
1186
+ pybind11_fail("Internal error: cast_safe fallback invoked");
1187
+ }
1188
+ template <>
1189
+ inline void cast_safe<void>(object &&) {}
1190
+
1191
+ PYBIND11_NAMESPACE_END(detail)
1192
+
1193
+ // The overloads could coexist, i.e. the #if is not strictly speaking needed,
1194
+ // but it is an easy minor optimization.
1195
+ #if defined(NDEBUG)
1196
+ inline cast_error cast_error_unable_to_convert_call_arg() {
1197
+ return cast_error(
1198
+ "Unable to convert call argument to Python object (compile in debug mode for details)");
1199
+ }
1200
+ #else
1201
+ inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
1202
+ const std::string &type) {
1203
+ return cast_error("Unable to convert call argument '" + name + "' of type '" + type
1204
+ + "' to Python object");
1205
+ }
1206
+ #endif
1207
+
1208
+ template <return_value_policy policy = return_value_policy::automatic_reference>
1209
+ tuple make_tuple() {
1210
+ return tuple(0);
1211
+ }
1212
+
1213
+ template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1214
+ tuple make_tuple(Args &&...args_) {
1215
+ constexpr size_t size = sizeof...(Args);
1216
+ std::array<object, size> args{{reinterpret_steal<object>(
1217
+ detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
1218
+ for (size_t i = 0; i < args.size(); i++) {
1219
+ if (!args[i]) {
1220
+ #if defined(NDEBUG)
1221
+ throw cast_error_unable_to_convert_call_arg();
1222
+ #else
1223
+ std::array<std::string, size> argtypes{{type_id<Args>()...}};
1224
+ throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
1225
+ #endif
1226
+ }
1227
+ }
1228
+ tuple result(size);
1229
+ int counter = 0;
1230
+ for (auto &arg_value : args) {
1231
+ PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1232
+ }
1233
+ return result;
1234
+ }
1235
+
1236
+ /// \ingroup annotations
1237
+ /// Annotation for arguments
1238
+ struct arg {
1239
+ /// Constructs an argument with the name of the argument; if null or omitted, this is a
1240
+ /// positional argument.
1241
+ constexpr explicit arg(const char *name = nullptr)
1242
+ : name(name), flag_noconvert(false), flag_none(true) {}
1243
+ /// Assign a value to this argument
1244
+ template <typename T>
1245
+ arg_v operator=(T &&value) const;
1246
+ /// Indicate that the type should not be converted in the type caster
1247
+ arg &noconvert(bool flag = true) {
1248
+ flag_noconvert = flag;
1249
+ return *this;
1250
+ }
1251
+ /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
1252
+ arg &none(bool flag = true) {
1253
+ flag_none = flag;
1254
+ return *this;
1255
+ }
1256
+
1257
+ const char *name; ///< If non-null, this is a named kwargs argument
1258
+ bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
1259
+ ///< caster!)
1260
+ bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
1261
+ };
1262
+
1263
+ /// \ingroup annotations
1264
+ /// Annotation for arguments with values
1265
+ struct arg_v : arg {
1266
+ private:
1267
+ template <typename T>
1268
+ arg_v(arg &&base, T &&x, const char *descr = nullptr)
1269
+ : arg(base), value(reinterpret_steal<object>(
1270
+ detail::make_caster<T>::cast(x, return_value_policy::automatic, {}))),
1271
+ descr(descr)
1272
+ #if !defined(NDEBUG)
1273
+ ,
1274
+ type(type_id<T>())
1275
+ #endif
1276
+ {
1277
+ // Workaround! See:
1278
+ // https://github.com/pybind/pybind11/issues/2336
1279
+ // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
1280
+ if (PyErr_Occurred()) {
1281
+ PyErr_Clear();
1282
+ }
1283
+ }
1284
+
1285
+ public:
1286
+ /// Direct construction with name, default, and description
1287
+ template <typename T>
1288
+ arg_v(const char *name, T &&x, const char *descr = nullptr)
1289
+ : arg_v(arg(name), std::forward<T>(x), descr) {}
1290
+
1291
+ /// Called internally when invoking `py::arg("a") = value`
1292
+ template <typename T>
1293
+ arg_v(const arg &base, T &&x, const char *descr = nullptr)
1294
+ : arg_v(arg(base), std::forward<T>(x), descr) {}
1295
+
1296
+ /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
1297
+ arg_v &noconvert(bool flag = true) {
1298
+ arg::noconvert(flag);
1299
+ return *this;
1300
+ }
1301
+
1302
+ /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
1303
+ arg_v &none(bool flag = true) {
1304
+ arg::none(flag);
1305
+ return *this;
1306
+ }
1307
+
1308
+ /// The default value
1309
+ object value;
1310
+ /// The (optional) description of the default value
1311
+ const char *descr;
1312
+ #if !defined(NDEBUG)
1313
+ /// The C++ type name of the default value (only available when compiled in debug mode)
1314
+ std::string type;
1315
+ #endif
1316
+ };
1317
+
1318
+ /// \ingroup annotations
1319
+ /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
1320
+ /// an unnamed '*' argument (in Python 3)
1321
+ struct kw_only {};
1322
+
1323
+ /// \ingroup annotations
1324
+ /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
1325
+ /// an unnamed '/' argument (in Python 3.8)
1326
+ struct pos_only {};
1327
+
1328
+ template <typename T>
1329
+ arg_v arg::operator=(T &&value) const {
1330
+ return {*this, std::forward<T>(value)};
1331
+ }
1332
+
1333
+ /// Alias for backward compatibility -- to be removed in version 2.0
1334
+ template <typename /*unused*/>
1335
+ using arg_t = arg_v;
1336
+
1337
+ inline namespace literals {
1338
+ /** \rst
1339
+ String literal version of `arg`
1340
+ \endrst */
1341
+ constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
1342
+ } // namespace literals
1343
+
1344
+ PYBIND11_NAMESPACE_BEGIN(detail)
1345
+
1346
+ template <typename T>
1347
+ using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
1348
+ template <typename T>
1349
+ using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
1350
+
1351
+ // forward declaration (definition in attr.h)
1352
+ struct function_record;
1353
+
1354
+ /// Internal data associated with a single function call
1355
+ struct function_call {
1356
+ function_call(const function_record &f, handle p); // Implementation in attr.h
1357
+
1358
+ /// The function data:
1359
+ const function_record &func;
1360
+
1361
+ /// Arguments passed to the function:
1362
+ std::vector<handle> args;
1363
+
1364
+ /// The `convert` value the arguments should be loaded with
1365
+ std::vector<bool> args_convert;
1366
+
1367
+ /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
1368
+ /// present, are also in `args` but without a reference).
1369
+ object args_ref, kwargs_ref;
1370
+
1371
+ /// The parent, if any
1372
+ handle parent;
1373
+
1374
+ /// If this is a call to an initializer, this argument contains `self`
1375
+ handle init_self;
1376
+ };
1377
+
1378
+ /// Helper class which loads arguments for C++ functions called from Python
1379
+ template <typename... Args>
1380
+ class argument_loader {
1381
+ using indices = make_index_sequence<sizeof...(Args)>;
1382
+
1383
+ template <typename Arg>
1384
+ using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
1385
+ template <typename Arg>
1386
+ using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
1387
+ // Get kwargs argument position, or -1 if not present:
1388
+ static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
1389
+
1390
+ static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
1391
+ "py::kwargs is only permitted as the last argument of a function");
1392
+
1393
+ public:
1394
+ static constexpr bool has_kwargs = kwargs_pos != -1;
1395
+
1396
+ // py::args argument position; -1 if not present.
1397
+ static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
1398
+
1399
+ static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
1400
+ "py::args cannot be specified more than once");
1401
+
1402
+ static constexpr auto arg_names = concat(type_descr(make_caster<Args>::name)...);
1403
+
1404
+ bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
1405
+
1406
+ template <typename Return, typename Guard, typename Func>
1407
+ // NOLINTNEXTLINE(readability-const-return-type)
1408
+ enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
1409
+ return std::move(*this).template call_impl<remove_cv_t<Return>>(
1410
+ std::forward<Func>(f), indices{}, Guard{});
1411
+ }
1412
+
1413
+ template <typename Return, typename Guard, typename Func>
1414
+ enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
1415
+ std::move(*this).template call_impl<remove_cv_t<Return>>(
1416
+ std::forward<Func>(f), indices{}, Guard{});
1417
+ return void_type();
1418
+ }
1419
+
1420
+ private:
1421
+ static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
1422
+
1423
+ template <size_t... Is>
1424
+ bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
1425
+ #ifdef __cpp_fold_expressions
1426
+ if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
1427
+ return false;
1428
+ }
1429
+ #else
1430
+ for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
1431
+ if (!r) {
1432
+ return false;
1433
+ }
1434
+ }
1435
+ #endif
1436
+ return true;
1437
+ }
1438
+
1439
+ template <typename Return, typename Func, size_t... Is, typename Guard>
1440
+ Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
1441
+ return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
1442
+ }
1443
+
1444
+ std::tuple<make_caster<Args>...> argcasters;
1445
+ };
1446
+
1447
+ /// Helper class which collects only positional arguments for a Python function call.
1448
+ /// A fancier version below can collect any argument, but this one is optimal for simple calls.
1449
+ template <return_value_policy policy>
1450
+ class simple_collector {
1451
+ public:
1452
+ template <typename... Ts>
1453
+ explicit simple_collector(Ts &&...values)
1454
+ : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
1455
+
1456
+ const tuple &args() const & { return m_args; }
1457
+ dict kwargs() const { return {}; }
1458
+
1459
+ tuple args() && { return std::move(m_args); }
1460
+
1461
+ /// Call a Python function and pass the collected arguments
1462
+ object call(PyObject *ptr) const {
1463
+ PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
1464
+ if (!result) {
1465
+ throw error_already_set();
1466
+ }
1467
+ return reinterpret_steal<object>(result);
1468
+ }
1469
+
1470
+ private:
1471
+ tuple m_args;
1472
+ };
1473
+
1474
+ /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
1475
+ template <return_value_policy policy>
1476
+ class unpacking_collector {
1477
+ public:
1478
+ template <typename... Ts>
1479
+ explicit unpacking_collector(Ts &&...values) {
1480
+ // Tuples aren't (easily) resizable so a list is needed for collection,
1481
+ // but the actual function call strictly requires a tuple.
1482
+ auto args_list = list();
1483
+ using expander = int[];
1484
+ (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
1485
+
1486
+ m_args = std::move(args_list);
1487
+ }
1488
+
1489
+ const tuple &args() const & { return m_args; }
1490
+ const dict &kwargs() const & { return m_kwargs; }
1491
+
1492
+ tuple args() && { return std::move(m_args); }
1493
+ dict kwargs() && { return std::move(m_kwargs); }
1494
+
1495
+ /// Call a Python function and pass the collected arguments
1496
+ object call(PyObject *ptr) const {
1497
+ PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
1498
+ if (!result) {
1499
+ throw error_already_set();
1500
+ }
1501
+ return reinterpret_steal<object>(result);
1502
+ }
1503
+
1504
+ private:
1505
+ template <typename T>
1506
+ void process(list &args_list, T &&x) {
1507
+ auto o = reinterpret_steal<object>(
1508
+ detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
1509
+ if (!o) {
1510
+ #if defined(NDEBUG)
1511
+ throw cast_error_unable_to_convert_call_arg();
1512
+ #else
1513
+ throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
1514
+ type_id<T>());
1515
+ #endif
1516
+ }
1517
+ args_list.append(o);
1518
+ }
1519
+
1520
+ void process(list &args_list, detail::args_proxy ap) {
1521
+ for (auto a : ap) {
1522
+ args_list.append(a);
1523
+ }
1524
+ }
1525
+
1526
+ void process(list & /*args_list*/, arg_v a) {
1527
+ if (!a.name) {
1528
+ #if defined(NDEBUG)
1529
+ nameless_argument_error();
1530
+ #else
1531
+ nameless_argument_error(a.type);
1532
+ #endif
1533
+ }
1534
+ if (m_kwargs.contains(a.name)) {
1535
+ #if defined(NDEBUG)
1536
+ multiple_values_error();
1537
+ #else
1538
+ multiple_values_error(a.name);
1539
+ #endif
1540
+ }
1541
+ if (!a.value) {
1542
+ #if defined(NDEBUG)
1543
+ throw cast_error_unable_to_convert_call_arg();
1544
+ #else
1545
+ throw cast_error_unable_to_convert_call_arg(a.name, a.type);
1546
+ #endif
1547
+ }
1548
+ m_kwargs[a.name] = a.value;
1549
+ }
1550
+
1551
+ void process(list & /*args_list*/, detail::kwargs_proxy kp) {
1552
+ if (!kp) {
1553
+ return;
1554
+ }
1555
+ for (auto k : reinterpret_borrow<dict>(kp)) {
1556
+ if (m_kwargs.contains(k.first)) {
1557
+ #if defined(NDEBUG)
1558
+ multiple_values_error();
1559
+ #else
1560
+ multiple_values_error(str(k.first));
1561
+ #endif
1562
+ }
1563
+ m_kwargs[k.first] = k.second;
1564
+ }
1565
+ }
1566
+
1567
+ [[noreturn]] static void nameless_argument_error() {
1568
+ throw type_error("Got kwargs without a name; only named arguments "
1569
+ "may be passed via py::arg() to a python function call. "
1570
+ "(compile in debug mode for details)");
1571
+ }
1572
+ [[noreturn]] static void nameless_argument_error(const std::string &type) {
1573
+ throw type_error("Got kwargs without a name of type '" + type
1574
+ + "'; only named "
1575
+ "arguments may be passed via py::arg() to a python function call. ");
1576
+ }
1577
+ [[noreturn]] static void multiple_values_error() {
1578
+ throw type_error("Got multiple values for keyword argument "
1579
+ "(compile in debug mode for details)");
1580
+ }
1581
+
1582
+ [[noreturn]] static void multiple_values_error(const std::string &name) {
1583
+ throw type_error("Got multiple values for keyword argument '" + name + "'");
1584
+ }
1585
+
1586
+ private:
1587
+ tuple m_args;
1588
+ dict m_kwargs;
1589
+ };
1590
+
1591
+ // [workaround(intel)] Separate function required here
1592
+ // We need to put this into a separate function because the Intel compiler
1593
+ // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
1594
+ // (tested with ICC 2021.1 Beta 20200827).
1595
+ template <typename... Args>
1596
+ constexpr bool args_are_all_positional() {
1597
+ return all_of<is_positional<Args>...>::value;
1598
+ }
1599
+
1600
+ /// Collect only positional arguments for a Python function call
1601
+ template <return_value_policy policy,
1602
+ typename... Args,
1603
+ typename = enable_if_t<args_are_all_positional<Args...>()>>
1604
+ simple_collector<policy> collect_arguments(Args &&...args) {
1605
+ return simple_collector<policy>(std::forward<Args>(args)...);
1606
+ }
1607
+
1608
+ /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
1609
+ template <return_value_policy policy,
1610
+ typename... Args,
1611
+ typename = enable_if_t<!args_are_all_positional<Args...>()>>
1612
+ unpacking_collector<policy> collect_arguments(Args &&...args) {
1613
+ // Following argument order rules for generalized unpacking according to PEP 448
1614
+ static_assert(constexpr_last<is_positional, Args...>()
1615
+ < constexpr_first<is_keyword_or_ds, Args...>()
1616
+ && constexpr_last<is_s_unpacking, Args...>()
1617
+ < constexpr_first<is_ds_unpacking, Args...>(),
1618
+ "Invalid function call: positional args must precede keywords and ** unpacking; "
1619
+ "* unpacking must precede ** unpacking");
1620
+ return unpacking_collector<policy>(std::forward<Args>(args)...);
1621
+ }
1622
+
1623
+ template <typename Derived>
1624
+ template <return_value_policy policy, typename... Args>
1625
+ object object_api<Derived>::operator()(Args &&...args) const {
1626
+ #if !defined(NDEBUG) && PY_VERSION_HEX >= 0x03060000
1627
+ if (!PyGILState_Check()) {
1628
+ pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
1629
+ }
1630
+ #endif
1631
+ return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
1632
+ }
1633
+
1634
+ template <typename Derived>
1635
+ template <return_value_policy policy, typename... Args>
1636
+ object object_api<Derived>::call(Args &&...args) const {
1637
+ return operator()<policy>(std::forward<Args>(args)...);
1638
+ }
1639
+
1640
+ PYBIND11_NAMESPACE_END(detail)
1641
+
1642
+ template <typename T>
1643
+ handle type::handle_of() {
1644
+ static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
1645
+ "py::type::of<T> only supports the case where T is a registered C++ types.");
1646
+
1647
+ return detail::get_type_handle(typeid(T), true);
1648
+ }
1649
+
1650
+ #define PYBIND11_MAKE_OPAQUE(...) \
1651
+ namespace pybind11 { \
1652
+ namespace detail { \
1653
+ template <> \
1654
+ class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
1655
+ } \
1656
+ }
1657
+
1658
+ /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
1659
+ /// typedef, e.g.:
1660
+ /// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
1661
+ #define PYBIND11_TYPE(...) __VA_ARGS__
1662
+
1663
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/chrono.h ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime
3
+
4
+ Copyright (c) 2016 Trent Houliston <[email protected]> and
5
+ Wenzel Jakob <[email protected]>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "pybind11.h"
14
+
15
+ #include <chrono>
16
+ #include <cmath>
17
+ #include <ctime>
18
+ #include <datetime.h>
19
+ #include <mutex>
20
+
21
+ // Backport the PyDateTime_DELTA functions from Python3.3 if required
22
+ #ifndef PyDateTime_DELTA_GET_DAYS
23
+ # define PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta *) o)->days)
24
+ #endif
25
+ #ifndef PyDateTime_DELTA_GET_SECONDS
26
+ # define PyDateTime_DELTA_GET_SECONDS(o) (((PyDateTime_Delta *) o)->seconds)
27
+ #endif
28
+ #ifndef PyDateTime_DELTA_GET_MICROSECONDS
29
+ # define PyDateTime_DELTA_GET_MICROSECONDS(o) (((PyDateTime_Delta *) o)->microseconds)
30
+ #endif
31
+
32
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
33
+ PYBIND11_NAMESPACE_BEGIN(detail)
34
+
35
+ template <typename type>
36
+ class duration_caster {
37
+ public:
38
+ using rep = typename type::rep;
39
+ using period = typename type::period;
40
+
41
+ // signed 25 bits required by the standard.
42
+ using days = std::chrono::duration<int_least32_t, std::ratio<86400>>;
43
+
44
+ bool load(handle src, bool) {
45
+ using namespace std::chrono;
46
+
47
+ // Lazy initialise the PyDateTime import
48
+ if (!PyDateTimeAPI) {
49
+ PyDateTime_IMPORT;
50
+ }
51
+
52
+ if (!src) {
53
+ return false;
54
+ }
55
+ // If invoked with datetime.delta object
56
+ if (PyDelta_Check(src.ptr())) {
57
+ value = type(duration_cast<duration<rep, period>>(
58
+ days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
59
+ + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
60
+ + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
61
+ return true;
62
+ }
63
+ // If invoked with a float we assume it is seconds and convert
64
+ if (PyFloat_Check(src.ptr())) {
65
+ value = type(duration_cast<duration<rep, period>>(
66
+ duration<double>(PyFloat_AsDouble(src.ptr()))));
67
+ return true;
68
+ }
69
+ return false;
70
+ }
71
+
72
+ // If this is a duration just return it back
73
+ static const std::chrono::duration<rep, period> &
74
+ get_duration(const std::chrono::duration<rep, period> &src) {
75
+ return src;
76
+ }
77
+
78
+ // If this is a time_point get the time_since_epoch
79
+ template <typename Clock>
80
+ static std::chrono::duration<rep, period>
81
+ get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
82
+ return src.time_since_epoch();
83
+ }
84
+
85
+ static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
86
+ using namespace std::chrono;
87
+
88
+ // Use overloaded function to get our duration from our source
89
+ // Works out if it is a duration or time_point and get the duration
90
+ auto d = get_duration(src);
91
+
92
+ // Lazy initialise the PyDateTime import
93
+ if (!PyDateTimeAPI) {
94
+ PyDateTime_IMPORT;
95
+ }
96
+
97
+ // Declare these special duration types so the conversions happen with the correct
98
+ // primitive types (int)
99
+ using dd_t = duration<int, std::ratio<86400>>;
100
+ using ss_t = duration<int, std::ratio<1>>;
101
+ using us_t = duration<int, std::micro>;
102
+
103
+ auto dd = duration_cast<dd_t>(d);
104
+ auto subd = d - dd;
105
+ auto ss = duration_cast<ss_t>(subd);
106
+ auto us = duration_cast<us_t>(subd - ss);
107
+ return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
108
+ }
109
+
110
+ PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta"));
111
+ };
112
+
113
+ inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
114
+ #if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
115
+ if (localtime_s(buf, time))
116
+ return nullptr;
117
+ return buf;
118
+ #else
119
+ static std::mutex mtx;
120
+ std::lock_guard<std::mutex> lock(mtx);
121
+ std::tm *tm_ptr = std::localtime(time);
122
+ if (tm_ptr != nullptr) {
123
+ *buf = *tm_ptr;
124
+ }
125
+ return tm_ptr;
126
+ #endif
127
+ }
128
+
129
+ // This is for casting times on the system clock into datetime.datetime instances
130
+ template <typename Duration>
131
+ class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
132
+ public:
133
+ using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
134
+ bool load(handle src, bool) {
135
+ using namespace std::chrono;
136
+
137
+ // Lazy initialise the PyDateTime import
138
+ if (!PyDateTimeAPI) {
139
+ PyDateTime_IMPORT;
140
+ }
141
+
142
+ if (!src) {
143
+ return false;
144
+ }
145
+
146
+ std::tm cal;
147
+ microseconds msecs;
148
+
149
+ if (PyDateTime_Check(src.ptr())) {
150
+ cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
151
+ cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
152
+ cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
153
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
154
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
155
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
156
+ cal.tm_isdst = -1;
157
+ msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
158
+ } else if (PyDate_Check(src.ptr())) {
159
+ cal.tm_sec = 0;
160
+ cal.tm_min = 0;
161
+ cal.tm_hour = 0;
162
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
163
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
164
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
165
+ cal.tm_isdst = -1;
166
+ msecs = microseconds(0);
167
+ } else if (PyTime_Check(src.ptr())) {
168
+ cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
169
+ cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
170
+ cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
171
+ cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
172
+ cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
173
+ cal.tm_year = 70; // earliest available date for Python's datetime
174
+ cal.tm_isdst = -1;
175
+ msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
176
+ } else {
177
+ return false;
178
+ }
179
+
180
+ value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
181
+ return true;
182
+ }
183
+
184
+ static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,
185
+ return_value_policy /* policy */,
186
+ handle /* parent */) {
187
+ using namespace std::chrono;
188
+
189
+ // Lazy initialise the PyDateTime import
190
+ if (!PyDateTimeAPI) {
191
+ PyDateTime_IMPORT;
192
+ }
193
+
194
+ // Get out microseconds, and make sure they are positive, to avoid bug in eastern
195
+ // hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)
196
+ using us_t = duration<int, std::micro>;
197
+ auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
198
+ if (us.count() < 0) {
199
+ us += seconds(1);
200
+ }
201
+
202
+ // Subtract microseconds BEFORE `system_clock::to_time_t`, because:
203
+ // > If std::time_t has lower precision, it is implementation-defined whether the value is
204
+ // rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
205
+ std::time_t tt
206
+ = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
207
+
208
+ std::tm localtime;
209
+ std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
210
+ if (!localtime_ptr) {
211
+ throw cast_error("Unable to represent system_clock in local time");
212
+ }
213
+ return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
214
+ localtime.tm_mon + 1,
215
+ localtime.tm_mday,
216
+ localtime.tm_hour,
217
+ localtime.tm_min,
218
+ localtime.tm_sec,
219
+ us.count());
220
+ }
221
+ PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime"));
222
+ };
223
+
224
+ // Other clocks that are not the system clock are not measured as datetime.datetime objects
225
+ // since they are not measured on calendar time. So instead we just make them timedeltas
226
+ // Or if they have passed us a time as a float we convert that
227
+ template <typename Clock, typename Duration>
228
+ class type_caster<std::chrono::time_point<Clock, Duration>>
229
+ : public duration_caster<std::chrono::time_point<Clock, Duration>> {};
230
+
231
+ template <typename Rep, typename Period>
232
+ class type_caster<std::chrono::duration<Rep, Period>>
233
+ : public duration_caster<std::chrono::duration<Rep, Period>> {};
234
+
235
+ PYBIND11_NAMESPACE_END(detail)
236
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/common.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #include "detail/common.h"
2
+ #warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'."
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/complex.h ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/complex.h: Complex number support
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+
14
+ #include <complex>
15
+
16
+ /// glibc defines I as a macro which breaks things, e.g., boost template names
17
+ #ifdef I
18
+ # undef I
19
+ #endif
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+
23
+ template <typename T>
24
+ struct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
25
+ static constexpr const char c = format_descriptor<T>::c;
26
+ static constexpr const char value[3] = {'Z', c, '\0'};
27
+ static std::string format() { return std::string(value); }
28
+ };
29
+
30
+ #ifndef PYBIND11_CPP17
31
+
32
+ template <typename T>
33
+ constexpr const char
34
+ format_descriptor<std::complex<T>,
35
+ detail::enable_if_t<std::is_floating_point<T>::value>>::value[3];
36
+
37
+ #endif
38
+
39
+ PYBIND11_NAMESPACE_BEGIN(detail)
40
+
41
+ template <typename T>
42
+ struct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
43
+ static constexpr bool value = true;
44
+ static constexpr int index = is_fmt_numeric<T>::index + 3;
45
+ };
46
+
47
+ template <typename T>
48
+ class type_caster<std::complex<T>> {
49
+ public:
50
+ bool load(handle src, bool convert) {
51
+ if (!src) {
52
+ return false;
53
+ }
54
+ if (!convert && !PyComplex_Check(src.ptr())) {
55
+ return false;
56
+ }
57
+ Py_complex result = PyComplex_AsCComplex(src.ptr());
58
+ if (result.real == -1.0 && PyErr_Occurred()) {
59
+ PyErr_Clear();
60
+ return false;
61
+ }
62
+ value = std::complex<T>((T) result.real, (T) result.imag);
63
+ return true;
64
+ }
65
+
66
+ static handle
67
+ cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
68
+ return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
69
+ }
70
+
71
+ PYBIND11_TYPE_CASTER(std::complex<T>, const_name("complex"));
72
+ };
73
+ PYBIND11_NAMESPACE_END(detail)
74
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/class.h ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/class.h: Python C API implementation details for py::class_
3
+
4
+ Copyright (c) 2017 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "../attr.h"
13
+ #include "../options.h"
14
+
15
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
16
+ PYBIND11_NAMESPACE_BEGIN(detail)
17
+
18
+ #if PY_VERSION_HEX >= 0x03030000 && !defined(PYPY_VERSION)
19
+ # define PYBIND11_BUILTIN_QUALNAME
20
+ # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
21
+ #else
22
+ // In pre-3.3 Python, we still set __qualname__ so that we can produce reliable function type
23
+ // signatures; in 3.3+ this macro expands to nothing:
24
+ # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) \
25
+ setattr((PyObject *) obj, "__qualname__", nameobj)
26
+ #endif
27
+
28
+ inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
29
+ #if !defined(PYPY_VERSION)
30
+ return type->tp_name;
31
+ #else
32
+ auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
33
+ if (module_name == PYBIND11_BUILTINS_MODULE)
34
+ return type->tp_name;
35
+ else
36
+ return std::move(module_name) + "." + type->tp_name;
37
+ #endif
38
+ }
39
+
40
+ inline PyTypeObject *type_incref(PyTypeObject *type) {
41
+ Py_INCREF(type);
42
+ return type;
43
+ }
44
+
45
+ #if !defined(PYPY_VERSION)
46
+
47
+ /// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
48
+ extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
49
+ return PyProperty_Type.tp_descr_get(self, cls, cls);
50
+ }
51
+
52
+ /// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
53
+ extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
54
+ PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
55
+ return PyProperty_Type.tp_descr_set(self, cls, value);
56
+ }
57
+
58
+ /** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
59
+ methods are modified to always use the object type instead of a concrete instance.
60
+ Return value: New reference. */
61
+ inline PyTypeObject *make_static_property_type() {
62
+ constexpr auto *name = "pybind11_static_property";
63
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
64
+
65
+ /* Danger zone: from now (and until PyType_Ready), make sure to
66
+ issue no Python C API calls which could potentially invoke the
67
+ garbage collector (the GC will call type_traverse(), which will in
68
+ turn find the newly constructed type in an invalid state) */
69
+ auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
70
+ if (!heap_type) {
71
+ pybind11_fail("make_static_property_type(): error allocating type!");
72
+ }
73
+
74
+ heap_type->ht_name = name_obj.inc_ref().ptr();
75
+ # ifdef PYBIND11_BUILTIN_QUALNAME
76
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
77
+ # endif
78
+
79
+ auto *type = &heap_type->ht_type;
80
+ type->tp_name = name;
81
+ type->tp_base = type_incref(&PyProperty_Type);
82
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
83
+ type->tp_descr_get = pybind11_static_get;
84
+ type->tp_descr_set = pybind11_static_set;
85
+
86
+ if (PyType_Ready(type) < 0) {
87
+ pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
88
+ }
89
+
90
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
91
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
92
+
93
+ return type;
94
+ }
95
+
96
+ #else // PYPY
97
+
98
+ /** PyPy has some issues with the above C API, so we evaluate Python code instead.
99
+ This function will only be called once so performance isn't really a concern.
100
+ Return value: New reference. */
101
+ inline PyTypeObject *make_static_property_type() {
102
+ auto d = dict();
103
+ PyObject *result = PyRun_String(R"(\
104
+ class pybind11_static_property(property):
105
+ def __get__(self, obj, cls):
106
+ return property.__get__(self, cls, cls)
107
+
108
+ def __set__(self, obj, value):
109
+ cls = obj if isinstance(obj, type) else type(obj)
110
+ property.__set__(self, cls, value)
111
+ )",
112
+ Py_file_input,
113
+ d.ptr(),
114
+ d.ptr());
115
+ if (result == nullptr)
116
+ throw error_already_set();
117
+ Py_DECREF(result);
118
+ return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
119
+ }
120
+
121
+ #endif // PYPY
122
+
123
+ /** Types with static properties need to handle `Type.static_prop = x` in a specific way.
124
+ By default, Python replaces the `static_property` itself, but for wrapped C++ types
125
+ we need to call `static_property.__set__()` in order to propagate the new value to
126
+ the underlying C++ data structure. */
127
+ extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
128
+ // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
129
+ // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
130
+ PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
131
+
132
+ // The following assignment combinations are possible:
133
+ // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
134
+ // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
135
+ // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
136
+ auto *const static_prop = (PyObject *) get_internals().static_property_type;
137
+ const auto call_descr_set = (descr != nullptr) && (value != nullptr)
138
+ && (PyObject_IsInstance(descr, static_prop) != 0)
139
+ && (PyObject_IsInstance(value, static_prop) == 0);
140
+ if (call_descr_set) {
141
+ // Call `static_property.__set__()` instead of replacing the `static_property`.
142
+ #if !defined(PYPY_VERSION)
143
+ return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
144
+ #else
145
+ if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
146
+ Py_DECREF(result);
147
+ return 0;
148
+ } else {
149
+ return -1;
150
+ }
151
+ #endif
152
+ } else {
153
+ // Replace existing attribute.
154
+ return PyType_Type.tp_setattro(obj, name, value);
155
+ }
156
+ }
157
+
158
+ #if PY_MAJOR_VERSION >= 3
159
+ /**
160
+ * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
161
+ * methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
162
+ * when called on a class, or a PyMethod, when called on an instance. Override that behaviour here
163
+ * to do a special case bypass for PyInstanceMethod_Types.
164
+ */
165
+ extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
166
+ PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
167
+ if (descr && PyInstanceMethod_Check(descr)) {
168
+ Py_INCREF(descr);
169
+ return descr;
170
+ }
171
+ return PyType_Type.tp_getattro(obj, name);
172
+ }
173
+ #endif
174
+
175
+ /// metaclass `__call__` function that is used to create all pybind11 objects.
176
+ extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
177
+
178
+ // use the default metaclass call to create/initialize the object
179
+ PyObject *self = PyType_Type.tp_call(type, args, kwargs);
180
+ if (self == nullptr) {
181
+ return nullptr;
182
+ }
183
+
184
+ // This must be a pybind11 instance
185
+ auto *instance = reinterpret_cast<detail::instance *>(self);
186
+
187
+ // Ensure that the base __init__ function(s) were called
188
+ for (const auto &vh : values_and_holders(instance)) {
189
+ if (!vh.holder_constructed()) {
190
+ PyErr_Format(PyExc_TypeError,
191
+ "%.200s.__init__() must be called when overriding __init__",
192
+ get_fully_qualified_tp_name(vh.type->type).c_str());
193
+ Py_DECREF(self);
194
+ return nullptr;
195
+ }
196
+ }
197
+
198
+ return self;
199
+ }
200
+
201
+ /// Cleanup the type-info for a pybind11-registered type.
202
+ extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
203
+ auto *type = (PyTypeObject *) obj;
204
+ auto &internals = get_internals();
205
+
206
+ // A pybind11-registered type will:
207
+ // 1) be found in internals.registered_types_py
208
+ // 2) have exactly one associated `detail::type_info`
209
+ auto found_type = internals.registered_types_py.find(type);
210
+ if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
211
+ && found_type->second[0]->type == type) {
212
+
213
+ auto *tinfo = found_type->second[0];
214
+ auto tindex = std::type_index(*tinfo->cpptype);
215
+ internals.direct_conversions.erase(tindex);
216
+
217
+ if (tinfo->module_local) {
218
+ get_local_internals().registered_types_cpp.erase(tindex);
219
+ } else {
220
+ internals.registered_types_cpp.erase(tindex);
221
+ }
222
+ internals.registered_types_py.erase(tinfo->type);
223
+
224
+ // Actually just `std::erase_if`, but that's only available in C++20
225
+ auto &cache = internals.inactive_override_cache;
226
+ for (auto it = cache.begin(), last = cache.end(); it != last;) {
227
+ if (it->first == (PyObject *) tinfo->type) {
228
+ it = cache.erase(it);
229
+ } else {
230
+ ++it;
231
+ }
232
+ }
233
+
234
+ delete tinfo;
235
+ }
236
+
237
+ PyType_Type.tp_dealloc(obj);
238
+ }
239
+
240
+ /** This metaclass is assigned by default to all pybind11 types and is required in order
241
+ for static properties to function correctly. Users may override this using `py::metaclass`.
242
+ Return value: New reference. */
243
+ inline PyTypeObject *make_default_metaclass() {
244
+ constexpr auto *name = "pybind11_type";
245
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
246
+
247
+ /* Danger zone: from now (and until PyType_Ready), make sure to
248
+ issue no Python C API calls which could potentially invoke the
249
+ garbage collector (the GC will call type_traverse(), which will in
250
+ turn find the newly constructed type in an invalid state) */
251
+ auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
252
+ if (!heap_type) {
253
+ pybind11_fail("make_default_metaclass(): error allocating metaclass!");
254
+ }
255
+
256
+ heap_type->ht_name = name_obj.inc_ref().ptr();
257
+ #ifdef PYBIND11_BUILTIN_QUALNAME
258
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
259
+ #endif
260
+
261
+ auto *type = &heap_type->ht_type;
262
+ type->tp_name = name;
263
+ type->tp_base = type_incref(&PyType_Type);
264
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
265
+
266
+ type->tp_call = pybind11_meta_call;
267
+
268
+ type->tp_setattro = pybind11_meta_setattro;
269
+ #if PY_MAJOR_VERSION >= 3
270
+ type->tp_getattro = pybind11_meta_getattro;
271
+ #endif
272
+
273
+ type->tp_dealloc = pybind11_meta_dealloc;
274
+
275
+ if (PyType_Ready(type) < 0) {
276
+ pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
277
+ }
278
+
279
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
280
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
281
+
282
+ return type;
283
+ }
284
+
285
+ /// For multiple inheritance types we need to recursively register/deregister base pointers for any
286
+ /// base classes with pointers that are difference from the instance value pointer so that we can
287
+ /// correctly recognize an offset base class pointer. This calls a function with any offset base
288
+ /// ptrs.
289
+ inline void traverse_offset_bases(void *valueptr,
290
+ const detail::type_info *tinfo,
291
+ instance *self,
292
+ bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
293
+ for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
294
+ if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
295
+ for (auto &c : parent_tinfo->implicit_casts) {
296
+ if (c.first == tinfo->cpptype) {
297
+ auto *parentptr = c.second(valueptr);
298
+ if (parentptr != valueptr) {
299
+ f(parentptr, self);
300
+ }
301
+ traverse_offset_bases(parentptr, parent_tinfo, self, f);
302
+ break;
303
+ }
304
+ }
305
+ }
306
+ }
307
+ }
308
+
309
+ inline bool register_instance_impl(void *ptr, instance *self) {
310
+ get_internals().registered_instances.emplace(ptr, self);
311
+ return true; // unused, but gives the same signature as the deregister func
312
+ }
313
+ inline bool deregister_instance_impl(void *ptr, instance *self) {
314
+ auto &registered_instances = get_internals().registered_instances;
315
+ auto range = registered_instances.equal_range(ptr);
316
+ for (auto it = range.first; it != range.second; ++it) {
317
+ if (self == it->second) {
318
+ registered_instances.erase(it);
319
+ return true;
320
+ }
321
+ }
322
+ return false;
323
+ }
324
+
325
+ inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
326
+ register_instance_impl(valptr, self);
327
+ if (!tinfo->simple_ancestors) {
328
+ traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
329
+ }
330
+ }
331
+
332
+ inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
333
+ bool ret = deregister_instance_impl(valptr, self);
334
+ if (!tinfo->simple_ancestors) {
335
+ traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
336
+ }
337
+ return ret;
338
+ }
339
+
340
+ /// Instance creation function for all pybind11 types. It allocates the internal instance layout
341
+ /// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
342
+ /// cast to a reference or pointer), and initialization is done by an `__init__` function.
343
+ inline PyObject *make_new_instance(PyTypeObject *type) {
344
+ #if defined(PYPY_VERSION)
345
+ // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
346
+ // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
347
+ ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
348
+ if (type->tp_basicsize < instance_size) {
349
+ type->tp_basicsize = instance_size;
350
+ }
351
+ #endif
352
+ PyObject *self = type->tp_alloc(type, 0);
353
+ auto *inst = reinterpret_cast<instance *>(self);
354
+ // Allocate the value/holder internals:
355
+ inst->allocate_layout();
356
+
357
+ return self;
358
+ }
359
+
360
+ /// Instance creation function for all pybind11 types. It only allocates space for the
361
+ /// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
362
+ extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
363
+ return make_new_instance(type);
364
+ }
365
+
366
+ /// An `__init__` function constructs the C++ object. Users should provide at least one
367
+ /// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
368
+ /// following default function will be used which simply throws an exception.
369
+ extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
370
+ PyTypeObject *type = Py_TYPE(self);
371
+ std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
372
+ PyErr_SetString(PyExc_TypeError, msg.c_str());
373
+ return -1;
374
+ }
375
+
376
+ inline void add_patient(PyObject *nurse, PyObject *patient) {
377
+ auto &internals = get_internals();
378
+ auto *instance = reinterpret_cast<detail::instance *>(nurse);
379
+ instance->has_patients = true;
380
+ Py_INCREF(patient);
381
+ internals.patients[nurse].push_back(patient);
382
+ }
383
+
384
+ inline void clear_patients(PyObject *self) {
385
+ auto *instance = reinterpret_cast<detail::instance *>(self);
386
+ auto &internals = get_internals();
387
+ auto pos = internals.patients.find(self);
388
+ assert(pos != internals.patients.end());
389
+ // Clearing the patients can cause more Python code to run, which
390
+ // can invalidate the iterator. Extract the vector of patients
391
+ // from the unordered_map first.
392
+ auto patients = std::move(pos->second);
393
+ internals.patients.erase(pos);
394
+ instance->has_patients = false;
395
+ for (PyObject *&patient : patients) {
396
+ Py_CLEAR(patient);
397
+ }
398
+ }
399
+
400
+ /// Clears all internal data from the instance and removes it from registered instances in
401
+ /// preparation for deallocation.
402
+ inline void clear_instance(PyObject *self) {
403
+ auto *instance = reinterpret_cast<detail::instance *>(self);
404
+
405
+ // Deallocate any values/holders, if present:
406
+ for (auto &v_h : values_and_holders(instance)) {
407
+ if (v_h) {
408
+
409
+ // We have to deregister before we call dealloc because, for virtual MI types, we still
410
+ // need to be able to get the parent pointers.
411
+ if (v_h.instance_registered()
412
+ && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
413
+ pybind11_fail(
414
+ "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
415
+ }
416
+
417
+ if (instance->owned || v_h.holder_constructed()) {
418
+ v_h.type->dealloc(v_h);
419
+ }
420
+ }
421
+ }
422
+ // Deallocate the value/holder layout internals:
423
+ instance->deallocate_layout();
424
+
425
+ if (instance->weakrefs) {
426
+ PyObject_ClearWeakRefs(self);
427
+ }
428
+
429
+ PyObject **dict_ptr = _PyObject_GetDictPtr(self);
430
+ if (dict_ptr) {
431
+ Py_CLEAR(*dict_ptr);
432
+ }
433
+
434
+ if (instance->has_patients) {
435
+ clear_patients(self);
436
+ }
437
+ }
438
+
439
+ /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
440
+ /// to destroy the C++ object itself, while the rest is Python bookkeeping.
441
+ extern "C" inline void pybind11_object_dealloc(PyObject *self) {
442
+ clear_instance(self);
443
+
444
+ auto *type = Py_TYPE(self);
445
+ type->tp_free(self);
446
+
447
+ #if PY_VERSION_HEX < 0x03080000
448
+ // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
449
+ // as part of a derived type's dealloc, in which case we're not allowed to decref
450
+ // the type here. For cross-module compatibility, we shouldn't compare directly
451
+ // with `pybind11_object_dealloc`, but with the common one stashed in internals.
452
+ auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
453
+ if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
454
+ Py_DECREF(type);
455
+ #else
456
+ // This was not needed before Python 3.8 (Python issue 35810)
457
+ // https://github.com/pybind/pybind11/issues/1946
458
+ Py_DECREF(type);
459
+ #endif
460
+ }
461
+
462
+ /** Create the type which can be used as a common base for all classes. This is
463
+ needed in order to satisfy Python's requirements for multiple inheritance.
464
+ Return value: New reference. */
465
+ inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
466
+ constexpr auto *name = "pybind11_object";
467
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
468
+
469
+ /* Danger zone: from now (and until PyType_Ready), make sure to
470
+ issue no Python C API calls which could potentially invoke the
471
+ garbage collector (the GC will call type_traverse(), which will in
472
+ turn find the newly constructed type in an invalid state) */
473
+ auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
474
+ if (!heap_type) {
475
+ pybind11_fail("make_object_base_type(): error allocating type!");
476
+ }
477
+
478
+ heap_type->ht_name = name_obj.inc_ref().ptr();
479
+ #ifdef PYBIND11_BUILTIN_QUALNAME
480
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
481
+ #endif
482
+
483
+ auto *type = &heap_type->ht_type;
484
+ type->tp_name = name;
485
+ type->tp_base = type_incref(&PyBaseObject_Type);
486
+ type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
487
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
488
+
489
+ type->tp_new = pybind11_object_new;
490
+ type->tp_init = pybind11_object_init;
491
+ type->tp_dealloc = pybind11_object_dealloc;
492
+
493
+ /* Support weak references (needed for the keep_alive feature) */
494
+ type->tp_weaklistoffset = offsetof(instance, weakrefs);
495
+
496
+ if (PyType_Ready(type) < 0) {
497
+ pybind11_fail("PyType_Ready failed in make_object_base_type():" + error_string());
498
+ }
499
+
500
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
501
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
502
+
503
+ assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
504
+ return (PyObject *) heap_type;
505
+ }
506
+
507
+ /// dynamic_attr: Support for `d = instance.__dict__`.
508
+ extern "C" inline PyObject *pybind11_get_dict(PyObject *self, void *) {
509
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
510
+ if (!dict) {
511
+ dict = PyDict_New();
512
+ }
513
+ Py_XINCREF(dict);
514
+ return dict;
515
+ }
516
+
517
+ /// dynamic_attr: Support for `instance.__dict__ = dict()`.
518
+ extern "C" inline int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *) {
519
+ if (!PyDict_Check(new_dict)) {
520
+ PyErr_Format(PyExc_TypeError,
521
+ "__dict__ must be set to a dictionary, not a '%.200s'",
522
+ get_fully_qualified_tp_name(Py_TYPE(new_dict)).c_str());
523
+ return -1;
524
+ }
525
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
526
+ Py_INCREF(new_dict);
527
+ Py_CLEAR(dict);
528
+ dict = new_dict;
529
+ return 0;
530
+ }
531
+
532
+ /// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
533
+ extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
534
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
535
+ Py_VISIT(dict);
536
+ return 0;
537
+ }
538
+
539
+ /// dynamic_attr: Allow the GC to clear the dictionary.
540
+ extern "C" inline int pybind11_clear(PyObject *self) {
541
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
542
+ Py_CLEAR(dict);
543
+ return 0;
544
+ }
545
+
546
+ /// Give instances of this type a `__dict__` and opt into garbage collection.
547
+ inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
548
+ auto *type = &heap_type->ht_type;
549
+ type->tp_flags |= Py_TPFLAGS_HAVE_GC;
550
+ type->tp_dictoffset = type->tp_basicsize; // place dict at the end
551
+ type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
552
+ type->tp_traverse = pybind11_traverse;
553
+ type->tp_clear = pybind11_clear;
554
+
555
+ static PyGetSetDef getset[] = {
556
+ {const_cast<char *>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
557
+ {nullptr, nullptr, nullptr, nullptr, nullptr}};
558
+ type->tp_getset = getset;
559
+ }
560
+
561
+ /// buffer_protocol: Fill in the view as specified by flags.
562
+ extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
563
+ // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
564
+ type_info *tinfo = nullptr;
565
+ for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
566
+ tinfo = get_type_info((PyTypeObject *) type.ptr());
567
+ if (tinfo && tinfo->get_buffer) {
568
+ break;
569
+ }
570
+ }
571
+ if (view == nullptr || !tinfo || !tinfo->get_buffer) {
572
+ if (view) {
573
+ view->obj = nullptr;
574
+ }
575
+ PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
576
+ return -1;
577
+ }
578
+ std::memset(view, 0, sizeof(Py_buffer));
579
+ buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
580
+ if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
581
+ delete info;
582
+ // view->obj = nullptr; // Was just memset to 0, so not necessary
583
+ PyErr_SetString(PyExc_BufferError, "Writable buffer requested for readonly storage");
584
+ return -1;
585
+ }
586
+ view->obj = obj;
587
+ view->ndim = 1;
588
+ view->internal = info;
589
+ view->buf = info->ptr;
590
+ view->itemsize = info->itemsize;
591
+ view->len = view->itemsize;
592
+ for (auto s : info->shape) {
593
+ view->len *= s;
594
+ }
595
+ view->readonly = static_cast<int>(info->readonly);
596
+ if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
597
+ view->format = const_cast<char *>(info->format.c_str());
598
+ }
599
+ if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
600
+ view->ndim = (int) info->ndim;
601
+ view->strides = info->strides.data();
602
+ view->shape = info->shape.data();
603
+ }
604
+ Py_INCREF(view->obj);
605
+ return 0;
606
+ }
607
+
608
+ /// buffer_protocol: Release the resources of the buffer.
609
+ extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
610
+ delete (buffer_info *) view->internal;
611
+ }
612
+
613
+ /// Give this type a buffer interface.
614
+ inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
615
+ heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
616
+ #if PY_MAJOR_VERSION < 3
617
+ heap_type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
618
+ #endif
619
+
620
+ heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
621
+ heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
622
+ }
623
+
624
+ /** Create a brand new Python type according to the `type_record` specification.
625
+ Return value: New reference. */
626
+ inline PyObject *make_new_python_type(const type_record &rec) {
627
+ auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
628
+
629
+ auto qualname = name;
630
+ if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
631
+ #if PY_MAJOR_VERSION >= 3
632
+ qualname = reinterpret_steal<object>(
633
+ PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
634
+ #else
635
+ qualname = str(rec.scope.attr("__qualname__").cast<std::string>() + "." + rec.name);
636
+ #endif
637
+ }
638
+
639
+ object module_;
640
+ if (rec.scope) {
641
+ if (hasattr(rec.scope, "__module__")) {
642
+ module_ = rec.scope.attr("__module__");
643
+ } else if (hasattr(rec.scope, "__name__")) {
644
+ module_ = rec.scope.attr("__name__");
645
+ }
646
+ }
647
+
648
+ const auto *full_name = c_str(
649
+ #if !defined(PYPY_VERSION)
650
+ module_ ? str(module_).cast<std::string>() + "." + rec.name :
651
+ #endif
652
+ rec.name);
653
+
654
+ char *tp_doc = nullptr;
655
+ if (rec.doc && options::show_user_defined_docstrings()) {
656
+ /* Allocate memory for docstring (using PyObject_MALLOC, since
657
+ Python will free this later on) */
658
+ size_t size = std::strlen(rec.doc) + 1;
659
+ tp_doc = (char *) PyObject_MALLOC(size);
660
+ std::memcpy((void *) tp_doc, rec.doc, size);
661
+ }
662
+
663
+ auto &internals = get_internals();
664
+ auto bases = tuple(rec.bases);
665
+ auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
666
+
667
+ /* Danger zone: from now (and until PyType_Ready), make sure to
668
+ issue no Python C API calls which could potentially invoke the
669
+ garbage collector (the GC will call type_traverse(), which will in
670
+ turn find the newly constructed type in an invalid state) */
671
+ auto *metaclass
672
+ = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
673
+
674
+ auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
675
+ if (!heap_type) {
676
+ pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
677
+ }
678
+
679
+ heap_type->ht_name = name.release().ptr();
680
+ #ifdef PYBIND11_BUILTIN_QUALNAME
681
+ heap_type->ht_qualname = qualname.inc_ref().ptr();
682
+ #endif
683
+
684
+ auto *type = &heap_type->ht_type;
685
+ type->tp_name = full_name;
686
+ type->tp_doc = tp_doc;
687
+ type->tp_base = type_incref((PyTypeObject *) base);
688
+ type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
689
+ if (!bases.empty()) {
690
+ type->tp_bases = bases.release().ptr();
691
+ }
692
+
693
+ /* Don't inherit base __init__ */
694
+ type->tp_init = pybind11_object_init;
695
+
696
+ /* Supported protocols */
697
+ type->tp_as_number = &heap_type->as_number;
698
+ type->tp_as_sequence = &heap_type->as_sequence;
699
+ type->tp_as_mapping = &heap_type->as_mapping;
700
+ #if PY_VERSION_HEX >= 0x03050000
701
+ type->tp_as_async = &heap_type->as_async;
702
+ #endif
703
+
704
+ /* Flags */
705
+ type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
706
+ #if PY_MAJOR_VERSION < 3
707
+ type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
708
+ #endif
709
+ if (!rec.is_final) {
710
+ type->tp_flags |= Py_TPFLAGS_BASETYPE;
711
+ }
712
+
713
+ if (rec.dynamic_attr) {
714
+ enable_dynamic_attributes(heap_type);
715
+ }
716
+
717
+ if (rec.buffer_protocol) {
718
+ enable_buffer_protocol(heap_type);
719
+ }
720
+
721
+ if (rec.custom_type_setup_callback) {
722
+ rec.custom_type_setup_callback(heap_type);
723
+ }
724
+
725
+ if (PyType_Ready(type) < 0) {
726
+ pybind11_fail(std::string(rec.name) + ": PyType_Ready failed (" + error_string() + ")!");
727
+ }
728
+
729
+ assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
730
+
731
+ /* Register type with the parent scope */
732
+ if (rec.scope) {
733
+ setattr(rec.scope, rec.name, (PyObject *) type);
734
+ } else {
735
+ Py_INCREF(type); // Keep it alive forever (reference leak)
736
+ }
737
+
738
+ if (module_) { // Needed by pydoc
739
+ setattr((PyObject *) type, "__module__", module_);
740
+ }
741
+
742
+ PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
743
+
744
+ return (PyObject *) type;
745
+ }
746
+
747
+ PYBIND11_NAMESPACE_END(detail)
748
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/common.h ADDED
@@ -0,0 +1,1210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/common.h -- Basic macros
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #define PYBIND11_VERSION_MAJOR 2
13
+ #define PYBIND11_VERSION_MINOR 9
14
+ #define PYBIND11_VERSION_PATCH 2
15
+
16
+ // Similar to Python's convention: https://docs.python.org/3/c-api/apiabiversion.html
17
+ // Additional convention: 0xD = dev
18
+ #define PYBIND11_VERSION_HEX 0x02090200
19
+
20
+ #define PYBIND11_NAMESPACE_BEGIN(name) namespace name {
21
+ #define PYBIND11_NAMESPACE_END(name) }
22
+
23
+ // Robust support for some features and loading modules compiled against different pybind versions
24
+ // requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute
25
+ // on the main `pybind11` namespace.
26
+ #if !defined(PYBIND11_NAMESPACE)
27
+ # ifdef __GNUG__
28
+ # define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
29
+ # else
30
+ # define PYBIND11_NAMESPACE pybind11
31
+ # endif
32
+ #endif
33
+
34
+ #if !(defined(_MSC_VER) && __cplusplus == 199711L)
35
+ # if __cplusplus >= 201402L
36
+ # define PYBIND11_CPP14
37
+ # if __cplusplus >= 201703L
38
+ # define PYBIND11_CPP17
39
+ # if __cplusplus >= 202002L
40
+ # define PYBIND11_CPP20
41
+ # endif
42
+ # endif
43
+ # endif
44
+ #elif defined(_MSC_VER) && __cplusplus == 199711L
45
+ // MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully
46
+ // implemented). Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3
47
+ // or newer.
48
+ # if _MSVC_LANG >= 201402L
49
+ # define PYBIND11_CPP14
50
+ # if _MSVC_LANG > 201402L && _MSC_VER >= 1910
51
+ # define PYBIND11_CPP17
52
+ # if _MSVC_LANG >= 202002L
53
+ # define PYBIND11_CPP20
54
+ # endif
55
+ # endif
56
+ # endif
57
+ #endif
58
+
59
+ // Compiler version assertions
60
+ #if defined(__INTEL_COMPILER)
61
+ # if __INTEL_COMPILER < 1800
62
+ # error pybind11 requires Intel C++ compiler v18 or newer
63
+ # elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)
64
+ # error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.
65
+ # endif
66
+ /* The following pragma cannot be pop'ed:
67
+ https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */
68
+ # pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
69
+ #elif defined(__clang__) && !defined(__apple_build_version__)
70
+ # if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
71
+ # error pybind11 requires clang 3.3 or newer
72
+ # endif
73
+ #elif defined(__clang__)
74
+ // Apple changes clang version macros to its Xcode version; the first Xcode release based on
75
+ // (upstream) clang 3.3 was Xcode 5:
76
+ # if __clang_major__ < 5
77
+ # error pybind11 requires Xcode/clang 5.0 or newer
78
+ # endif
79
+ #elif defined(__GNUG__)
80
+ # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
81
+ # error pybind11 requires gcc 4.8 or newer
82
+ # endif
83
+ #elif defined(_MSC_VER)
84
+ // Pybind hits various compiler bugs in 2015u2 and earlier, and also makes use of some stl features
85
+ // (e.g. std::negation) added in 2015u3:
86
+ # if _MSC_FULL_VER < 190024210
87
+ # error pybind11 requires MSVC 2015 update 3 or newer
88
+ # endif
89
+ #endif
90
+
91
+ #if !defined(PYBIND11_EXPORT)
92
+ # if defined(WIN32) || defined(_WIN32)
93
+ # define PYBIND11_EXPORT __declspec(dllexport)
94
+ # else
95
+ # define PYBIND11_EXPORT __attribute__((visibility("default")))
96
+ # endif
97
+ #endif
98
+
99
+ #if !defined(PYBIND11_EXPORT_EXCEPTION)
100
+ # ifdef __MINGW32__
101
+ // workaround for:
102
+ // error: 'dllexport' implies default visibility, but xxx has already been declared with a
103
+ // different visibility
104
+ # define PYBIND11_EXPORT_EXCEPTION
105
+ # else
106
+ # define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
107
+ # endif
108
+ #endif
109
+
110
+ // For CUDA, GCC7, GCC8:
111
+ // PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.
112
+ // When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.
113
+ // However, the measured shared-library size saving when using noinline are only
114
+ // 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,
115
+ // the default under pybind11/tests).
116
+ #if !defined(PYBIND11_NOINLINE_FORCED) \
117
+ && (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))
118
+ # define PYBIND11_NOINLINE_DISABLED
119
+ #endif
120
+
121
+ // The PYBIND11_NOINLINE macro is for function DEFINITIONS.
122
+ // In contrast, FORWARD DECLARATIONS should never use this macro:
123
+ // https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions
124
+ #if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.
125
+ # define PYBIND11_NOINLINE inline
126
+ #elif defined(_MSC_VER)
127
+ # define PYBIND11_NOINLINE __declspec(noinline) inline
128
+ #else
129
+ # define PYBIND11_NOINLINE __attribute__((noinline)) inline
130
+ #endif
131
+
132
+ #if defined(__MINGW32__)
133
+ // For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
134
+ // whether it is used or not
135
+ # define PYBIND11_DEPRECATED(reason)
136
+ #elif defined(PYBIND11_CPP14)
137
+ # define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
138
+ #else
139
+ # define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
140
+ #endif
141
+
142
+ #if defined(PYBIND11_CPP17)
143
+ # define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
144
+ #elif defined(_MSC_VER) && !defined(__clang__)
145
+ # define PYBIND11_MAYBE_UNUSED
146
+ #else
147
+ # define PYBIND11_MAYBE_UNUSED __attribute__((__unused__))
148
+ #endif
149
+
150
+ /* Don't let Python.h #define (v)snprintf as macro because they are implemented
151
+ properly in Visual Studio since 2015. */
152
+ #if defined(_MSC_VER) && _MSC_VER >= 1900
153
+ # define HAVE_SNPRINTF 1
154
+ #endif
155
+
156
+ /// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
157
+ #if defined(_MSC_VER)
158
+ # pragma warning(push)
159
+ // C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
160
+ # pragma warning(disable : 4505)
161
+ # if defined(_DEBUG) && !defined(Py_DEBUG)
162
+ // Workaround for a VS 2022 issue.
163
+ // NOTE: This workaround knowingly violates the Python.h include order requirement:
164
+ // https://docs.python.org/3/c-api/intro.html#include-files
165
+ // See https://github.com/pybind/pybind11/pull/3497 for full context.
166
+ # include <yvals.h>
167
+ # if _MSVC_STL_VERSION >= 143
168
+ # include <crtdefs.h>
169
+ # endif
170
+ # define PYBIND11_DEBUG_MARKER
171
+ # undef _DEBUG
172
+ # endif
173
+ #endif
174
+
175
+ // https://en.cppreference.com/w/c/chrono/localtime
176
+ #if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
177
+ # define __STDC_WANT_LIB_EXT1__
178
+ #endif
179
+
180
+ #ifdef __has_include
181
+ // std::optional (but including it in c++14 mode isn't allowed)
182
+ # if defined(PYBIND11_CPP17) && __has_include(<optional>)
183
+ # define PYBIND11_HAS_OPTIONAL 1
184
+ # endif
185
+ // std::experimental::optional (but not allowed in c++11 mode)
186
+ # if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
187
+ !__has_include(<optional>))
188
+ # define PYBIND11_HAS_EXP_OPTIONAL 1
189
+ # endif
190
+ // std::variant
191
+ # if defined(PYBIND11_CPP17) && __has_include(<variant>)
192
+ # define PYBIND11_HAS_VARIANT 1
193
+ # endif
194
+ #elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
195
+ # define PYBIND11_HAS_OPTIONAL 1
196
+ # define PYBIND11_HAS_VARIANT 1
197
+ #endif
198
+
199
+ #if defined(PYBIND11_CPP17)
200
+ # if defined(__has_include)
201
+ # if __has_include(<string_view>)
202
+ # define PYBIND11_HAS_STRING_VIEW
203
+ # endif
204
+ # elif defined(_MSC_VER)
205
+ # define PYBIND11_HAS_STRING_VIEW
206
+ # endif
207
+ #endif
208
+
209
+ #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
210
+ # define PYBIND11_HAS_U8STRING
211
+ #endif
212
+
213
+ #include <Python.h>
214
+ #include <frameobject.h>
215
+ #include <pythread.h>
216
+
217
+ /* Python #defines overrides on all sorts of core functions, which
218
+ tends to weak havok in C++ codebases that expect these to work
219
+ like regular functions (potentially with several overloads) */
220
+ #if defined(isalnum)
221
+ # undef isalnum
222
+ # undef isalpha
223
+ # undef islower
224
+ # undef isspace
225
+ # undef isupper
226
+ # undef tolower
227
+ # undef toupper
228
+ #endif
229
+
230
+ #if defined(copysign)
231
+ # undef copysign
232
+ #endif
233
+
234
+ #if defined(_MSC_VER)
235
+ # if defined(PYBIND11_DEBUG_MARKER)
236
+ # define _DEBUG
237
+ # undef PYBIND11_DEBUG_MARKER
238
+ # endif
239
+ # pragma warning(pop)
240
+ #endif
241
+
242
+ #include <cstddef>
243
+ #include <cstring>
244
+ #include <exception>
245
+ #include <forward_list>
246
+ #include <memory>
247
+ #include <stdexcept>
248
+ #include <string>
249
+ #include <type_traits>
250
+ #include <typeindex>
251
+ #include <unordered_map>
252
+ #include <unordered_set>
253
+ #include <vector>
254
+ #if defined(__has_include)
255
+ # if __has_include(<version>)
256
+ # include <version>
257
+ # endif
258
+ #endif
259
+
260
+ // #define PYBIND11_STR_LEGACY_PERMISSIVE
261
+ // If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
262
+ // (probably surprising and never documented, but this was the
263
+ // legacy behavior until and including v2.6.x). As a side-effect,
264
+ // pybind11::isinstance<str>() is true for both pybind11::str and
265
+ // pybind11::bytes.
266
+ // If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
267
+ // pybind11::isinstance<str>() is true only for pybind11::str.
268
+ // However, for Python 2 only (!), the pybind11::str caster
269
+ // implicitly decodes bytes to PyUnicodeObject. This is to ease
270
+ // the transition from the legacy behavior to the non-permissive
271
+ // behavior.
272
+
273
+ #if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
274
+ # define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
275
+ # define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
276
+ # define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
277
+ # define PYBIND11_BYTES_CHECK PyBytes_Check
278
+ # define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
279
+ # define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
280
+ # define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
281
+ # define PYBIND11_BYTES_AS_STRING PyBytes_AsString
282
+ # define PYBIND11_BYTES_SIZE PyBytes_Size
283
+ # define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
284
+ # define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
285
+ # define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))
286
+ # define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))
287
+ # define PYBIND11_BYTES_NAME "bytes"
288
+ # define PYBIND11_STRING_NAME "str"
289
+ # define PYBIND11_SLICE_OBJECT PyObject
290
+ # define PYBIND11_FROM_STRING PyUnicode_FromString
291
+ # define PYBIND11_STR_TYPE ::pybind11::str
292
+ # define PYBIND11_BOOL_ATTR "__bool__"
293
+ # define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
294
+ # define PYBIND11_BUILTINS_MODULE "builtins"
295
+ // Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
296
+ // See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
297
+ # define PYBIND11_PLUGIN_IMPL(name) \
298
+ extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name(); \
299
+ extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
300
+
301
+ #else
302
+ # define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
303
+ # define PYBIND11_INSTANCE_METHOD_CHECK PyMethod_Check
304
+ # define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyMethod_GET_FUNCTION
305
+ # define PYBIND11_BYTES_CHECK PyString_Check
306
+ # define PYBIND11_BYTES_FROM_STRING PyString_FromString
307
+ # define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
308
+ # define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
309
+ # define PYBIND11_BYTES_AS_STRING PyString_AsString
310
+ # define PYBIND11_BYTES_SIZE PyString_Size
311
+ # define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
312
+ # define PYBIND11_LONG_AS_LONGLONG(o) \
313
+ (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
314
+ # define PYBIND11_LONG_FROM_SIGNED(o) PyInt_FromSsize_t((ssize_t) o) // Returns long if needed.
315
+ # define PYBIND11_LONG_FROM_UNSIGNED(o) PyInt_FromSize_t((size_t) o) // Returns long if needed.
316
+ # define PYBIND11_BYTES_NAME "str"
317
+ # define PYBIND11_STRING_NAME "unicode"
318
+ # define PYBIND11_SLICE_OBJECT PySliceObject
319
+ # define PYBIND11_FROM_STRING PyString_FromString
320
+ # define PYBIND11_STR_TYPE ::pybind11::bytes
321
+ # define PYBIND11_BOOL_ATTR "__nonzero__"
322
+ # define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_nonzero)
323
+ # define PYBIND11_BUILTINS_MODULE "__builtin__"
324
+ // Providing a separate PyInit decl to make Clang's -Wmissing-prototypes happy.
325
+ // See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
326
+ # define PYBIND11_PLUGIN_IMPL(name) \
327
+ static PyObject *pybind11_init_wrapper(); \
328
+ extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT void init##name(); \
329
+ extern "C" PYBIND11_EXPORT void init##name() { (void) pybind11_init_wrapper(); } \
330
+ PyObject *pybind11_init_wrapper()
331
+ #endif
332
+
333
+ #if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
334
+ extern "C" {
335
+ struct _Py_atomic_address {
336
+ void *value;
337
+ };
338
+ PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
339
+ }
340
+ #endif
341
+
342
+ #define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
343
+ #define PYBIND11_STRINGIFY(x) #x
344
+ #define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
345
+ #define PYBIND11_CONCAT(first, second) first##second
346
+ #define PYBIND11_ENSURE_INTERNALS_READY pybind11::detail::get_internals();
347
+
348
+ #define PYBIND11_CHECK_PYTHON_VERSION \
349
+ { \
350
+ const char *compiled_ver \
351
+ = PYBIND11_TOSTRING(PY_MAJOR_VERSION) "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
352
+ const char *runtime_ver = Py_GetVersion(); \
353
+ size_t len = std::strlen(compiled_ver); \
354
+ if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
355
+ || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
356
+ PyErr_Format(PyExc_ImportError, \
357
+ "Python version mismatch: module was compiled for Python %s, " \
358
+ "but the interpreter version is incompatible: %s.", \
359
+ compiled_ver, \
360
+ runtime_ver); \
361
+ return nullptr; \
362
+ } \
363
+ }
364
+
365
+ #if PY_VERSION_HEX >= 0x03030000
366
+
367
+ # define PYBIND11_CATCH_INIT_EXCEPTIONS \
368
+ catch (pybind11::error_already_set & e) { \
369
+ pybind11::raise_from(e, PyExc_ImportError, "initialization failed"); \
370
+ return nullptr; \
371
+ } \
372
+ catch (const std::exception &e) { \
373
+ PyErr_SetString(PyExc_ImportError, e.what()); \
374
+ return nullptr; \
375
+ }
376
+
377
+ #else
378
+
379
+ # define PYBIND11_CATCH_INIT_EXCEPTIONS \
380
+ catch (pybind11::error_already_set & e) { \
381
+ PyErr_SetString(PyExc_ImportError, e.what()); \
382
+ return nullptr; \
383
+ } \
384
+ catch (const std::exception &e) { \
385
+ PyErr_SetString(PyExc_ImportError, e.what()); \
386
+ return nullptr; \
387
+ }
388
+
389
+ #endif
390
+
391
+ /** \rst
392
+ ***Deprecated in favor of PYBIND11_MODULE***
393
+
394
+ This macro creates the entry point that will be invoked when the Python interpreter
395
+ imports a plugin library. Please create a `module_` in the function body and return
396
+ the pointer to its underlying Python object at the end.
397
+
398
+ .. code-block:: cpp
399
+
400
+ PYBIND11_PLUGIN(example) {
401
+ pybind11::module_ m("example", "pybind11 example plugin");
402
+ /// Set up bindings here
403
+ return m.ptr();
404
+ }
405
+ \endrst */
406
+ #define PYBIND11_PLUGIN(name) \
407
+ PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
408
+ static PyObject *pybind11_init(); \
409
+ PYBIND11_PLUGIN_IMPL(name) { \
410
+ PYBIND11_CHECK_PYTHON_VERSION \
411
+ PYBIND11_ENSURE_INTERNALS_READY \
412
+ try { \
413
+ return pybind11_init(); \
414
+ } \
415
+ PYBIND11_CATCH_INIT_EXCEPTIONS \
416
+ } \
417
+ PyObject *pybind11_init()
418
+
419
+ /** \rst
420
+ This macro creates the entry point that will be invoked when the Python interpreter
421
+ imports an extension module. The module name is given as the fist argument and it
422
+ should not be in quotes. The second macro argument defines a variable of type
423
+ `py::module_` which can be used to initialize the module.
424
+
425
+ The entry point is marked as "maybe unused" to aid dead-code detection analysis:
426
+ since the entry point is typically only looked up at runtime and not referenced
427
+ during translation, it would otherwise appear as unused ("dead") code.
428
+
429
+ .. code-block:: cpp
430
+
431
+ PYBIND11_MODULE(example, m) {
432
+ m.doc() = "pybind11 example module";
433
+
434
+ // Add bindings here
435
+ m.def("foo", []() {
436
+ return "Hello, World!";
437
+ });
438
+ }
439
+ \endrst */
440
+ #define PYBIND11_MODULE(name, variable) \
441
+ static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name) \
442
+ PYBIND11_MAYBE_UNUSED; \
443
+ PYBIND11_MAYBE_UNUSED \
444
+ static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
445
+ PYBIND11_PLUGIN_IMPL(name) { \
446
+ PYBIND11_CHECK_PYTHON_VERSION \
447
+ PYBIND11_ENSURE_INTERNALS_READY \
448
+ auto m = ::pybind11::module_::create_extension_module( \
449
+ PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
450
+ try { \
451
+ PYBIND11_CONCAT(pybind11_init_, name)(m); \
452
+ return m.ptr(); \
453
+ } \
454
+ PYBIND11_CATCH_INIT_EXCEPTIONS \
455
+ } \
456
+ void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ & (variable))
457
+
458
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
459
+
460
+ using ssize_t = Py_ssize_t;
461
+ using size_t = std::size_t;
462
+
463
+ template <typename IntType>
464
+ inline ssize_t ssize_t_cast(const IntType &val) {
465
+ static_assert(sizeof(IntType) <= sizeof(ssize_t), "Implicit narrowing is not permitted.");
466
+ return static_cast<ssize_t>(val);
467
+ }
468
+
469
+ /// Approach used to cast a previously unknown C++ instance into a Python object
470
+ enum class return_value_policy : uint8_t {
471
+ /** This is the default return value policy, which falls back to the policy
472
+ return_value_policy::take_ownership when the return value is a pointer.
473
+ Otherwise, it uses return_value::move or return_value::copy for rvalue
474
+ and lvalue references, respectively. See below for a description of what
475
+ all of these different policies do. */
476
+ automatic = 0,
477
+
478
+ /** As above, but use policy return_value_policy::reference when the return
479
+ value is a pointer. This is the default conversion policy for function
480
+ arguments when calling Python functions manually from C++ code (i.e. via
481
+ handle::operator()). You probably won't need to use this. */
482
+ automatic_reference,
483
+
484
+ /** Reference an existing object (i.e. do not create a new copy) and take
485
+ ownership. Python will call the destructor and delete operator when the
486
+ object’s reference count reaches zero. Undefined behavior ensues when
487
+ the C++ side does the same.. */
488
+ take_ownership,
489
+
490
+ /** Create a new copy of the returned object, which will be owned by
491
+ Python. This policy is comparably safe because the lifetimes of the two
492
+ instances are decoupled. */
493
+ copy,
494
+
495
+ /** Use std::move to move the return value contents into a new instance
496
+ that will be owned by Python. This policy is comparably safe because the
497
+ lifetimes of the two instances (move source and destination) are
498
+ decoupled. */
499
+ move,
500
+
501
+ /** Reference an existing object, but do not take ownership. The C++ side
502
+ is responsible for managing the object’s lifetime and deallocating it
503
+ when it is no longer used. Warning: undefined behavior will ensue when
504
+ the C++ side deletes an object that is still referenced and used by
505
+ Python. */
506
+ reference,
507
+
508
+ /** This policy only applies to methods and properties. It references the
509
+ object without taking ownership similar to the above
510
+ return_value_policy::reference policy. In contrast to that policy, the
511
+ function or property’s implicit this argument (called the parent) is
512
+ considered to be the the owner of the return value (the child).
513
+ pybind11 then couples the lifetime of the parent to the child via a
514
+ reference relationship that ensures that the parent cannot be garbage
515
+ collected while Python is still using the child. More advanced
516
+ variations of this scheme are also possible using combinations of
517
+ return_value_policy::reference and the keep_alive call policy */
518
+ reference_internal
519
+ };
520
+
521
+ PYBIND11_NAMESPACE_BEGIN(detail)
522
+
523
+ inline static constexpr int log2(size_t n, int k = 0) {
524
+ return (n <= 1) ? k : log2(n >> 1, k + 1);
525
+ }
526
+
527
+ // Returns the size as a multiple of sizeof(void *), rounded up.
528
+ inline static constexpr size_t size_in_ptrs(size_t s) {
529
+ return 1 + ((s - 1) >> log2(sizeof(void *)));
530
+ }
531
+
532
+ /**
533
+ * The space to allocate for simple layout instance holders (see below) in multiple of the size of
534
+ * a pointer (e.g. 2 means 16 bytes on 64-bit architectures). The default is the minimum required
535
+ * to holder either a std::unique_ptr or std::shared_ptr (which is almost always
536
+ * sizeof(std::shared_ptr<T>)).
537
+ */
538
+ constexpr size_t instance_simple_holder_in_ptrs() {
539
+ static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
540
+ "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
541
+ return size_in_ptrs(sizeof(std::shared_ptr<int>));
542
+ }
543
+
544
+ // Forward declarations
545
+ struct type_info;
546
+ struct value_and_holder;
547
+
548
+ struct nonsimple_values_and_holders {
549
+ void **values_and_holders;
550
+ uint8_t *status;
551
+ };
552
+
553
+ /// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
554
+ struct instance {
555
+ PyObject_HEAD
556
+ /// Storage for pointers and holder; see simple_layout, below, for a description
557
+ union {
558
+ void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
559
+ nonsimple_values_and_holders nonsimple;
560
+ };
561
+ /// Weak references
562
+ PyObject *weakrefs;
563
+ /// If true, the pointer is owned which means we're free to manage it with a holder.
564
+ bool owned : 1;
565
+ /**
566
+ * An instance has two possible value/holder layouts.
567
+ *
568
+ * Simple layout (when this flag is true), means the `simple_value_holder` is set with a
569
+ * pointer and the holder object governing that pointer, i.e. [val1*][holder]. This layout is
570
+ * applied whenever there is no python-side multiple inheritance of bound C++ types *and* the
571
+ * type's holder will fit in the default space (which is large enough to hold either a
572
+ * std::unique_ptr or std::shared_ptr).
573
+ *
574
+ * Non-simple layout applies when using custom holders that require more space than
575
+ * `shared_ptr` (which is typically the size of two pointers), or when multiple inheritance is
576
+ * used on the python side. Non-simple layout allocates the required amount of memory to have
577
+ * multiple bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is
578
+ * set to a pointer to allocated space of the required space to hold a sequence of value
579
+ * pointers and holders followed `status`, a set of bit flags (1 byte each), i.e.
580
+ * [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple
581
+ * of `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the beginning of
582
+ * the [bb...] block (but not independently allocated).
583
+ *
584
+ * Status bits indicate whether the associated holder is constructed (&
585
+ * status_holder_constructed) and whether the value pointer is registered (&
586
+ * status_instance_registered) in `registered_instances`.
587
+ */
588
+ bool simple_layout : 1;
589
+ /// For simple layout, tracks whether the holder has been constructed
590
+ bool simple_holder_constructed : 1;
591
+ /// For simple layout, tracks whether the instance is registered in `registered_instances`
592
+ bool simple_instance_registered : 1;
593
+ /// If true, get_internals().patients has an entry for this object
594
+ bool has_patients : 1;
595
+
596
+ /// Initializes all of the above type/values/holders data (but not the instance values
597
+ /// themselves)
598
+ void allocate_layout();
599
+
600
+ /// Destroys/deallocates all of the above
601
+ void deallocate_layout();
602
+
603
+ /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
604
+ /// omitted). Returns a default-constructed (with `.inst = nullptr`) object on failure if
605
+ /// `throw_if_missing` is false.
606
+ value_and_holder get_value_and_holder(const type_info *find_type = nullptr,
607
+ bool throw_if_missing = true);
608
+
609
+ /// Bit values for the non-simple status flags
610
+ static constexpr uint8_t status_holder_constructed = 1;
611
+ static constexpr uint8_t status_instance_registered = 2;
612
+ };
613
+
614
+ static_assert(std::is_standard_layout<instance>::value,
615
+ "Internal error: `pybind11::detail::instance` is not standard layout!");
616
+
617
+ /// from __cpp_future__ import (convenient aliases from C++14/17)
618
+ #if defined(PYBIND11_CPP14) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
619
+ using std::conditional_t;
620
+ using std::enable_if_t;
621
+ using std::remove_cv_t;
622
+ using std::remove_reference_t;
623
+ #else
624
+ template <bool B, typename T = void>
625
+ using enable_if_t = typename std::enable_if<B, T>::type;
626
+ template <bool B, typename T, typename F>
627
+ using conditional_t = typename std::conditional<B, T, F>::type;
628
+ template <typename T>
629
+ using remove_cv_t = typename std::remove_cv<T>::type;
630
+ template <typename T>
631
+ using remove_reference_t = typename std::remove_reference<T>::type;
632
+ #endif
633
+
634
+ #if defined(PYBIND11_CPP20)
635
+ using std::remove_cvref;
636
+ using std::remove_cvref_t;
637
+ #else
638
+ template <class T>
639
+ struct remove_cvref {
640
+ using type = remove_cv_t<remove_reference_t<T>>;
641
+ };
642
+ template <class T>
643
+ using remove_cvref_t = typename remove_cvref<T>::type;
644
+ #endif
645
+
646
+ /// Index sequences
647
+ #if defined(PYBIND11_CPP14)
648
+ using std::index_sequence;
649
+ using std::make_index_sequence;
650
+ #else
651
+ template <size_t...>
652
+ struct index_sequence {};
653
+ template <size_t N, size_t... S>
654
+ struct make_index_sequence_impl : make_index_sequence_impl<N - 1, N - 1, S...> {};
655
+ template <size_t... S>
656
+ struct make_index_sequence_impl<0, S...> {
657
+ using type = index_sequence<S...>;
658
+ };
659
+ template <size_t N>
660
+ using make_index_sequence = typename make_index_sequence_impl<N>::type;
661
+ #endif
662
+
663
+ /// Make an index sequence of the indices of true arguments
664
+ template <typename ISeq, size_t, bool...>
665
+ struct select_indices_impl {
666
+ using type = ISeq;
667
+ };
668
+ template <size_t... IPrev, size_t I, bool B, bool... Bs>
669
+ struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
670
+ : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>,
671
+ I + 1,
672
+ Bs...> {};
673
+ template <bool... Bs>
674
+ using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
675
+
676
+ /// Backports of std::bool_constant and std::negation to accommodate older compilers
677
+ template <bool B>
678
+ using bool_constant = std::integral_constant<bool, B>;
679
+ template <typename T>
680
+ struct negation : bool_constant<!T::value> {};
681
+
682
+ // PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
683
+ // using the new one (C++14 defect, so generally works on newer compilers, even
684
+ // if not in C++17 mode)
685
+ #if defined(__PGIC__) || defined(__INTEL_COMPILER)
686
+ template <typename...>
687
+ using void_t = void;
688
+ #else
689
+ template <typename...>
690
+ struct void_t_impl {
691
+ using type = void;
692
+ };
693
+ template <typename... Ts>
694
+ using void_t = typename void_t_impl<Ts...>::type;
695
+ #endif
696
+
697
+ /// Compile-time all/any/none of that check the boolean value of all template types
698
+ #if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
699
+ template <class... Ts>
700
+ using all_of = bool_constant<(Ts::value && ...)>;
701
+ template <class... Ts>
702
+ using any_of = bool_constant<(Ts::value || ...)>;
703
+ #elif !defined(_MSC_VER)
704
+ template <bool...>
705
+ struct bools {};
706
+ template <class... Ts>
707
+ using all_of = std::is_same<bools<Ts::value..., true>, bools<true, Ts::value...>>;
708
+ template <class... Ts>
709
+ using any_of = negation<all_of<negation<Ts>...>>;
710
+ #else
711
+ // MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
712
+ // at a slight loss of compilation efficiency).
713
+ template <class... Ts>
714
+ using all_of = std::conjunction<Ts...>;
715
+ template <class... Ts>
716
+ using any_of = std::disjunction<Ts...>;
717
+ #endif
718
+ template <class... Ts>
719
+ using none_of = negation<any_of<Ts...>>;
720
+
721
+ template <class T, template <class> class... Predicates>
722
+ using satisfies_all_of = all_of<Predicates<T>...>;
723
+ template <class T, template <class> class... Predicates>
724
+ using satisfies_any_of = any_of<Predicates<T>...>;
725
+ template <class T, template <class> class... Predicates>
726
+ using satisfies_none_of = none_of<Predicates<T>...>;
727
+
728
+ /// Strip the class from a method type
729
+ template <typename T>
730
+ struct remove_class {};
731
+ template <typename C, typename R, typename... A>
732
+ struct remove_class<R (C::*)(A...)> {
733
+ using type = R(A...);
734
+ };
735
+ template <typename C, typename R, typename... A>
736
+ struct remove_class<R (C::*)(A...) const> {
737
+ using type = R(A...);
738
+ };
739
+
740
+ /// Helper template to strip away type modifiers
741
+ template <typename T>
742
+ struct intrinsic_type {
743
+ using type = T;
744
+ };
745
+ template <typename T>
746
+ struct intrinsic_type<const T> {
747
+ using type = typename intrinsic_type<T>::type;
748
+ };
749
+ template <typename T>
750
+ struct intrinsic_type<T *> {
751
+ using type = typename intrinsic_type<T>::type;
752
+ };
753
+ template <typename T>
754
+ struct intrinsic_type<T &> {
755
+ using type = typename intrinsic_type<T>::type;
756
+ };
757
+ template <typename T>
758
+ struct intrinsic_type<T &&> {
759
+ using type = typename intrinsic_type<T>::type;
760
+ };
761
+ template <typename T, size_t N>
762
+ struct intrinsic_type<const T[N]> {
763
+ using type = typename intrinsic_type<T>::type;
764
+ };
765
+ template <typename T, size_t N>
766
+ struct intrinsic_type<T[N]> {
767
+ using type = typename intrinsic_type<T>::type;
768
+ };
769
+ template <typename T>
770
+ using intrinsic_t = typename intrinsic_type<T>::type;
771
+
772
+ /// Helper type to replace 'void' in some expressions
773
+ struct void_type {};
774
+
775
+ /// Helper template which holds a list of types
776
+ template <typename...>
777
+ struct type_list {};
778
+
779
+ /// Compile-time integer sum
780
+ #ifdef __cpp_fold_expressions
781
+ template <typename... Ts>
782
+ constexpr size_t constexpr_sum(Ts... ns) {
783
+ return (0 + ... + size_t{ns});
784
+ }
785
+ #else
786
+ constexpr size_t constexpr_sum() { return 0; }
787
+ template <typename T, typename... Ts>
788
+ constexpr size_t constexpr_sum(T n, Ts... ns) {
789
+ return size_t{n} + constexpr_sum(ns...);
790
+ }
791
+ #endif
792
+
793
+ PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
794
+ /// Implementation details for constexpr functions
795
+ constexpr int first(int i) { return i; }
796
+ template <typename T, typename... Ts>
797
+ constexpr int first(int i, T v, Ts... vs) {
798
+ return v ? i : first(i + 1, vs...);
799
+ }
800
+
801
+ constexpr int last(int /*i*/, int result) { return result; }
802
+ template <typename T, typename... Ts>
803
+ constexpr int last(int i, int result, T v, Ts... vs) {
804
+ return last(i + 1, v ? i : result, vs...);
805
+ }
806
+ PYBIND11_NAMESPACE_END(constexpr_impl)
807
+
808
+ /// Return the index of the first type in Ts which satisfies Predicate<T>.
809
+ /// Returns sizeof...(Ts) if none match.
810
+ template <template <typename> class Predicate, typename... Ts>
811
+ constexpr int constexpr_first() {
812
+ return constexpr_impl::first(0, Predicate<Ts>::value...);
813
+ }
814
+
815
+ /// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
816
+ template <template <typename> class Predicate, typename... Ts>
817
+ constexpr int constexpr_last() {
818
+ return constexpr_impl::last(0, -1, Predicate<Ts>::value...);
819
+ }
820
+
821
+ /// Return the Nth element from the parameter pack
822
+ template <size_t N, typename T, typename... Ts>
823
+ struct pack_element {
824
+ using type = typename pack_element<N - 1, Ts...>::type;
825
+ };
826
+ template <typename T, typename... Ts>
827
+ struct pack_element<0, T, Ts...> {
828
+ using type = T;
829
+ };
830
+
831
+ /// Return the one and only type which matches the predicate, or Default if none match.
832
+ /// If more than one type matches the predicate, fail at compile-time.
833
+ template <template <typename> class Predicate, typename Default, typename... Ts>
834
+ struct exactly_one {
835
+ static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
836
+ static_assert(found <= 1, "Found more than one type matching the predicate");
837
+
838
+ static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
839
+ using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
840
+ };
841
+ template <template <typename> class P, typename Default>
842
+ struct exactly_one<P, Default> {
843
+ using type = Default;
844
+ };
845
+
846
+ template <template <typename> class Predicate, typename Default, typename... Ts>
847
+ using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
848
+
849
+ /// Defer the evaluation of type T until types Us are instantiated
850
+ template <typename T, typename... /*Us*/>
851
+ struct deferred_type {
852
+ using type = T;
853
+ };
854
+ template <typename T, typename... Us>
855
+ using deferred_t = typename deferred_type<T, Us...>::type;
856
+
857
+ /// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
858
+ /// unlike `std::is_base_of`)
859
+ template <typename Base, typename Derived>
860
+ using is_strict_base_of
861
+ = bool_constant<std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
862
+
863
+ /// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived
864
+ /// pointer can be converted to a Base pointer) For unions, `is_base_of<T, T>::value` is False, so
865
+ /// we need to check `is_same` as well.
866
+ template <typename Base, typename Derived>
867
+ using is_accessible_base_of
868
+ = bool_constant<(std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value)
869
+ && std::is_convertible<Derived *, Base *>::value>;
870
+
871
+ template <template <typename...> class Base>
872
+ struct is_template_base_of_impl {
873
+ template <typename... Us>
874
+ static std::true_type check(Base<Us...> *);
875
+ static std::false_type check(...);
876
+ };
877
+
878
+ /// Check if a template is the base of a type. For example:
879
+ /// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
880
+ template <template <typename...> class Base, typename T>
881
+ #if !defined(_MSC_VER)
882
+ using is_template_base_of
883
+ = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));
884
+ #else // MSVC2015 has trouble with decltype in template aliases
885
+ struct is_template_base_of
886
+ : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)) {
887
+ };
888
+ #endif
889
+
890
+ /// Check if T is an instantiation of the template `Class`. For example:
891
+ /// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
892
+ template <template <typename...> class Class, typename T>
893
+ struct is_instantiation : std::false_type {};
894
+ template <template <typename...> class Class, typename... Us>
895
+ struct is_instantiation<Class, Class<Us...>> : std::true_type {};
896
+
897
+ /// Check if T is std::shared_ptr<U> where U can be anything
898
+ template <typename T>
899
+ using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
900
+
901
+ /// Check if T looks like an input iterator
902
+ template <typename T, typename = void>
903
+ struct is_input_iterator : std::false_type {};
904
+ template <typename T>
905
+ struct is_input_iterator<T,
906
+ void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
907
+ : std::true_type {};
908
+
909
+ template <typename T>
910
+ using is_function_pointer
911
+ = bool_constant<std::is_pointer<T>::value
912
+ && std::is_function<typename std::remove_pointer<T>::type>::value>;
913
+
914
+ template <typename F>
915
+ struct strip_function_object {
916
+ // If you are encountering an
917
+ // 'error: name followed by "::" must be a class or namespace name'
918
+ // with the Intel compiler and a noexcept function here,
919
+ // try to use noexcept(true) instead of plain noexcept.
920
+ using type = typename remove_class<decltype(&F::operator())>::type;
921
+ };
922
+
923
+ // Extracts the function signature from a function, function pointer or lambda.
924
+ template <typename Function, typename F = remove_reference_t<Function>>
925
+ using function_signature_t = conditional_t<
926
+ std::is_function<F>::value,
927
+ F,
928
+ typename conditional_t<std::is_pointer<F>::value || std::is_member_pointer<F>::value,
929
+ std::remove_pointer<F>,
930
+ strip_function_object<F>>::type>;
931
+
932
+ /// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
933
+ /// pointer. Note that this can catch all sorts of other things, too; this is intended to be used
934
+ /// in a place where passing a lambda makes sense.
935
+ template <typename T>
936
+ using is_lambda = satisfies_none_of<remove_reference_t<T>,
937
+ std::is_function,
938
+ std::is_pointer,
939
+ std::is_member_pointer>;
940
+
941
+ // [workaround(intel)] Internal error on fold expression
942
+ /// Apply a function over each element of a parameter pack
943
+ #if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
944
+ // Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
945
+ # define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
946
+ #else
947
+ using expand_side_effects = bool[];
948
+ # define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) \
949
+ (void) pybind11::detail::expand_side_effects { ((PATTERN), void(), false)..., false }
950
+ #endif
951
+
952
+ PYBIND11_NAMESPACE_END(detail)
953
+
954
+ #if defined(_MSC_VER)
955
+ # pragma warning(push)
956
+ # pragma warning(disable : 4275)
957
+ // warning C4275: An exported class was derived from a class that wasn't exported.
958
+ // Can be ignored when derived from a STL class.
959
+ #endif
960
+ /// C++ bindings of builtin Python exceptions
961
+ class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
962
+ public:
963
+ using std::runtime_error::runtime_error;
964
+ /// Set the error using the Python C API
965
+ virtual void set_error() const = 0;
966
+ };
967
+ #if defined(_MSC_VER)
968
+ # pragma warning(pop)
969
+ #endif
970
+
971
+ #define PYBIND11_RUNTIME_EXCEPTION(name, type) \
972
+ class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception { \
973
+ public: \
974
+ using builtin_exception::builtin_exception; \
975
+ name() : name("") {} \
976
+ void set_error() const override { PyErr_SetString(type, what()); } \
977
+ };
978
+
979
+ PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
980
+ PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
981
+ PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
982
+ PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
983
+ PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
984
+ PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
985
+ PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
986
+ PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)
987
+ PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or
988
+ /// handle::call fail due to a type
989
+ /// casting error
990
+ PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
991
+
992
+ [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) {
993
+ throw std::runtime_error(reason);
994
+ }
995
+ [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) {
996
+ throw std::runtime_error(reason);
997
+ }
998
+
999
+ template <typename T, typename SFINAE = void>
1000
+ struct format_descriptor {};
1001
+
1002
+ PYBIND11_NAMESPACE_BEGIN(detail)
1003
+ // Returns the index of the given type in the type char array below, and in the list in numpy.h
1004
+ // The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
1005
+ // complex float,double,long double. Note that the long double types only participate when long
1006
+ // double is actually longer than double (it isn't under MSVC).
1007
+ // NB: not only the string below but also complex.h and numpy.h rely on this order.
1008
+ template <typename T, typename SFINAE = void>
1009
+ struct is_fmt_numeric {
1010
+ static constexpr bool value = false;
1011
+ };
1012
+ template <typename T>
1013
+ struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
1014
+ static constexpr bool value = true;
1015
+ static constexpr int index
1016
+ = std::is_same<T, bool>::value
1017
+ ? 0
1018
+ : 1
1019
+ + (std::is_integral<T>::value
1020
+ ? detail::log2(sizeof(T)) * 2 + std::is_unsigned<T>::value
1021
+ : 8
1022
+ + (std::is_same<T, double>::value ? 1
1023
+ : std::is_same<T, long double>::value ? 2
1024
+ : 0));
1025
+ };
1026
+ PYBIND11_NAMESPACE_END(detail)
1027
+
1028
+ template <typename T>
1029
+ struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
1030
+ static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
1031
+ static constexpr const char value[2] = {c, '\0'};
1032
+ static std::string format() { return std::string(1, c); }
1033
+ };
1034
+
1035
+ #if !defined(PYBIND11_CPP17)
1036
+
1037
+ template <typename T>
1038
+ constexpr const char
1039
+ format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
1040
+
1041
+ #endif
1042
+
1043
+ /// RAII wrapper that temporarily clears any Python error state
1044
+ struct error_scope {
1045
+ PyObject *type, *value, *trace;
1046
+ error_scope() { PyErr_Fetch(&type, &value, &trace); }
1047
+ ~error_scope() { PyErr_Restore(type, value, trace); }
1048
+ };
1049
+
1050
+ /// Dummy destructor wrapper that can be used to expose classes with a private destructor
1051
+ struct nodelete {
1052
+ template <typename T>
1053
+ void operator()(T *) {}
1054
+ };
1055
+
1056
+ PYBIND11_NAMESPACE_BEGIN(detail)
1057
+ template <typename... Args>
1058
+ struct overload_cast_impl {
1059
+ // NOLINTNEXTLINE(modernize-use-equals-default): MSVC 2015 needs this
1060
+ constexpr overload_cast_impl() {}
1061
+
1062
+ template <typename Return>
1063
+ constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {
1064
+ return pf;
1065
+ }
1066
+
1067
+ template <typename Return, typename Class>
1068
+ constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
1069
+ -> decltype(pmf) {
1070
+ return pmf;
1071
+ }
1072
+
1073
+ template <typename Return, typename Class>
1074
+ constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
1075
+ -> decltype(pmf) {
1076
+ return pmf;
1077
+ }
1078
+ };
1079
+ PYBIND11_NAMESPACE_END(detail)
1080
+
1081
+ // overload_cast requires variable templates: C++14
1082
+ #if defined(PYBIND11_CPP14)
1083
+ # define PYBIND11_OVERLOAD_CAST 1
1084
+ /// Syntax sugar for resolving overloaded function pointers:
1085
+ /// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
1086
+ /// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
1087
+ template <typename... Args>
1088
+ static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
1089
+ // MSVC 2015 only accepts this particular initialization syntax for this variable template.
1090
+ #endif
1091
+
1092
+ /// Const member function selector for overload_cast
1093
+ /// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
1094
+ /// - sweet: overload_cast<Arg>(&Class::func, const_)
1095
+ static constexpr auto const_ = std::true_type{};
1096
+
1097
+ #if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
1098
+ template <typename... Args>
1099
+ struct overload_cast {
1100
+ static_assert(detail::deferred_t<std::false_type, Args...>::value,
1101
+ "pybind11::overload_cast<...> requires compiling in C++14 mode");
1102
+ };
1103
+ #endif // overload_cast
1104
+
1105
+ PYBIND11_NAMESPACE_BEGIN(detail)
1106
+
1107
+ // Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
1108
+ // any standard container (or C-style array) supporting std::begin/std::end, any singleton
1109
+ // arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
1110
+ template <typename T>
1111
+ class any_container {
1112
+ std::vector<T> v;
1113
+
1114
+ public:
1115
+ any_container() = default;
1116
+
1117
+ // Can construct from a pair of iterators
1118
+ template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
1119
+ any_container(It first, It last) : v(first, last) {}
1120
+
1121
+ // Implicit conversion constructor from any arbitrary container type
1122
+ // with values convertible to T
1123
+ template <typename Container,
1124
+ typename = enable_if_t<
1125
+ std::is_convertible<decltype(*std::begin(std::declval<const Container &>())),
1126
+ T>::value>>
1127
+ // NOLINTNEXTLINE(google-explicit-constructor)
1128
+ any_container(const Container &c) : any_container(std::begin(c), std::end(c)) {}
1129
+
1130
+ // initializer_list's aren't deducible, so don't get matched by the above template;
1131
+ // we need this to explicitly allow implicit conversion from one:
1132
+ template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
1133
+ any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) {}
1134
+
1135
+ // Avoid copying if given an rvalue vector of the correct type.
1136
+ // NOLINTNEXTLINE(google-explicit-constructor)
1137
+ any_container(std::vector<T> &&v) : v(std::move(v)) {}
1138
+
1139
+ // Moves the vector out of an rvalue any_container
1140
+ // NOLINTNEXTLINE(google-explicit-constructor)
1141
+ operator std::vector<T> &&() && { return std::move(v); }
1142
+
1143
+ // Dereferencing obtains a reference to the underlying vector
1144
+ std::vector<T> &operator*() { return v; }
1145
+ const std::vector<T> &operator*() const { return v; }
1146
+
1147
+ // -> lets you call methods on the underlying vector
1148
+ std::vector<T> *operator->() { return &v; }
1149
+ const std::vector<T> *operator->() const { return &v; }
1150
+ };
1151
+
1152
+ // Forward-declaration; see detail/class.h
1153
+ std::string get_fully_qualified_tp_name(PyTypeObject *);
1154
+
1155
+ template <typename T>
1156
+ inline static std::shared_ptr<T>
1157
+ try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
1158
+ // Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
1159
+ // Use at your own risk!
1160
+ // See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
1161
+ // the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
1162
+ #if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1163
+ return holder_value_ptr->weak_from_this().lock();
1164
+ #else
1165
+ try {
1166
+ return holder_value_ptr->shared_from_this();
1167
+ } catch (const std::bad_weak_ptr &) {
1168
+ return nullptr;
1169
+ }
1170
+ #endif
1171
+ }
1172
+
1173
+ // For silencing "unused" compiler warnings in special situations.
1174
+ template <typename... Args>
1175
+ #if defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER < 1920 // MSVC 2017
1176
+ constexpr
1177
+ #endif
1178
+ inline void
1179
+ silence_unused_warnings(Args &&...) {
1180
+ }
1181
+
1182
+ // MSVC warning C4100: Unreferenced formal parameter
1183
+ #if defined(_MSC_VER) && _MSC_VER <= 1916
1184
+ # define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...) \
1185
+ detail::silence_unused_warnings(__VA_ARGS__)
1186
+ #else
1187
+ # define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
1188
+ #endif
1189
+
1190
+ // GCC -Wunused-but-set-parameter All GCC versions (as of July 2021).
1191
+ #if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
1192
+ # define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...) \
1193
+ detail::silence_unused_warnings(__VA_ARGS__)
1194
+ #else
1195
+ # define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
1196
+ #endif
1197
+
1198
+ #if defined(_MSC_VER) // All versions (as of July 2021).
1199
+
1200
+ // warning C4127: Conditional expression is constant
1201
+ constexpr inline bool silence_msvc_c4127(bool cond) { return cond; }
1202
+
1203
+ # define PYBIND11_SILENCE_MSVC_C4127(...) ::pybind11::detail::silence_msvc_c4127(__VA_ARGS__)
1204
+
1205
+ #else
1206
+ # define PYBIND11_SILENCE_MSVC_C4127(...) __VA_ARGS__
1207
+ #endif
1208
+
1209
+ PYBIND11_NAMESPACE_END(detail)
1210
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/descr.h ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/descr.h: Helper type for concatenating type signatures at compile time
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "common.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+ PYBIND11_NAMESPACE_BEGIN(detail)
16
+
17
+ #if !defined(_MSC_VER)
18
+ # define PYBIND11_DESCR_CONSTEXPR static constexpr
19
+ #else
20
+ # define PYBIND11_DESCR_CONSTEXPR const
21
+ #endif
22
+
23
+ /* Concatenate type signatures at compile time */
24
+ template <size_t N, typename... Ts>
25
+ struct descr {
26
+ char text[N + 1]{'\0'};
27
+
28
+ constexpr descr() = default;
29
+ // NOLINTNEXTLINE(google-explicit-constructor)
30
+ constexpr descr(char const (&s)[N + 1]) : descr(s, make_index_sequence<N>()) {}
31
+
32
+ template <size_t... Is>
33
+ constexpr descr(char const (&s)[N + 1], index_sequence<Is...>) : text{s[Is]..., '\0'} {}
34
+
35
+ template <typename... Chars>
36
+ // NOLINTNEXTLINE(google-explicit-constructor)
37
+ constexpr descr(char c, Chars... cs) : text{c, static_cast<char>(cs)..., '\0'} {}
38
+
39
+ static constexpr std::array<const std::type_info *, sizeof...(Ts) + 1> types() {
40
+ return {{&typeid(Ts)..., nullptr}};
41
+ }
42
+ };
43
+
44
+ template <size_t N1, size_t N2, typename... Ts1, typename... Ts2, size_t... Is1, size_t... Is2>
45
+ constexpr descr<N1 + N2, Ts1..., Ts2...> plus_impl(const descr<N1, Ts1...> &a,
46
+ const descr<N2, Ts2...> &b,
47
+ index_sequence<Is1...>,
48
+ index_sequence<Is2...>) {
49
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(b);
50
+ return {a.text[Is1]..., b.text[Is2]...};
51
+ }
52
+
53
+ template <size_t N1, size_t N2, typename... Ts1, typename... Ts2>
54
+ constexpr descr<N1 + N2, Ts1..., Ts2...> operator+(const descr<N1, Ts1...> &a,
55
+ const descr<N2, Ts2...> &b) {
56
+ return plus_impl(a, b, make_index_sequence<N1>(), make_index_sequence<N2>());
57
+ }
58
+
59
+ template <size_t N>
60
+ constexpr descr<N - 1> const_name(char const (&text)[N]) {
61
+ return descr<N - 1>(text);
62
+ }
63
+ constexpr descr<0> const_name(char const (&)[1]) { return {}; }
64
+
65
+ template <size_t Rem, size_t... Digits>
66
+ struct int_to_str : int_to_str<Rem / 10, Rem % 10, Digits...> {};
67
+ template <size_t... Digits>
68
+ struct int_to_str<0, Digits...> {
69
+ // WARNING: This only works with C++17 or higher.
70
+ static constexpr auto digits = descr<sizeof...(Digits)>(('0' + Digits)...);
71
+ };
72
+
73
+ // Ternary description (like std::conditional)
74
+ template <bool B, size_t N1, size_t N2>
75
+ constexpr enable_if_t<B, descr<N1 - 1>> const_name(char const (&text1)[N1], char const (&)[N2]) {
76
+ return const_name(text1);
77
+ }
78
+ template <bool B, size_t N1, size_t N2>
79
+ constexpr enable_if_t<!B, descr<N2 - 1>> const_name(char const (&)[N1], char const (&text2)[N2]) {
80
+ return const_name(text2);
81
+ }
82
+
83
+ template <bool B, typename T1, typename T2>
84
+ constexpr enable_if_t<B, T1> const_name(const T1 &d, const T2 &) {
85
+ return d;
86
+ }
87
+ template <bool B, typename T1, typename T2>
88
+ constexpr enable_if_t<!B, T2> const_name(const T1 &, const T2 &d) {
89
+ return d;
90
+ }
91
+
92
+ template <size_t Size>
93
+ auto constexpr const_name() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {
94
+ return int_to_str<Size / 10, Size % 10>::digits;
95
+ }
96
+
97
+ template <typename Type>
98
+ constexpr descr<1, Type> const_name() {
99
+ return {'%'};
100
+ }
101
+
102
+ // If "_" is defined as a macro, py::detail::_ cannot be provided.
103
+ // It is therefore best to use py::detail::const_name universally.
104
+ // This block is for backward compatibility only.
105
+ // (The const_name code is repeated to avoid introducing a "_" #define ourselves.)
106
+ #ifndef _
107
+ # define PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY
108
+ template <size_t N>
109
+ constexpr descr<N - 1> _(char const (&text)[N]) {
110
+ return const_name<N>(text);
111
+ }
112
+ template <bool B, size_t N1, size_t N2>
113
+ constexpr enable_if_t<B, descr<N1 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {
114
+ return const_name<B, N1, N2>(text1, text2);
115
+ }
116
+ template <bool B, size_t N1, size_t N2>
117
+ constexpr enable_if_t<!B, descr<N2 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {
118
+ return const_name<B, N1, N2>(text1, text2);
119
+ }
120
+ template <bool B, typename T1, typename T2>
121
+ constexpr enable_if_t<B, T1> _(const T1 &d1, const T2 &d2) {
122
+ return const_name<B, T1, T2>(d1, d2);
123
+ }
124
+ template <bool B, typename T1, typename T2>
125
+ constexpr enable_if_t<!B, T2> _(const T1 &d1, const T2 &d2) {
126
+ return const_name<B, T1, T2>(d1, d2);
127
+ }
128
+
129
+ template <size_t Size>
130
+ auto constexpr _() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {
131
+ return const_name<Size>();
132
+ }
133
+ template <typename Type>
134
+ constexpr descr<1, Type> _() {
135
+ return const_name<Type>();
136
+ }
137
+ #endif // #ifndef _
138
+
139
+ constexpr descr<0> concat() { return {}; }
140
+
141
+ template <size_t N, typename... Ts>
142
+ constexpr descr<N, Ts...> concat(const descr<N, Ts...> &descr) {
143
+ return descr;
144
+ }
145
+
146
+ template <size_t N, typename... Ts, typename... Args>
147
+ constexpr auto concat(const descr<N, Ts...> &d, const Args &...args)
148
+ -> decltype(std::declval<descr<N + 2, Ts...>>() + concat(args...)) {
149
+ return d + const_name(", ") + concat(args...);
150
+ }
151
+
152
+ template <size_t N, typename... Ts>
153
+ constexpr descr<N + 2, Ts...> type_descr(const descr<N, Ts...> &descr) {
154
+ return const_name("{") + descr + const_name("}");
155
+ }
156
+
157
+ PYBIND11_NAMESPACE_END(detail)
158
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/init.h ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/init.h: init factory function implementation and support code.
3
+
4
+ Copyright (c) 2017 Jason Rhinelander <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "class.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+ PYBIND11_NAMESPACE_BEGIN(detail)
16
+
17
+ template <>
18
+ class type_caster<value_and_holder> {
19
+ public:
20
+ bool load(handle h, bool) {
21
+ value = reinterpret_cast<value_and_holder *>(h.ptr());
22
+ return true;
23
+ }
24
+
25
+ template <typename>
26
+ using cast_op_type = value_and_holder &;
27
+ explicit operator value_and_holder &() { return *value; }
28
+ static constexpr auto name = const_name<value_and_holder>();
29
+
30
+ private:
31
+ value_and_holder *value = nullptr;
32
+ };
33
+
34
+ PYBIND11_NAMESPACE_BEGIN(initimpl)
35
+
36
+ inline void no_nullptr(void *ptr) {
37
+ if (!ptr) {
38
+ throw type_error("pybind11::init(): factory function returned nullptr");
39
+ }
40
+ }
41
+
42
+ // Implementing functions for all forms of py::init<...> and py::init(...)
43
+ template <typename Class>
44
+ using Cpp = typename Class::type;
45
+ template <typename Class>
46
+ using Alias = typename Class::type_alias;
47
+ template <typename Class>
48
+ using Holder = typename Class::holder_type;
49
+
50
+ template <typename Class>
51
+ using is_alias_constructible = std::is_constructible<Alias<Class>, Cpp<Class> &&>;
52
+
53
+ // Takes a Cpp pointer and returns true if it actually is a polymorphic Alias instance.
54
+ template <typename Class, enable_if_t<Class::has_alias, int> = 0>
55
+ bool is_alias(Cpp<Class> *ptr) {
56
+ return dynamic_cast<Alias<Class> *>(ptr) != nullptr;
57
+ }
58
+ // Failing fallback version of the above for a no-alias class (always returns false)
59
+ template <typename /*Class*/>
60
+ constexpr bool is_alias(void *) {
61
+ return false;
62
+ }
63
+
64
+ // Constructs and returns a new object; if the given arguments don't map to a constructor, we fall
65
+ // back to brace aggregate initiailization so that for aggregate initialization can be used with
66
+ // py::init, e.g. `py::init<int, int>` to initialize a `struct T { int a; int b; }`. For
67
+ // non-aggregate types, we need to use an ordinary T(...) constructor (invoking as `T{...}` usually
68
+ // works, but will not do the expected thing when `T` has an `initializer_list<T>` constructor).
69
+ template <typename Class,
70
+ typename... Args,
71
+ detail::enable_if_t<std::is_constructible<Class, Args...>::value, int> = 0>
72
+ inline Class *construct_or_initialize(Args &&...args) {
73
+ return new Class(std::forward<Args>(args)...);
74
+ }
75
+ template <typename Class,
76
+ typename... Args,
77
+ detail::enable_if_t<!std::is_constructible<Class, Args...>::value, int> = 0>
78
+ inline Class *construct_or_initialize(Args &&...args) {
79
+ return new Class{std::forward<Args>(args)...};
80
+ }
81
+
82
+ // Attempts to constructs an alias using a `Alias(Cpp &&)` constructor. This allows types with
83
+ // an alias to provide only a single Cpp factory function as long as the Alias can be
84
+ // constructed from an rvalue reference of the base Cpp type. This means that Alias classes
85
+ // can, when appropriate, simply define a `Alias(Cpp &&)` constructor rather than needing to
86
+ // inherit all the base class constructors.
87
+ template <typename Class>
88
+ void construct_alias_from_cpp(std::true_type /*is_alias_constructible*/,
89
+ value_and_holder &v_h,
90
+ Cpp<Class> &&base) {
91
+ v_h.value_ptr() = new Alias<Class>(std::move(base));
92
+ }
93
+ template <typename Class>
94
+ [[noreturn]] void construct_alias_from_cpp(std::false_type /*!is_alias_constructible*/,
95
+ value_and_holder &,
96
+ Cpp<Class> &&) {
97
+ throw type_error("pybind11::init(): unable to convert returned instance to required "
98
+ "alias class: no `Alias<Class>(Class &&)` constructor available");
99
+ }
100
+
101
+ // Error-generating fallback for factories that don't match one of the below construction
102
+ // mechanisms.
103
+ template <typename Class>
104
+ void construct(...) {
105
+ static_assert(!std::is_same<Class, Class>::value /* always false */,
106
+ "pybind11::init(): init function must return a compatible pointer, "
107
+ "holder, or value");
108
+ }
109
+
110
+ // Pointer return v1: the factory function returns a class pointer for a registered class.
111
+ // If we don't need an alias (because this class doesn't have one, or because the final type is
112
+ // inherited on the Python side) we can simply take over ownership. Otherwise we need to try to
113
+ // construct an Alias from the returned base instance.
114
+ template <typename Class>
115
+ void construct(value_and_holder &v_h, Cpp<Class> *ptr, bool need_alias) {
116
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
117
+ no_nullptr(ptr);
118
+ if (PYBIND11_SILENCE_MSVC_C4127(Class::has_alias) && need_alias && !is_alias<Class>(ptr)) {
119
+ // We're going to try to construct an alias by moving the cpp type. Whether or not
120
+ // that succeeds, we still need to destroy the original cpp pointer (either the
121
+ // moved away leftover, if the alias construction works, or the value itself if we
122
+ // throw an error), but we can't just call `delete ptr`: it might have a special
123
+ // deleter, or might be shared_from_this. So we construct a holder around it as if
124
+ // it was a normal instance, then steal the holder away into a local variable; thus
125
+ // the holder and destruction happens when we leave the C++ scope, and the holder
126
+ // class gets to handle the destruction however it likes.
127
+ v_h.value_ptr() = ptr;
128
+ v_h.set_instance_registered(true); // To prevent init_instance from registering it
129
+ v_h.type->init_instance(v_h.inst, nullptr); // Set up the holder
130
+ Holder<Class> temp_holder(std::move(v_h.holder<Holder<Class>>())); // Steal the holder
131
+ v_h.type->dealloc(v_h); // Destroys the moved-out holder remains, resets value ptr to null
132
+ v_h.set_instance_registered(false);
133
+
134
+ construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(*ptr));
135
+ } else {
136
+ // Otherwise the type isn't inherited, so we don't need an Alias
137
+ v_h.value_ptr() = ptr;
138
+ }
139
+ }
140
+
141
+ // Pointer return v2: a factory that always returns an alias instance ptr. We simply take over
142
+ // ownership of the pointer.
143
+ template <typename Class, enable_if_t<Class::has_alias, int> = 0>
144
+ void construct(value_and_holder &v_h, Alias<Class> *alias_ptr, bool) {
145
+ no_nullptr(alias_ptr);
146
+ v_h.value_ptr() = static_cast<Cpp<Class> *>(alias_ptr);
147
+ }
148
+
149
+ // Holder return: copy its pointer, and move or copy the returned holder into the new instance's
150
+ // holder. This also handles types like std::shared_ptr<T> and std::unique_ptr<T> where T is a
151
+ // derived type (through those holder's implicit conversion from derived class holder
152
+ // constructors).
153
+ template <typename Class>
154
+ void construct(value_and_holder &v_h, Holder<Class> holder, bool need_alias) {
155
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
156
+ auto *ptr = holder_helper<Holder<Class>>::get(holder);
157
+ no_nullptr(ptr);
158
+ // If we need an alias, check that the held pointer is actually an alias instance
159
+ if (PYBIND11_SILENCE_MSVC_C4127(Class::has_alias) && need_alias && !is_alias<Class>(ptr)) {
160
+ throw type_error("pybind11::init(): construction failed: returned holder-wrapped instance "
161
+ "is not an alias instance");
162
+ }
163
+
164
+ v_h.value_ptr() = ptr;
165
+ v_h.type->init_instance(v_h.inst, &holder);
166
+ }
167
+
168
+ // return-by-value version 1: returning a cpp class by value. If the class has an alias and an
169
+ // alias is required the alias must have an `Alias(Cpp &&)` constructor so that we can construct
170
+ // the alias from the base when needed (i.e. because of Python-side inheritance). When we don't
171
+ // need it, we simply move-construct the cpp value into a new instance.
172
+ template <typename Class>
173
+ void construct(value_and_holder &v_h, Cpp<Class> &&result, bool need_alias) {
174
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
175
+ static_assert(std::is_move_constructible<Cpp<Class>>::value,
176
+ "pybind11::init() return-by-value factory function requires a movable class");
177
+ if (PYBIND11_SILENCE_MSVC_C4127(Class::has_alias) && need_alias) {
178
+ construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(result));
179
+ } else {
180
+ v_h.value_ptr() = new Cpp<Class>(std::move(result));
181
+ }
182
+ }
183
+
184
+ // return-by-value version 2: returning a value of the alias type itself. We move-construct an
185
+ // Alias instance (even if no the python-side inheritance is involved). The is intended for
186
+ // cases where Alias initialization is always desired.
187
+ template <typename Class>
188
+ void construct(value_and_holder &v_h, Alias<Class> &&result, bool) {
189
+ static_assert(
190
+ std::is_move_constructible<Alias<Class>>::value,
191
+ "pybind11::init() return-by-alias-value factory function requires a movable alias class");
192
+ v_h.value_ptr() = new Alias<Class>(std::move(result));
193
+ }
194
+
195
+ // Implementing class for py::init<...>()
196
+ template <typename... Args>
197
+ struct constructor {
198
+ template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
199
+ static void execute(Class &cl, const Extra &...extra) {
200
+ cl.def(
201
+ "__init__",
202
+ [](value_and_holder &v_h, Args... args) {
203
+ v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
204
+ },
205
+ is_new_style_constructor(),
206
+ extra...);
207
+ }
208
+
209
+ template <typename Class,
210
+ typename... Extra,
211
+ enable_if_t<Class::has_alias && std::is_constructible<Cpp<Class>, Args...>::value,
212
+ int> = 0>
213
+ static void execute(Class &cl, const Extra &...extra) {
214
+ cl.def(
215
+ "__init__",
216
+ [](value_and_holder &v_h, Args... args) {
217
+ if (Py_TYPE(v_h.inst) == v_h.type->type) {
218
+ v_h.value_ptr()
219
+ = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
220
+ } else {
221
+ v_h.value_ptr()
222
+ = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
223
+ }
224
+ },
225
+ is_new_style_constructor(),
226
+ extra...);
227
+ }
228
+
229
+ template <typename Class,
230
+ typename... Extra,
231
+ enable_if_t<Class::has_alias && !std::is_constructible<Cpp<Class>, Args...>::value,
232
+ int> = 0>
233
+ static void execute(Class &cl, const Extra &...extra) {
234
+ cl.def(
235
+ "__init__",
236
+ [](value_and_holder &v_h, Args... args) {
237
+ v_h.value_ptr()
238
+ = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
239
+ },
240
+ is_new_style_constructor(),
241
+ extra...);
242
+ }
243
+ };
244
+
245
+ // Implementing class for py::init_alias<...>()
246
+ template <typename... Args>
247
+ struct alias_constructor {
248
+ template <typename Class,
249
+ typename... Extra,
250
+ enable_if_t<Class::has_alias && std::is_constructible<Alias<Class>, Args...>::value,
251
+ int> = 0>
252
+ static void execute(Class &cl, const Extra &...extra) {
253
+ cl.def(
254
+ "__init__",
255
+ [](value_and_holder &v_h, Args... args) {
256
+ v_h.value_ptr()
257
+ = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
258
+ },
259
+ is_new_style_constructor(),
260
+ extra...);
261
+ }
262
+ };
263
+
264
+ // Implementation class for py::init(Func) and py::init(Func, AliasFunc)
265
+ template <typename CFunc,
266
+ typename AFunc = void_type (*)(),
267
+ typename = function_signature_t<CFunc>,
268
+ typename = function_signature_t<AFunc>>
269
+ struct factory;
270
+
271
+ // Specialization for py::init(Func)
272
+ template <typename Func, typename Return, typename... Args>
273
+ struct factory<Func, void_type (*)(), Return(Args...)> {
274
+ remove_reference_t<Func> class_factory;
275
+
276
+ // NOLINTNEXTLINE(google-explicit-constructor)
277
+ factory(Func &&f) : class_factory(std::forward<Func>(f)) {}
278
+
279
+ // The given class either has no alias or has no separate alias factory;
280
+ // this always constructs the class itself. If the class is registered with an alias
281
+ // type and an alias instance is needed (i.e. because the final type is a Python class
282
+ // inheriting from the C++ type) the returned value needs to either already be an alias
283
+ // instance, or the alias needs to be constructible from a `Class &&` argument.
284
+ template <typename Class, typename... Extra>
285
+ void execute(Class &cl, const Extra &...extra) && {
286
+ #if defined(PYBIND11_CPP14)
287
+ cl.def(
288
+ "__init__",
289
+ [func = std::move(class_factory)]
290
+ #else
291
+ auto &func = class_factory;
292
+ cl.def(
293
+ "__init__",
294
+ [func]
295
+ #endif
296
+ (value_and_holder &v_h, Args... args) {
297
+ construct<Class>(
298
+ v_h, func(std::forward<Args>(args)...), Py_TYPE(v_h.inst) != v_h.type->type);
299
+ },
300
+ is_new_style_constructor(),
301
+ extra...);
302
+ }
303
+ };
304
+
305
+ // Specialization for py::init(Func, AliasFunc)
306
+ template <typename CFunc,
307
+ typename AFunc,
308
+ typename CReturn,
309
+ typename... CArgs,
310
+ typename AReturn,
311
+ typename... AArgs>
312
+ struct factory<CFunc, AFunc, CReturn(CArgs...), AReturn(AArgs...)> {
313
+ static_assert(sizeof...(CArgs) == sizeof...(AArgs),
314
+ "pybind11::init(class_factory, alias_factory): class and alias factories "
315
+ "must have identical argument signatures");
316
+ static_assert(all_of<std::is_same<CArgs, AArgs>...>::value,
317
+ "pybind11::init(class_factory, alias_factory): class and alias factories "
318
+ "must have identical argument signatures");
319
+
320
+ remove_reference_t<CFunc> class_factory;
321
+ remove_reference_t<AFunc> alias_factory;
322
+
323
+ factory(CFunc &&c, AFunc &&a)
324
+ : class_factory(std::forward<CFunc>(c)), alias_factory(std::forward<AFunc>(a)) {}
325
+
326
+ // The class factory is called when the `self` type passed to `__init__` is the direct
327
+ // class (i.e. not inherited), the alias factory when `self` is a Python-side subtype.
328
+ template <typename Class, typename... Extra>
329
+ void execute(Class &cl, const Extra &...extra) && {
330
+ static_assert(Class::has_alias,
331
+ "The two-argument version of `py::init()` can "
332
+ "only be used if the class has an alias");
333
+ #if defined(PYBIND11_CPP14)
334
+ cl.def(
335
+ "__init__",
336
+ [class_func = std::move(class_factory), alias_func = std::move(alias_factory)]
337
+ #else
338
+ auto &class_func = class_factory;
339
+ auto &alias_func = alias_factory;
340
+ cl.def(
341
+ "__init__",
342
+ [class_func, alias_func]
343
+ #endif
344
+ (value_and_holder &v_h, CArgs... args) {
345
+ if (Py_TYPE(v_h.inst) == v_h.type->type) {
346
+ // If the instance type equals the registered type we don't have inheritance,
347
+ // so don't need the alias and can construct using the class function:
348
+ construct<Class>(v_h, class_func(std::forward<CArgs>(args)...), false);
349
+ } else {
350
+ construct<Class>(v_h, alias_func(std::forward<CArgs>(args)...), true);
351
+ }
352
+ },
353
+ is_new_style_constructor(),
354
+ extra...);
355
+ }
356
+ };
357
+
358
+ /// Set just the C++ state. Same as `__init__`.
359
+ template <typename Class, typename T>
360
+ void setstate(value_and_holder &v_h, T &&result, bool need_alias) {
361
+ construct<Class>(v_h, std::forward<T>(result), need_alias);
362
+ }
363
+
364
+ /// Set both the C++ and Python states
365
+ template <typename Class,
366
+ typename T,
367
+ typename O,
368
+ enable_if_t<std::is_convertible<O, handle>::value, int> = 0>
369
+ void setstate(value_and_holder &v_h, std::pair<T, O> &&result, bool need_alias) {
370
+ construct<Class>(v_h, std::move(result.first), need_alias);
371
+ auto d = handle(result.second);
372
+ if (PyDict_Check(d.ptr()) && PyDict_Size(d.ptr()) == 0) {
373
+ // Skipping setattr below, to not force use of py::dynamic_attr() for Class unnecessarily.
374
+ // See PR #2972 for details.
375
+ return;
376
+ }
377
+ setattr((PyObject *) v_h.inst, "__dict__", d);
378
+ }
379
+
380
+ /// Implementation for py::pickle(GetState, SetState)
381
+ template <typename Get,
382
+ typename Set,
383
+ typename = function_signature_t<Get>,
384
+ typename = function_signature_t<Set>>
385
+ struct pickle_factory;
386
+
387
+ template <typename Get,
388
+ typename Set,
389
+ typename RetState,
390
+ typename Self,
391
+ typename NewInstance,
392
+ typename ArgState>
393
+ struct pickle_factory<Get, Set, RetState(Self), NewInstance(ArgState)> {
394
+ static_assert(std::is_same<intrinsic_t<RetState>, intrinsic_t<ArgState>>::value,
395
+ "The type returned by `__getstate__` must be the same "
396
+ "as the argument accepted by `__setstate__`");
397
+
398
+ remove_reference_t<Get> get;
399
+ remove_reference_t<Set> set;
400
+
401
+ pickle_factory(Get get, Set set) : get(std::forward<Get>(get)), set(std::forward<Set>(set)) {}
402
+
403
+ template <typename Class, typename... Extra>
404
+ void execute(Class &cl, const Extra &...extra) && {
405
+ cl.def("__getstate__", std::move(get));
406
+
407
+ #if defined(PYBIND11_CPP14)
408
+ cl.def(
409
+ "__setstate__",
410
+ [func = std::move(set)]
411
+ #else
412
+ auto &func = set;
413
+ cl.def(
414
+ "__setstate__",
415
+ [func]
416
+ #endif
417
+ (value_and_holder &v_h, ArgState state) {
418
+ setstate<Class>(
419
+ v_h, func(std::forward<ArgState>(state)), Py_TYPE(v_h.inst) != v_h.type->type);
420
+ },
421
+ is_new_style_constructor(),
422
+ extra...);
423
+ }
424
+ };
425
+
426
+ PYBIND11_NAMESPACE_END(initimpl)
427
+ PYBIND11_NAMESPACE_END(detail)
428
+ PYBIND11_NAMESPACE_END(pybind11)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/internals.h ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/internals.h: Internal data structure and related functions
3
+
4
+ Copyright (c) 2017 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "../pytypes.h"
13
+
14
+ #include <exception>
15
+
16
+ /// Tracks the `internals` and `type_info` ABI version independent of the main library version.
17
+ ///
18
+ /// Some portions of the code use an ABI that is conditional depending on this
19
+ /// version number. That allows ABI-breaking changes to be "pre-implemented".
20
+ /// Once the default version number is incremented, the conditional logic that
21
+ /// no longer applies can be removed. Additionally, users that need not
22
+ /// maintain ABI compatibility can increase the version number in order to take
23
+ /// advantage of any functionality/efficiency improvements that depend on the
24
+ /// newer ABI.
25
+ ///
26
+ /// WARNING: If you choose to manually increase the ABI version, note that
27
+ /// pybind11 may not be tested as thoroughly with a non-default ABI version, and
28
+ /// further ABI-incompatible changes may be made before the ABI is officially
29
+ /// changed to the new version.
30
+ #ifndef PYBIND11_INTERNALS_VERSION
31
+ # define PYBIND11_INTERNALS_VERSION 4
32
+ #endif
33
+
34
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
35
+
36
+ using ExceptionTranslator = void (*)(std::exception_ptr);
37
+
38
+ PYBIND11_NAMESPACE_BEGIN(detail)
39
+
40
+ // Forward declarations
41
+ inline PyTypeObject *make_static_property_type();
42
+ inline PyTypeObject *make_default_metaclass();
43
+ inline PyObject *make_object_base_type(PyTypeObject *metaclass);
44
+
45
+ // The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
46
+ // Thread Specific Storage (TSS) API.
47
+ #if PY_VERSION_HEX >= 0x03070000
48
+ // Avoid unnecessary allocation of `Py_tss_t`, since we cannot use
49
+ // `Py_LIMITED_API` anyway.
50
+ # if PYBIND11_INTERNALS_VERSION > 4
51
+ # define PYBIND11_TLS_KEY_REF Py_tss_t &
52
+ # ifdef __GNUC__
53
+ // Clang on macOS warns due to `Py_tss_NEEDS_INIT` not specifying an initializer
54
+ // for every field.
55
+ # define PYBIND11_TLS_KEY_INIT(var) \
56
+ _Pragma("GCC diagnostic push") /**/ \
57
+ _Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") /**/ \
58
+ Py_tss_t var \
59
+ = Py_tss_NEEDS_INIT; \
60
+ _Pragma("GCC diagnostic pop")
61
+ # else
62
+ # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT;
63
+ # endif
64
+ # define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0)
65
+ # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key))
66
+ # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value))
67
+ # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr)
68
+ # define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key))
69
+ # else
70
+ # define PYBIND11_TLS_KEY_REF Py_tss_t *
71
+ # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr;
72
+ # define PYBIND11_TLS_KEY_CREATE(var) \
73
+ (((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0))
74
+ # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
75
+ # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
76
+ # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
77
+ # define PYBIND11_TLS_FREE(key) PyThread_tss_free(key)
78
+ # endif
79
+ #else
80
+ // Usually an int but a long on Cygwin64 with Python 3.x
81
+ # define PYBIND11_TLS_KEY_REF decltype(PyThread_create_key())
82
+ # define PYBIND11_TLS_KEY_INIT(var) PYBIND11_TLS_KEY_REF var = 0;
83
+ # define PYBIND11_TLS_KEY_CREATE(var) (((var) = PyThread_create_key()) != -1)
84
+ # define PYBIND11_TLS_GET_VALUE(key) PyThread_get_key_value((key))
85
+ # if PY_MAJOR_VERSION < 3 || defined(PYPY_VERSION)
86
+ // On CPython < 3.4 and on PyPy, `PyThread_set_key_value` strangely does not set
87
+ // the value if it has already been set. Instead, it must first be deleted and
88
+ // then set again.
89
+ inline void tls_replace_value(PYBIND11_TLS_KEY_REF key, void *value) {
90
+ PyThread_delete_key_value(key);
91
+ PyThread_set_key_value(key, value);
92
+ }
93
+ # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_delete_key_value(key)
94
+ # define PYBIND11_TLS_REPLACE_VALUE(key, value) \
95
+ ::pybind11::detail::tls_replace_value((key), (value))
96
+ # else
97
+ # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_set_key_value((key), nullptr)
98
+ # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_set_key_value((key), (value))
99
+ # endif
100
+ # define PYBIND11_TLS_FREE(key) (void) key
101
+ #endif
102
+
103
+ // Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
104
+ // other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module
105
+ // even when `A` is the same, non-hidden-visibility type (e.g. from a common include). Under
106
+ // libstdc++, this doesn't happen: equality and the type_index hash are based on the type name,
107
+ // which works. If not under a known-good stl, provide our own name-based hash and equality
108
+ // functions that use the type name.
109
+ #if defined(__GLIBCXX__)
110
+ inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; }
111
+ using type_hash = std::hash<std::type_index>;
112
+ using type_equal_to = std::equal_to<std::type_index>;
113
+ #else
114
+ inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) {
115
+ return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
116
+ }
117
+
118
+ struct type_hash {
119
+ size_t operator()(const std::type_index &t) const {
120
+ size_t hash = 5381;
121
+ const char *ptr = t.name();
122
+ while (auto c = static_cast<unsigned char>(*ptr++)) {
123
+ hash = (hash * 33) ^ c;
124
+ }
125
+ return hash;
126
+ }
127
+ };
128
+
129
+ struct type_equal_to {
130
+ bool operator()(const std::type_index &lhs, const std::type_index &rhs) const {
131
+ return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
132
+ }
133
+ };
134
+ #endif
135
+
136
+ template <typename value_type>
137
+ using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;
138
+
139
+ struct override_hash {
140
+ inline size_t operator()(const std::pair<const PyObject *, const char *> &v) const {
141
+ size_t value = std::hash<const void *>()(v.first);
142
+ value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value << 6) + (value >> 2);
143
+ return value;
144
+ }
145
+ };
146
+
147
+ /// Internal data structure used to track registered instances and types.
148
+ /// Whenever binary incompatible changes are made to this structure,
149
+ /// `PYBIND11_INTERNALS_VERSION` must be incremented.
150
+ struct internals {
151
+ // std::type_index -> pybind11's type information
152
+ type_map<type_info *> registered_types_cpp;
153
+ // PyTypeObject* -> base type_info(s)
154
+ std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py;
155
+ std::unordered_multimap<const void *, instance *> registered_instances; // void * -> instance*
156
+ std::unordered_set<std::pair<const PyObject *, const char *>, override_hash>
157
+ inactive_override_cache;
158
+ type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
159
+ std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
160
+ std::forward_list<ExceptionTranslator> registered_exception_translators;
161
+ std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across
162
+ // extensions
163
+ #if PYBIND11_INTERNALS_VERSION == 4
164
+ std::vector<PyObject *> unused_loader_patient_stack_remove_at_v5;
165
+ #endif
166
+ std::forward_list<std::string> static_strings; // Stores the std::strings backing
167
+ // detail::c_str()
168
+ PyTypeObject *static_property_type;
169
+ PyTypeObject *default_metaclass;
170
+ PyObject *instance_base;
171
+ #if defined(WITH_THREAD)
172
+ PYBIND11_TLS_KEY_INIT(tstate)
173
+ # if PYBIND11_INTERNALS_VERSION > 4
174
+ PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
175
+ # endif // PYBIND11_INTERNALS_VERSION > 4
176
+ PyInterpreterState *istate = nullptr;
177
+ ~internals() {
178
+ # if PYBIND11_INTERNALS_VERSION > 4
179
+ PYBIND11_TLS_FREE(loader_life_support_tls_key);
180
+ # endif // PYBIND11_INTERNALS_VERSION > 4
181
+
182
+ // This destructor is called *after* Py_Finalize() in finalize_interpreter().
183
+ // That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
184
+ // called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
185
+ // nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
186
+ // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
187
+ // Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
188
+ // that the `tstate` be allocated with the CPython allocator.
189
+ PYBIND11_TLS_FREE(tstate);
190
+ }
191
+ #endif
192
+ };
193
+
194
+ /// Additional type information which does not fit into the PyTypeObject.
195
+ /// Changes to this struct also require bumping `PYBIND11_INTERNALS_VERSION`.
196
+ struct type_info {
197
+ PyTypeObject *type;
198
+ const std::type_info *cpptype;
199
+ size_t type_size, type_align, holder_size_in_ptrs;
200
+ void *(*operator_new)(size_t);
201
+ void (*init_instance)(instance *, const void *);
202
+ void (*dealloc)(value_and_holder &v_h);
203
+ std::vector<PyObject *(*) (PyObject *, PyTypeObject *)> implicit_conversions;
204
+ std::vector<std::pair<const std::type_info *, void *(*) (void *)>> implicit_casts;
205
+ std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
206
+ buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
207
+ void *get_buffer_data = nullptr;
208
+ void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
209
+ /* A simple type never occurs as a (direct or indirect) parent
210
+ * of a class that makes use of multiple inheritance.
211
+ * A type can be simple even if it has non-simple ancestors as long as it has no descendants.
212
+ */
213
+ bool simple_type : 1;
214
+ /* True if there is no multiple inheritance in this type's inheritance tree */
215
+ bool simple_ancestors : 1;
216
+ /* for base vs derived holder_type checks */
217
+ bool default_holder : 1;
218
+ /* true if this is a type registered with py::module_local */
219
+ bool module_local : 1;
220
+ };
221
+
222
+ /// On MSVC, debug and release builds are not ABI-compatible!
223
+ #if defined(_MSC_VER) && defined(_DEBUG)
224
+ # define PYBIND11_BUILD_TYPE "_debug"
225
+ #else
226
+ # define PYBIND11_BUILD_TYPE ""
227
+ #endif
228
+
229
+ /// Let's assume that different compilers are ABI-incompatible.
230
+ /// A user can manually set this string if they know their
231
+ /// compiler is compatible.
232
+ #ifndef PYBIND11_COMPILER_TYPE
233
+ # if defined(_MSC_VER)
234
+ # define PYBIND11_COMPILER_TYPE "_msvc"
235
+ # elif defined(__INTEL_COMPILER)
236
+ # define PYBIND11_COMPILER_TYPE "_icc"
237
+ # elif defined(__clang__)
238
+ # define PYBIND11_COMPILER_TYPE "_clang"
239
+ # elif defined(__PGI)
240
+ # define PYBIND11_COMPILER_TYPE "_pgi"
241
+ # elif defined(__MINGW32__)
242
+ # define PYBIND11_COMPILER_TYPE "_mingw"
243
+ # elif defined(__CYGWIN__)
244
+ # define PYBIND11_COMPILER_TYPE "_gcc_cygwin"
245
+ # elif defined(__GNUC__)
246
+ # define PYBIND11_COMPILER_TYPE "_gcc"
247
+ # else
248
+ # define PYBIND11_COMPILER_TYPE "_unknown"
249
+ # endif
250
+ #endif
251
+
252
+ /// Also standard libs
253
+ #ifndef PYBIND11_STDLIB
254
+ # if defined(_LIBCPP_VERSION)
255
+ # define PYBIND11_STDLIB "_libcpp"
256
+ # elif defined(__GLIBCXX__) || defined(__GLIBCPP__)
257
+ # define PYBIND11_STDLIB "_libstdcpp"
258
+ # else
259
+ # define PYBIND11_STDLIB ""
260
+ # endif
261
+ #endif
262
+
263
+ /// On Linux/OSX, changes in __GXX_ABI_VERSION__ indicate ABI incompatibility.
264
+ #ifndef PYBIND11_BUILD_ABI
265
+ # if defined(__GXX_ABI_VERSION)
266
+ # define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION)
267
+ # else
268
+ # define PYBIND11_BUILD_ABI ""
269
+ # endif
270
+ #endif
271
+
272
+ #ifndef PYBIND11_INTERNALS_KIND
273
+ # if defined(WITH_THREAD)
274
+ # define PYBIND11_INTERNALS_KIND ""
275
+ # else
276
+ # define PYBIND11_INTERNALS_KIND "_without_thread"
277
+ # endif
278
+ #endif
279
+
280
+ #define PYBIND11_INTERNALS_ID \
281
+ "__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
282
+ PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
283
+ PYBIND11_BUILD_TYPE "__"
284
+
285
+ #define PYBIND11_MODULE_LOCAL_ID \
286
+ "__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
287
+ PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
288
+ PYBIND11_BUILD_TYPE "__"
289
+
290
+ /// Each module locally stores a pointer to the `internals` data. The data
291
+ /// itself is shared among modules with the same `PYBIND11_INTERNALS_ID`.
292
+ inline internals **&get_internals_pp() {
293
+ static internals **internals_pp = nullptr;
294
+ return internals_pp;
295
+ }
296
+
297
+ #if PY_VERSION_HEX >= 0x03030000
298
+ // forward decl
299
+ inline void translate_exception(std::exception_ptr);
300
+
301
+ template <class T,
302
+ enable_if_t<std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
303
+ bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
304
+ std::exception_ptr nested = exc.nested_ptr();
305
+ if (nested != nullptr && nested != p) {
306
+ translate_exception(nested);
307
+ return true;
308
+ }
309
+ return false;
310
+ }
311
+
312
+ template <class T,
313
+ enable_if_t<!std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
314
+ bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
315
+ if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {
316
+ return handle_nested_exception(*nep, p);
317
+ }
318
+ return false;
319
+ }
320
+
321
+ #else
322
+
323
+ template <class T>
324
+ bool handle_nested_exception(const T &, std::exception_ptr &) {
325
+ return false;
326
+ }
327
+ #endif
328
+
329
+ inline bool raise_err(PyObject *exc_type, const char *msg) {
330
+ #if PY_VERSION_HEX >= 0x03030000
331
+ if (PyErr_Occurred()) {
332
+ raise_from(exc_type, msg);
333
+ return true;
334
+ }
335
+ #endif
336
+ PyErr_SetString(exc_type, msg);
337
+ return false;
338
+ }
339
+
340
+ inline void translate_exception(std::exception_ptr p) {
341
+ if (!p) {
342
+ return;
343
+ }
344
+ try {
345
+ std::rethrow_exception(p);
346
+ } catch (error_already_set &e) {
347
+ handle_nested_exception(e, p);
348
+ e.restore();
349
+ return;
350
+ } catch (const builtin_exception &e) {
351
+ // Could not use template since it's an abstract class.
352
+ if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {
353
+ handle_nested_exception(*nep, p);
354
+ }
355
+ e.set_error();
356
+ return;
357
+ } catch (const std::bad_alloc &e) {
358
+ handle_nested_exception(e, p);
359
+ raise_err(PyExc_MemoryError, e.what());
360
+ return;
361
+ } catch (const std::domain_error &e) {
362
+ handle_nested_exception(e, p);
363
+ raise_err(PyExc_ValueError, e.what());
364
+ return;
365
+ } catch (const std::invalid_argument &e) {
366
+ handle_nested_exception(e, p);
367
+ raise_err(PyExc_ValueError, e.what());
368
+ return;
369
+ } catch (const std::length_error &e) {
370
+ handle_nested_exception(e, p);
371
+ raise_err(PyExc_ValueError, e.what());
372
+ return;
373
+ } catch (const std::out_of_range &e) {
374
+ handle_nested_exception(e, p);
375
+ raise_err(PyExc_IndexError, e.what());
376
+ return;
377
+ } catch (const std::range_error &e) {
378
+ handle_nested_exception(e, p);
379
+ raise_err(PyExc_ValueError, e.what());
380
+ return;
381
+ } catch (const std::overflow_error &e) {
382
+ handle_nested_exception(e, p);
383
+ raise_err(PyExc_OverflowError, e.what());
384
+ return;
385
+ } catch (const std::exception &e) {
386
+ handle_nested_exception(e, p);
387
+ raise_err(PyExc_RuntimeError, e.what());
388
+ return;
389
+ } catch (const std::nested_exception &e) {
390
+ handle_nested_exception(e, p);
391
+ raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!");
392
+ return;
393
+ } catch (...) {
394
+ raise_err(PyExc_RuntimeError, "Caught an unknown exception!");
395
+ return;
396
+ }
397
+ }
398
+
399
+ #if !defined(__GLIBCXX__)
400
+ inline void translate_local_exception(std::exception_ptr p) {
401
+ try {
402
+ if (p) {
403
+ std::rethrow_exception(p);
404
+ }
405
+ } catch (error_already_set &e) {
406
+ e.restore();
407
+ return;
408
+ } catch (const builtin_exception &e) {
409
+ e.set_error();
410
+ return;
411
+ }
412
+ }
413
+ #endif
414
+
415
+ /// Return a reference to the current `internals` data
416
+ PYBIND11_NOINLINE internals &get_internals() {
417
+ auto **&internals_pp = get_internals_pp();
418
+ if (internals_pp && *internals_pp) {
419
+ return **internals_pp;
420
+ }
421
+
422
+ // Ensure that the GIL is held since we will need to make Python calls.
423
+ // Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
424
+ struct gil_scoped_acquire_local {
425
+ gil_scoped_acquire_local() : state(PyGILState_Ensure()) {}
426
+ ~gil_scoped_acquire_local() { PyGILState_Release(state); }
427
+ const PyGILState_STATE state;
428
+ } gil;
429
+
430
+ PYBIND11_STR_TYPE id(PYBIND11_INTERNALS_ID);
431
+ auto builtins = handle(PyEval_GetBuiltins());
432
+ if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
433
+ internals_pp = static_cast<internals **>(capsule(builtins[id]));
434
+
435
+ // We loaded builtins through python's builtins, which means that our `error_already_set`
436
+ // and `builtin_exception` may be different local classes than the ones set up in the
437
+ // initial exception translator, below, so add another for our local exception classes.
438
+ //
439
+ // libstdc++ doesn't require this (types there are identified only by name)
440
+ // libc++ with CPython doesn't require this (types are explicitly exported)
441
+ // libc++ with PyPy still need it, awaiting further investigation
442
+ #if !defined(__GLIBCXX__)
443
+ (*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
444
+ #endif
445
+ } else {
446
+ if (!internals_pp) {
447
+ internals_pp = new internals *();
448
+ }
449
+ auto *&internals_ptr = *internals_pp;
450
+ internals_ptr = new internals();
451
+ #if defined(WITH_THREAD)
452
+
453
+ # if PY_VERSION_HEX < 0x03090000
454
+ PyEval_InitThreads();
455
+ # endif
456
+ PyThreadState *tstate = PyThreadState_Get();
457
+ if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
458
+ pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
459
+ }
460
+ PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
461
+
462
+ # if PYBIND11_INTERNALS_VERSION > 4
463
+ if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
464
+ pybind11_fail("get_internals: could not successfully initialize the "
465
+ "loader_life_support TSS key!");
466
+ }
467
+ # endif
468
+ internals_ptr->istate = tstate->interp;
469
+ #endif
470
+ builtins[id] = capsule(internals_pp);
471
+ internals_ptr->registered_exception_translators.push_front(&translate_exception);
472
+ internals_ptr->static_property_type = make_static_property_type();
473
+ internals_ptr->default_metaclass = make_default_metaclass();
474
+ internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
475
+ }
476
+ return **internals_pp;
477
+ }
478
+
479
+ // the internals struct (above) is shared between all the modules. local_internals are only
480
+ // for a single module. Any changes made to internals may require an update to
481
+ // PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
482
+ // restricted to a single module. Whether a module has local internals or not should not
483
+ // impact any other modules, because the only things accessing the local internals is the
484
+ // module that contains them.
485
+ struct local_internals {
486
+ type_map<type_info *> registered_types_cpp;
487
+ std::forward_list<ExceptionTranslator> registered_exception_translators;
488
+ #if defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
489
+
490
+ // For ABI compatibility, we can't store the loader_life_support TLS key in
491
+ // the `internals` struct directly. Instead, we store it in `shared_data` and
492
+ // cache a copy in `local_internals`. If we allocated a separate TLS key for
493
+ // each instance of `local_internals`, we could end up allocating hundreds of
494
+ // TLS keys if hundreds of different pybind11 modules are loaded (which is a
495
+ // plausible number).
496
+ PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
497
+
498
+ // Holds the shared TLS key for the loader_life_support stack.
499
+ struct shared_loader_life_support_data {
500
+ PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
501
+ shared_loader_life_support_data() {
502
+ if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
503
+ pybind11_fail("local_internals: could not successfully initialize the "
504
+ "loader_life_support TLS key!");
505
+ }
506
+ }
507
+ // We can't help but leak the TLS key, because Python never unloads extension modules.
508
+ };
509
+
510
+ local_internals() {
511
+ auto &internals = get_internals();
512
+ // Get or create the `loader_life_support_stack_key`.
513
+ auto &ptr = internals.shared_data["_life_support"];
514
+ if (!ptr) {
515
+ ptr = new shared_loader_life_support_data;
516
+ }
517
+ loader_life_support_tls_key
518
+ = static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
519
+ }
520
+ #endif // defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
521
+ };
522
+
523
+ /// Works like `get_internals`, but for things which are locally registered.
524
+ inline local_internals &get_local_internals() {
525
+ static local_internals locals;
526
+ return locals;
527
+ }
528
+
529
+ /// Constructs a std::string with the given arguments, stores it in `internals`, and returns its
530
+ /// `c_str()`. Such strings objects have a long storage duration -- the internal strings are only
531
+ /// cleared when the program exits or after interpreter shutdown (when embedding), and so are
532
+ /// suitable for c-style strings needed by Python internals (such as PyTypeObject's tp_name).
533
+ template <typename... Args>
534
+ const char *c_str(Args &&...args) {
535
+ auto &strings = get_internals().static_strings;
536
+ strings.emplace_front(std::forward<Args>(args)...);
537
+ return strings.front().c_str();
538
+ }
539
+
540
+ PYBIND11_NAMESPACE_END(detail)
541
+
542
+ /// Returns a named pointer that is shared among all extension modules (using the same
543
+ /// pybind11 version) running in the current interpreter. Names starting with underscores
544
+ /// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
545
+ PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
546
+ auto &internals = detail::get_internals();
547
+ auto it = internals.shared_data.find(name);
548
+ return it != internals.shared_data.end() ? it->second : nullptr;
549
+ }
550
+
551
+ /// Set the shared data that can be later recovered by `get_shared_data()`.
552
+ PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
553
+ detail::get_internals().shared_data[name] = data;
554
+ return data;
555
+ }
556
+
557
+ /// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
558
+ /// such entry exists. Otherwise, a new object of default-constructible type `T` is
559
+ /// added to the shared data under the given name and a reference to it is returned.
560
+ template <typename T>
561
+ T &get_or_create_shared_data(const std::string &name) {
562
+ auto &internals = detail::get_internals();
563
+ auto it = internals.shared_data.find(name);
564
+ T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
565
+ if (!ptr) {
566
+ ptr = new T();
567
+ internals.shared_data[name] = ptr;
568
+ }
569
+ return *ptr;
570
+ }
571
+
572
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/type_caster_base.h ADDED
@@ -0,0 +1,1083 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/type_caster_base.h (originally first part of pybind11/cast.h)
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "../pytypes.h"
13
+ #include "common.h"
14
+ #include "descr.h"
15
+ #include "internals.h"
16
+ #include "typeid.h"
17
+
18
+ #include <cstdint>
19
+ #include <iterator>
20
+ #include <new>
21
+ #include <string>
22
+ #include <type_traits>
23
+ #include <typeindex>
24
+ #include <typeinfo>
25
+ #include <unordered_map>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
30
+ PYBIND11_NAMESPACE_BEGIN(detail)
31
+
32
+ /// A life support system for temporary objects created by `type_caster::load()`.
33
+ /// Adding a patient will keep it alive up until the enclosing function returns.
34
+ class loader_life_support {
35
+ private:
36
+ loader_life_support *parent = nullptr;
37
+ std::unordered_set<PyObject *> keep_alive;
38
+
39
+ #if defined(WITH_THREAD)
40
+ // Store stack pointer in thread-local storage.
41
+ static PYBIND11_TLS_KEY_REF get_stack_tls_key() {
42
+ # if PYBIND11_INTERNALS_VERSION == 4
43
+ return get_local_internals().loader_life_support_tls_key;
44
+ # else
45
+ return get_internals().loader_life_support_tls_key;
46
+ # endif
47
+ }
48
+ static loader_life_support *get_stack_top() {
49
+ return static_cast<loader_life_support *>(PYBIND11_TLS_GET_VALUE(get_stack_tls_key()));
50
+ }
51
+ static void set_stack_top(loader_life_support *value) {
52
+ PYBIND11_TLS_REPLACE_VALUE(get_stack_tls_key(), value);
53
+ }
54
+ #else
55
+ // Use single global variable for stack.
56
+ static loader_life_support **get_stack_pp() {
57
+ static loader_life_support *global_stack = nullptr;
58
+ return global_stack;
59
+ }
60
+ static loader_life_support *get_stack_top() { return *get_stack_pp(); }
61
+ static void set_stack_top(loader_life_support *value) { *get_stack_pp() = value; }
62
+ #endif
63
+
64
+ public:
65
+ /// A new patient frame is created when a function is entered
66
+ loader_life_support() : parent{get_stack_top()} { set_stack_top(this); }
67
+
68
+ /// ... and destroyed after it returns
69
+ ~loader_life_support() {
70
+ if (get_stack_top() != this) {
71
+ pybind11_fail("loader_life_support: internal error");
72
+ }
73
+ set_stack_top(parent);
74
+ for (auto *item : keep_alive) {
75
+ Py_DECREF(item);
76
+ }
77
+ }
78
+
79
+ /// This can only be used inside a pybind11-bound function, either by `argument_loader`
80
+ /// at argument preparation time or by `py::cast()` at execution time.
81
+ PYBIND11_NOINLINE static void add_patient(handle h) {
82
+ loader_life_support *frame = get_stack_top();
83
+ if (!frame) {
84
+ // NOTE: It would be nice to include the stack frames here, as this indicates
85
+ // use of pybind11::cast<> outside the normal call framework, finding such
86
+ // a location is challenging. Developers could consider printing out
87
+ // stack frame addresses here using something like __builtin_frame_address(0)
88
+ throw cast_error("When called outside a bound function, py::cast() cannot "
89
+ "do Python -> C++ conversions which require the creation "
90
+ "of temporary values");
91
+ }
92
+
93
+ if (frame->keep_alive.insert(h.ptr()).second) {
94
+ Py_INCREF(h.ptr());
95
+ }
96
+ }
97
+ };
98
+
99
+ // Gets the cache entry for the given type, creating it if necessary. The return value is the pair
100
+ // returned by emplace, i.e. an iterator for the entry and a bool set to `true` if the entry was
101
+ // just created.
102
+ inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
103
+ all_type_info_get_cache(PyTypeObject *type);
104
+
105
+ // Populates a just-created cache entry.
106
+ PYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
107
+ std::vector<PyTypeObject *> check;
108
+ for (handle parent : reinterpret_borrow<tuple>(t->tp_bases)) {
109
+ check.push_back((PyTypeObject *) parent.ptr());
110
+ }
111
+
112
+ auto const &type_dict = get_internals().registered_types_py;
113
+ for (size_t i = 0; i < check.size(); i++) {
114
+ auto *type = check[i];
115
+ // Ignore Python2 old-style class super type:
116
+ if (!PyType_Check((PyObject *) type)) {
117
+ continue;
118
+ }
119
+
120
+ // Check `type` in the current set of registered python types:
121
+ auto it = type_dict.find(type);
122
+ if (it != type_dict.end()) {
123
+ // We found a cache entry for it, so it's either pybind-registered or has pre-computed
124
+ // pybind bases, but we have to make sure we haven't already seen the type(s) before:
125
+ // we want to follow Python/virtual C++ rules that there should only be one instance of
126
+ // a common base.
127
+ for (auto *tinfo : it->second) {
128
+ // NB: Could use a second set here, rather than doing a linear search, but since
129
+ // having a large number of immediate pybind11-registered types seems fairly
130
+ // unlikely, that probably isn't worthwhile.
131
+ bool found = false;
132
+ for (auto *known : bases) {
133
+ if (known == tinfo) {
134
+ found = true;
135
+ break;
136
+ }
137
+ }
138
+ if (!found) {
139
+ bases.push_back(tinfo);
140
+ }
141
+ }
142
+ } else if (type->tp_bases) {
143
+ // It's some python type, so keep follow its bases classes to look for one or more
144
+ // registered types
145
+ if (i + 1 == check.size()) {
146
+ // When we're at the end, we can pop off the current element to avoid growing
147
+ // `check` when adding just one base (which is typical--i.e. when there is no
148
+ // multiple inheritance)
149
+ check.pop_back();
150
+ i--;
151
+ }
152
+ for (handle parent : reinterpret_borrow<tuple>(type->tp_bases)) {
153
+ check.push_back((PyTypeObject *) parent.ptr());
154
+ }
155
+ }
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Extracts vector of type_info pointers of pybind-registered roots of the given Python type. Will
161
+ * be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side
162
+ * derived class that uses single inheritance. Will contain as many types as required for a Python
163
+ * class that uses multiple inheritance to inherit (directly or indirectly) from multiple
164
+ * pybind-registered classes. Will be empty if neither the type nor any base classes are
165
+ * pybind-registered.
166
+ *
167
+ * The value is cached for the lifetime of the Python type.
168
+ */
169
+ inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
170
+ auto ins = all_type_info_get_cache(type);
171
+ if (ins.second) {
172
+ // New cache entry: populate it
173
+ all_type_info_populate(type, ins.first->second);
174
+ }
175
+
176
+ return ins.first->second;
177
+ }
178
+
179
+ /**
180
+ * Gets a single pybind11 type info for a python type. Returns nullptr if neither the type nor any
181
+ * ancestors are pybind11-registered. Throws an exception if there are multiple bases--use
182
+ * `all_type_info` instead if you want to support multiple bases.
183
+ */
184
+ PYBIND11_NOINLINE detail::type_info *get_type_info(PyTypeObject *type) {
185
+ const auto &bases = all_type_info(type);
186
+ if (bases.empty()) {
187
+ return nullptr;
188
+ }
189
+ if (bases.size() > 1) {
190
+ pybind11_fail(
191
+ "pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
192
+ }
193
+ return bases.front();
194
+ }
195
+
196
+ inline detail::type_info *get_local_type_info(const std::type_index &tp) {
197
+ auto &locals = get_local_internals().registered_types_cpp;
198
+ auto it = locals.find(tp);
199
+ if (it != locals.end()) {
200
+ return it->second;
201
+ }
202
+ return nullptr;
203
+ }
204
+
205
+ inline detail::type_info *get_global_type_info(const std::type_index &tp) {
206
+ auto &types = get_internals().registered_types_cpp;
207
+ auto it = types.find(tp);
208
+ if (it != types.end()) {
209
+ return it->second;
210
+ }
211
+ return nullptr;
212
+ }
213
+
214
+ /// Return the type info for a given C++ type; on lookup failure can either throw or return
215
+ /// nullptr.
216
+ PYBIND11_NOINLINE detail::type_info *get_type_info(const std::type_index &tp,
217
+ bool throw_if_missing = false) {
218
+ if (auto *ltype = get_local_type_info(tp)) {
219
+ return ltype;
220
+ }
221
+ if (auto *gtype = get_global_type_info(tp)) {
222
+ return gtype;
223
+ }
224
+
225
+ if (throw_if_missing) {
226
+ std::string tname = tp.name();
227
+ detail::clean_type_id(tname);
228
+ pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \"" + tname
229
+ + "\"");
230
+ }
231
+ return nullptr;
232
+ }
233
+
234
+ PYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
235
+ detail::type_info *type_info = get_type_info(tp, throw_if_missing);
236
+ return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
237
+ }
238
+
239
+ // Searches the inheritance graph for a registered Python instance, using all_type_info().
240
+ PYBIND11_NOINLINE handle find_registered_python_instance(void *src,
241
+ const detail::type_info *tinfo) {
242
+ auto it_instances = get_internals().registered_instances.equal_range(src);
243
+ for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
244
+ for (auto *instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
245
+ if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype)) {
246
+ return handle((PyObject *) it_i->second).inc_ref();
247
+ }
248
+ }
249
+ }
250
+ return handle();
251
+ }
252
+
253
+ struct value_and_holder {
254
+ instance *inst = nullptr;
255
+ size_t index = 0u;
256
+ const detail::type_info *type = nullptr;
257
+ void **vh = nullptr;
258
+
259
+ // Main constructor for a found value/holder:
260
+ value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index)
261
+ : inst{i}, index{index}, type{type}, vh{inst->simple_layout
262
+ ? inst->simple_value_holder
263
+ : &inst->nonsimple.values_and_holders[vpos]} {}
264
+
265
+ // Default constructor (used to signal a value-and-holder not found by get_value_and_holder())
266
+ value_and_holder() = default;
267
+
268
+ // Used for past-the-end iterator
269
+ explicit value_and_holder(size_t index) : index{index} {}
270
+
271
+ template <typename V = void>
272
+ V *&value_ptr() const {
273
+ return reinterpret_cast<V *&>(vh[0]);
274
+ }
275
+ // True if this `value_and_holder` has a non-null value pointer
276
+ explicit operator bool() const { return value_ptr() != nullptr; }
277
+
278
+ template <typename H>
279
+ H &holder() const {
280
+ return reinterpret_cast<H &>(vh[1]);
281
+ }
282
+ bool holder_constructed() const {
283
+ return inst->simple_layout
284
+ ? inst->simple_holder_constructed
285
+ : (inst->nonsimple.status[index] & instance::status_holder_constructed) != 0u;
286
+ }
287
+ // NOLINTNEXTLINE(readability-make-member-function-const)
288
+ void set_holder_constructed(bool v = true) {
289
+ if (inst->simple_layout) {
290
+ inst->simple_holder_constructed = v;
291
+ } else if (v) {
292
+ inst->nonsimple.status[index] |= instance::status_holder_constructed;
293
+ } else {
294
+ inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_holder_constructed;
295
+ }
296
+ }
297
+ bool instance_registered() const {
298
+ return inst->simple_layout
299
+ ? inst->simple_instance_registered
300
+ : ((inst->nonsimple.status[index] & instance::status_instance_registered) != 0);
301
+ }
302
+ // NOLINTNEXTLINE(readability-make-member-function-const)
303
+ void set_instance_registered(bool v = true) {
304
+ if (inst->simple_layout) {
305
+ inst->simple_instance_registered = v;
306
+ } else if (v) {
307
+ inst->nonsimple.status[index] |= instance::status_instance_registered;
308
+ } else {
309
+ inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_instance_registered;
310
+ }
311
+ }
312
+ };
313
+
314
+ // Container for accessing and iterating over an instance's values/holders
315
+ struct values_and_holders {
316
+ private:
317
+ instance *inst;
318
+ using type_vec = std::vector<detail::type_info *>;
319
+ const type_vec &tinfo;
320
+
321
+ public:
322
+ explicit values_and_holders(instance *inst)
323
+ : inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
324
+
325
+ struct iterator {
326
+ private:
327
+ instance *inst = nullptr;
328
+ const type_vec *types = nullptr;
329
+ value_and_holder curr;
330
+ friend struct values_and_holders;
331
+ iterator(instance *inst, const type_vec *tinfo)
332
+ : inst{inst}, types{tinfo},
333
+ curr(inst /* instance */,
334
+ types->empty() ? nullptr : (*types)[0] /* type info */,
335
+ 0, /* vpos: (non-simple types only): the first vptr comes first */
336
+ 0 /* index */) {}
337
+ // Past-the-end iterator:
338
+ explicit iterator(size_t end) : curr(end) {}
339
+
340
+ public:
341
+ bool operator==(const iterator &other) const { return curr.index == other.curr.index; }
342
+ bool operator!=(const iterator &other) const { return curr.index != other.curr.index; }
343
+ iterator &operator++() {
344
+ if (!inst->simple_layout) {
345
+ curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
346
+ }
347
+ ++curr.index;
348
+ curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
349
+ return *this;
350
+ }
351
+ value_and_holder &operator*() { return curr; }
352
+ value_and_holder *operator->() { return &curr; }
353
+ };
354
+
355
+ iterator begin() { return iterator(inst, &tinfo); }
356
+ iterator end() { return iterator(tinfo.size()); }
357
+
358
+ iterator find(const type_info *find_type) {
359
+ auto it = begin(), endit = end();
360
+ while (it != endit && it->type != find_type) {
361
+ ++it;
362
+ }
363
+ return it;
364
+ }
365
+
366
+ size_t size() { return tinfo.size(); }
367
+ };
368
+
369
+ /**
370
+ * Extracts C++ value and holder pointer references from an instance (which may contain multiple
371
+ * values/holders for python-side multiple inheritance) that match the given type. Throws an error
372
+ * if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance. If
373
+ * `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,
374
+ * regardless of type (and the resulting .type will be nullptr).
375
+ *
376
+ * The returned object should be short-lived: in particular, it must not outlive the called-upon
377
+ * instance.
378
+ */
379
+ PYBIND11_NOINLINE value_and_holder
380
+ instance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/,
381
+ bool throw_if_missing /*= true in common.h*/) {
382
+ // Optimize common case:
383
+ if (!find_type || Py_TYPE(this) == find_type->type) {
384
+ return value_and_holder(this, find_type, 0, 0);
385
+ }
386
+
387
+ detail::values_and_holders vhs(this);
388
+ auto it = vhs.find(find_type);
389
+ if (it != vhs.end()) {
390
+ return *it;
391
+ }
392
+
393
+ if (!throw_if_missing) {
394
+ return value_and_holder();
395
+ }
396
+
397
+ #if defined(NDEBUG)
398
+ pybind11_fail("pybind11::detail::instance::get_value_and_holder: "
399
+ "type is not a pybind11 base of the given instance "
400
+ "(compile in debug mode for type details)");
401
+ #else
402
+ pybind11_fail("pybind11::detail::instance::get_value_and_holder: `"
403
+ + get_fully_qualified_tp_name(find_type->type)
404
+ + "' is not a pybind11 base of the given `"
405
+ + get_fully_qualified_tp_name(Py_TYPE(this)) + "' instance");
406
+ #endif
407
+ }
408
+
409
+ PYBIND11_NOINLINE void instance::allocate_layout() {
410
+ const auto &tinfo = all_type_info(Py_TYPE(this));
411
+
412
+ const size_t n_types = tinfo.size();
413
+
414
+ if (n_types == 0) {
415
+ pybind11_fail(
416
+ "instance allocation failed: new instance has no pybind11-registered base types");
417
+ }
418
+
419
+ simple_layout
420
+ = n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
421
+
422
+ // Simple path: no python-side multiple inheritance, and a small-enough holder
423
+ if (simple_layout) {
424
+ simple_value_holder[0] = nullptr;
425
+ simple_holder_constructed = false;
426
+ simple_instance_registered = false;
427
+ } else { // multiple base types or a too-large holder
428
+ // Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
429
+ // [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
430
+ // values that tracks whether each associated holder has been initialized. Each [block] is
431
+ // padded, if necessary, to an integer multiple of sizeof(void *).
432
+ size_t space = 0;
433
+ for (auto *t : tinfo) {
434
+ space += 1; // value pointer
435
+ space += t->holder_size_in_ptrs; // holder instance
436
+ }
437
+ size_t flags_at = space;
438
+ space += size_in_ptrs(n_types); // status bytes (holder_constructed and
439
+ // instance_registered)
440
+
441
+ // Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
442
+ // in particular, need to be 0). Use Python's memory allocation functions: in Python 3.6
443
+ // they default to using pymalloc, which is designed to be efficient for small allocations
444
+ // like the one we're doing here; in earlier versions (and for larger allocations) they are
445
+ // just wrappers around malloc.
446
+ #if PY_VERSION_HEX >= 0x03050000
447
+ nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
448
+ if (!nonsimple.values_and_holders) {
449
+ throw std::bad_alloc();
450
+ }
451
+ #else
452
+ nonsimple.values_and_holders = (void **) PyMem_New(void *, space);
453
+ if (!nonsimple.values_and_holders)
454
+ throw std::bad_alloc();
455
+ std::memset(nonsimple.values_and_holders, 0, space * sizeof(void *));
456
+ #endif
457
+ nonsimple.status
458
+ = reinterpret_cast<std::uint8_t *>(&nonsimple.values_and_holders[flags_at]);
459
+ }
460
+ owned = true;
461
+ }
462
+
463
+ // NOLINTNEXTLINE(readability-make-member-function-const)
464
+ PYBIND11_NOINLINE void instance::deallocate_layout() {
465
+ if (!simple_layout) {
466
+ PyMem_Free(nonsimple.values_and_holders);
467
+ }
468
+ }
469
+
470
+ PYBIND11_NOINLINE bool isinstance_generic(handle obj, const std::type_info &tp) {
471
+ handle type = detail::get_type_handle(tp, false);
472
+ if (!type) {
473
+ return false;
474
+ }
475
+ return isinstance(obj, type);
476
+ }
477
+
478
+ PYBIND11_NOINLINE std::string error_string() {
479
+ if (!PyErr_Occurred()) {
480
+ PyErr_SetString(PyExc_RuntimeError, "Unknown internal error occurred");
481
+ return "Unknown internal error occurred";
482
+ }
483
+
484
+ error_scope scope; // Preserve error state
485
+
486
+ std::string errorString;
487
+ if (scope.type) {
488
+ errorString += handle(scope.type).attr("__name__").cast<std::string>();
489
+ errorString += ": ";
490
+ }
491
+ if (scope.value) {
492
+ errorString += (std::string) str(scope.value);
493
+ }
494
+
495
+ PyErr_NormalizeException(&scope.type, &scope.value, &scope.trace);
496
+
497
+ #if PY_MAJOR_VERSION >= 3
498
+ if (scope.trace != nullptr) {
499
+ PyException_SetTraceback(scope.value, scope.trace);
500
+ }
501
+ #endif
502
+
503
+ #if !defined(PYPY_VERSION)
504
+ if (scope.trace) {
505
+ auto *trace = (PyTracebackObject *) scope.trace;
506
+
507
+ /* Get the deepest trace possible */
508
+ while (trace->tb_next) {
509
+ trace = trace->tb_next;
510
+ }
511
+
512
+ PyFrameObject *frame = trace->tb_frame;
513
+ Py_XINCREF(frame);
514
+ errorString += "\n\nAt:\n";
515
+ while (frame) {
516
+ # if PY_VERSION_HEX >= 0x030900B1
517
+ PyCodeObject *f_code = PyFrame_GetCode(frame);
518
+ # else
519
+ PyCodeObject *f_code = frame->f_code;
520
+ Py_INCREF(f_code);
521
+ # endif
522
+ int lineno = PyFrame_GetLineNumber(frame);
523
+ errorString += " " + handle(f_code->co_filename).cast<std::string>() + "("
524
+ + std::to_string(lineno)
525
+ + "): " + handle(f_code->co_name).cast<std::string>() + "\n";
526
+ Py_DECREF(f_code);
527
+ # if PY_VERSION_HEX >= 0x030900B1
528
+ auto *b_frame = PyFrame_GetBack(frame);
529
+ # else
530
+ auto *b_frame = frame->f_back;
531
+ Py_XINCREF(b_frame);
532
+ # endif
533
+ Py_DECREF(frame);
534
+ frame = b_frame;
535
+ }
536
+ }
537
+ #endif
538
+
539
+ return errorString;
540
+ }
541
+
542
+ PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type) {
543
+ auto &instances = get_internals().registered_instances;
544
+ auto range = instances.equal_range(ptr);
545
+ for (auto it = range.first; it != range.second; ++it) {
546
+ for (const auto &vh : values_and_holders(it->second)) {
547
+ if (vh.type == type) {
548
+ return handle((PyObject *) it->second);
549
+ }
550
+ }
551
+ }
552
+ return handle();
553
+ }
554
+
555
+ inline PyThreadState *get_thread_state_unchecked() {
556
+ #if defined(PYPY_VERSION)
557
+ return PyThreadState_GET();
558
+ #elif PY_VERSION_HEX < 0x03000000
559
+ return _PyThreadState_Current;
560
+ #elif PY_VERSION_HEX < 0x03050000
561
+ return (PyThreadState *) _Py_atomic_load_relaxed(&_PyThreadState_Current);
562
+ #elif PY_VERSION_HEX < 0x03050200
563
+ return (PyThreadState *) _PyThreadState_Current.value;
564
+ #else
565
+ return _PyThreadState_UncheckedGet();
566
+ #endif
567
+ }
568
+
569
+ // Forward declarations
570
+ void keep_alive_impl(handle nurse, handle patient);
571
+ inline PyObject *make_new_instance(PyTypeObject *type);
572
+
573
+ class type_caster_generic {
574
+ public:
575
+ PYBIND11_NOINLINE explicit type_caster_generic(const std::type_info &type_info)
576
+ : typeinfo(get_type_info(type_info)), cpptype(&type_info) {}
577
+
578
+ explicit type_caster_generic(const type_info *typeinfo)
579
+ : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) {}
580
+
581
+ bool load(handle src, bool convert) { return load_impl<type_caster_generic>(src, convert); }
582
+
583
+ PYBIND11_NOINLINE static handle cast(const void *_src,
584
+ return_value_policy policy,
585
+ handle parent,
586
+ const detail::type_info *tinfo,
587
+ void *(*copy_constructor)(const void *),
588
+ void *(*move_constructor)(const void *),
589
+ const void *existing_holder = nullptr) {
590
+ if (!tinfo) { // no type info: error will be set already
591
+ return handle();
592
+ }
593
+
594
+ void *src = const_cast<void *>(_src);
595
+ if (src == nullptr) {
596
+ return none().release();
597
+ }
598
+
599
+ if (handle registered_inst = find_registered_python_instance(src, tinfo)) {
600
+ return registered_inst;
601
+ }
602
+
603
+ auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
604
+ auto *wrapper = reinterpret_cast<instance *>(inst.ptr());
605
+ wrapper->owned = false;
606
+ void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
607
+
608
+ switch (policy) {
609
+ case return_value_policy::automatic:
610
+ case return_value_policy::take_ownership:
611
+ valueptr = src;
612
+ wrapper->owned = true;
613
+ break;
614
+
615
+ case return_value_policy::automatic_reference:
616
+ case return_value_policy::reference:
617
+ valueptr = src;
618
+ wrapper->owned = false;
619
+ break;
620
+
621
+ case return_value_policy::copy:
622
+ if (copy_constructor) {
623
+ valueptr = copy_constructor(src);
624
+ } else {
625
+ #if defined(NDEBUG)
626
+ throw cast_error("return_value_policy = copy, but type is "
627
+ "non-copyable! (compile in debug mode for details)");
628
+ #else
629
+ std::string type_name(tinfo->cpptype->name());
630
+ detail::clean_type_id(type_name);
631
+ throw cast_error("return_value_policy = copy, but type " + type_name
632
+ + " is non-copyable!");
633
+ #endif
634
+ }
635
+ wrapper->owned = true;
636
+ break;
637
+
638
+ case return_value_policy::move:
639
+ if (move_constructor) {
640
+ valueptr = move_constructor(src);
641
+ } else if (copy_constructor) {
642
+ valueptr = copy_constructor(src);
643
+ } else {
644
+ #if defined(NDEBUG)
645
+ throw cast_error("return_value_policy = move, but type is neither "
646
+ "movable nor copyable! "
647
+ "(compile in debug mode for details)");
648
+ #else
649
+ std::string type_name(tinfo->cpptype->name());
650
+ detail::clean_type_id(type_name);
651
+ throw cast_error("return_value_policy = move, but type " + type_name
652
+ + " is neither movable nor copyable!");
653
+ #endif
654
+ }
655
+ wrapper->owned = true;
656
+ break;
657
+
658
+ case return_value_policy::reference_internal:
659
+ valueptr = src;
660
+ wrapper->owned = false;
661
+ keep_alive_impl(inst, parent);
662
+ break;
663
+
664
+ default:
665
+ throw cast_error("unhandled return_value_policy: should not happen!");
666
+ }
667
+
668
+ tinfo->init_instance(wrapper, existing_holder);
669
+
670
+ return inst.release();
671
+ }
672
+
673
+ // Base methods for generic caster; there are overridden in copyable_holder_caster
674
+ void load_value(value_and_holder &&v_h) {
675
+ auto *&vptr = v_h.value_ptr();
676
+ // Lazy allocation for unallocated values:
677
+ if (vptr == nullptr) {
678
+ const auto *type = v_h.type ? v_h.type : typeinfo;
679
+ if (type->operator_new) {
680
+ vptr = type->operator_new(type->type_size);
681
+ } else {
682
+ #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
683
+ if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
684
+ vptr = ::operator new(type->type_size, std::align_val_t(type->type_align));
685
+ } else {
686
+ vptr = ::operator new(type->type_size);
687
+ }
688
+ #else
689
+ vptr = ::operator new(type->type_size);
690
+ #endif
691
+ }
692
+ }
693
+ value = vptr;
694
+ }
695
+ bool try_implicit_casts(handle src, bool convert) {
696
+ for (const auto &cast : typeinfo->implicit_casts) {
697
+ type_caster_generic sub_caster(*cast.first);
698
+ if (sub_caster.load(src, convert)) {
699
+ value = cast.second(sub_caster.value);
700
+ return true;
701
+ }
702
+ }
703
+ return false;
704
+ }
705
+ bool try_direct_conversions(handle src) {
706
+ for (auto &converter : *typeinfo->direct_conversions) {
707
+ if (converter(src.ptr(), value)) {
708
+ return true;
709
+ }
710
+ }
711
+ return false;
712
+ }
713
+ void check_holder_compat() {}
714
+
715
+ PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
716
+ auto caster = type_caster_generic(ti);
717
+ if (caster.load(src, false)) {
718
+ return caster.value;
719
+ }
720
+ return nullptr;
721
+ }
722
+
723
+ /// Try to load with foreign typeinfo, if available. Used when there is no
724
+ /// native typeinfo, or when the native one wasn't able to produce a value.
725
+ PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
726
+ constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
727
+ const auto pytype = type::handle_of(src);
728
+ if (!hasattr(pytype, local_key)) {
729
+ return false;
730
+ }
731
+
732
+ type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
733
+ // Only consider this foreign loader if actually foreign and is a loader of the correct cpp
734
+ // type
735
+ if (foreign_typeinfo->module_local_load == &local_load
736
+ || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype))) {
737
+ return false;
738
+ }
739
+
740
+ if (auto *result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
741
+ value = result;
742
+ return true;
743
+ }
744
+ return false;
745
+ }
746
+
747
+ // Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
748
+ // bits of code between here and copyable_holder_caster where the two classes need different
749
+ // logic (without having to resort to virtual inheritance).
750
+ template <typename ThisT>
751
+ PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
752
+ if (!src) {
753
+ return false;
754
+ }
755
+ if (!typeinfo) {
756
+ return try_load_foreign_module_local(src);
757
+ }
758
+
759
+ auto &this_ = static_cast<ThisT &>(*this);
760
+ this_.check_holder_compat();
761
+
762
+ PyTypeObject *srctype = Py_TYPE(src.ptr());
763
+
764
+ // Case 1: If src is an exact type match for the target type then we can reinterpret_cast
765
+ // the instance's value pointer to the target type:
766
+ if (srctype == typeinfo->type) {
767
+ this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
768
+ return true;
769
+ }
770
+ // Case 2: We have a derived class
771
+ if (PyType_IsSubtype(srctype, typeinfo->type)) {
772
+ const auto &bases = all_type_info(srctype);
773
+ bool no_cpp_mi = typeinfo->simple_type;
774
+
775
+ // Case 2a: the python type is a Python-inherited derived class that inherits from just
776
+ // one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
777
+ // the right type and we can use reinterpret_cast.
778
+ // (This is essentially the same as case 2b, but because not using multiple inheritance
779
+ // is extremely common, we handle it specially to avoid the loop iterator and type
780
+ // pointer lookup overhead)
781
+ if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
782
+ this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
783
+ return true;
784
+ }
785
+ // Case 2b: the python type inherits from multiple C++ bases. Check the bases to see
786
+ // if we can find an exact match (or, for a simple C++ type, an inherited match); if
787
+ // so, we can safely reinterpret_cast to the relevant pointer.
788
+ if (bases.size() > 1) {
789
+ for (auto *base : bases) {
790
+ if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type)
791
+ : base->type == typeinfo->type) {
792
+ this_.load_value(
793
+ reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
794
+ return true;
795
+ }
796
+ }
797
+ }
798
+
799
+ // Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type
800
+ // match in the registered bases, above, so try implicit casting (needed for proper C++
801
+ // casting when MI is involved).
802
+ if (this_.try_implicit_casts(src, convert)) {
803
+ return true;
804
+ }
805
+ }
806
+
807
+ // Perform an implicit conversion
808
+ if (convert) {
809
+ for (const auto &converter : typeinfo->implicit_conversions) {
810
+ auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
811
+ if (load_impl<ThisT>(temp, false)) {
812
+ loader_life_support::add_patient(temp);
813
+ return true;
814
+ }
815
+ }
816
+ if (this_.try_direct_conversions(src)) {
817
+ return true;
818
+ }
819
+ }
820
+
821
+ // Failed to match local typeinfo. Try again with global.
822
+ if (typeinfo->module_local) {
823
+ if (auto *gtype = get_global_type_info(*typeinfo->cpptype)) {
824
+ typeinfo = gtype;
825
+ return load(src, false);
826
+ }
827
+ }
828
+
829
+ // Global typeinfo has precedence over foreign module_local
830
+ if (try_load_foreign_module_local(src)) {
831
+ return true;
832
+ }
833
+
834
+ // Custom converters didn't take None, now we convert None to nullptr.
835
+ if (src.is_none()) {
836
+ // Defer accepting None to other overloads (if we aren't in convert mode):
837
+ if (!convert) {
838
+ return false;
839
+ }
840
+ value = nullptr;
841
+ return true;
842
+ }
843
+
844
+ return false;
845
+ }
846
+
847
+ // Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
848
+ // isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
849
+ // with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
850
+ PYBIND11_NOINLINE static std::pair<const void *, const type_info *>
851
+ src_and_type(const void *src,
852
+ const std::type_info &cast_type,
853
+ const std::type_info *rtti_type = nullptr) {
854
+ if (auto *tpi = get_type_info(cast_type)) {
855
+ return {src, const_cast<const type_info *>(tpi)};
856
+ }
857
+
858
+ // Not found, set error:
859
+ std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
860
+ detail::clean_type_id(tname);
861
+ std::string msg = "Unregistered type : " + tname;
862
+ PyErr_SetString(PyExc_TypeError, msg.c_str());
863
+ return {nullptr, nullptr};
864
+ }
865
+
866
+ const type_info *typeinfo = nullptr;
867
+ const std::type_info *cpptype = nullptr;
868
+ void *value = nullptr;
869
+ };
870
+
871
+ /**
872
+ * Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
873
+ * needs to provide `operator T*()` and `operator T&()` operators.
874
+ *
875
+ * If the type supports moving the value away via an `operator T&&() &&` method, it should use
876
+ * `movable_cast_op_type` instead.
877
+ */
878
+ template <typename T>
879
+ using cast_op_type = conditional_t<std::is_pointer<remove_reference_t<T>>::value,
880
+ typename std::add_pointer<intrinsic_t<T>>::type,
881
+ typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
882
+
883
+ /**
884
+ * Determine suitable casting operator for a type caster with a movable value. Such a type caster
885
+ * needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
886
+ * called in appropriate contexts where the value can be moved rather than copied.
887
+ *
888
+ * These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
889
+ */
890
+ template <typename T>
891
+ using movable_cast_op_type
892
+ = conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
893
+ typename std::add_pointer<intrinsic_t<T>>::type,
894
+ conditional_t<std::is_rvalue_reference<T>::value,
895
+ typename std::add_rvalue_reference<intrinsic_t<T>>::type,
896
+ typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
897
+
898
+ // std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
899
+ // T is non-copyable, but code containing such a copy constructor fails to actually compile.
900
+ template <typename T, typename SFINAE = void>
901
+ struct is_copy_constructible : std::is_copy_constructible<T> {};
902
+
903
+ // Specialization for types that appear to be copy constructible but also look like stl containers
904
+ // (we specifically check for: has `value_type` and `reference` with `reference = value_type&`): if
905
+ // so, copy constructability depends on whether the value_type is copy constructible.
906
+ template <typename Container>
907
+ struct is_copy_constructible<
908
+ Container,
909
+ enable_if_t<
910
+ all_of<std::is_copy_constructible<Container>,
911
+ std::is_same<typename Container::value_type &, typename Container::reference>,
912
+ // Avoid infinite recursion
913
+ negation<std::is_same<Container, typename Container::value_type>>>::value>>
914
+ : is_copy_constructible<typename Container::value_type> {};
915
+
916
+ // Likewise for std::pair
917
+ // (after C++17 it is mandatory that the copy constructor not exist when the two types aren't
918
+ // themselves copy constructible, but this can not be relied upon when T1 or T2 are themselves
919
+ // containers).
920
+ template <typename T1, typename T2>
921
+ struct is_copy_constructible<std::pair<T1, T2>>
922
+ : all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
923
+
924
+ // The same problems arise with std::is_copy_assignable, so we use the same workaround.
925
+ template <typename T, typename SFINAE = void>
926
+ struct is_copy_assignable : std::is_copy_assignable<T> {};
927
+ template <typename Container>
928
+ struct is_copy_assignable<Container,
929
+ enable_if_t<all_of<std::is_copy_assignable<Container>,
930
+ std::is_same<typename Container::value_type &,
931
+ typename Container::reference>>::value>>
932
+ : is_copy_assignable<typename Container::value_type> {};
933
+ template <typename T1, typename T2>
934
+ struct is_copy_assignable<std::pair<T1, T2>>
935
+ : all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
936
+
937
+ PYBIND11_NAMESPACE_END(detail)
938
+
939
+ // polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed
940
+ // to by `src` actually is an instance of some class derived from `itype`.
941
+ // If so, it sets `tinfo` to point to the std::type_info representing that derived
942
+ // type, and returns a pointer to the start of the most-derived object of that type
943
+ // (in which `src` is a subobject; this will be the same address as `src` in most
944
+ // single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`
945
+ // and leaves `tinfo` at its default value of nullptr.
946
+ //
947
+ // The default polymorphic_type_hook just returns src. A specialization for polymorphic
948
+ // types determines the runtime type of the passed object and adjusts the this-pointer
949
+ // appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear
950
+ // to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is
951
+ // registered with pybind11, and this Animal is in fact a Dog).
952
+ //
953
+ // You may specialize polymorphic_type_hook yourself for types that want to appear
954
+ // polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern
955
+ // in performance-sensitive applications, used most notably in LLVM.)
956
+ //
957
+ // polymorphic_type_hook_base allows users to specialize polymorphic_type_hook with
958
+ // std::enable_if. User provided specializations will always have higher priority than
959
+ // the default implementation and specialization provided in polymorphic_type_hook_base.
960
+ template <typename itype, typename SFINAE = void>
961
+ struct polymorphic_type_hook_base {
962
+ static const void *get(const itype *src, const std::type_info *&) { return src; }
963
+ };
964
+ template <typename itype>
965
+ struct polymorphic_type_hook_base<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>> {
966
+ static const void *get(const itype *src, const std::type_info *&type) {
967
+ type = src ? &typeid(*src) : nullptr;
968
+ return dynamic_cast<const void *>(src);
969
+ }
970
+ };
971
+ template <typename itype, typename SFINAE = void>
972
+ struct polymorphic_type_hook : public polymorphic_type_hook_base<itype> {};
973
+
974
+ PYBIND11_NAMESPACE_BEGIN(detail)
975
+
976
+ /// Generic type caster for objects stored on the heap
977
+ template <typename type>
978
+ class type_caster_base : public type_caster_generic {
979
+ using itype = intrinsic_t<type>;
980
+
981
+ public:
982
+ static constexpr auto name = const_name<type>();
983
+
984
+ type_caster_base() : type_caster_base(typeid(type)) {}
985
+ explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) {}
986
+
987
+ static handle cast(const itype &src, return_value_policy policy, handle parent) {
988
+ if (policy == return_value_policy::automatic
989
+ || policy == return_value_policy::automatic_reference) {
990
+ policy = return_value_policy::copy;
991
+ }
992
+ return cast(&src, policy, parent);
993
+ }
994
+
995
+ static handle cast(itype &&src, return_value_policy, handle parent) {
996
+ return cast(&src, return_value_policy::move, parent);
997
+ }
998
+
999
+ // Returns a (pointer, type_info) pair taking care of necessary type lookup for a
1000
+ // polymorphic type (using RTTI by default, but can be overridden by specializing
1001
+ // polymorphic_type_hook). If the instance isn't derived, returns the base version.
1002
+ static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
1003
+ const auto &cast_type = typeid(itype);
1004
+ const std::type_info *instance_type = nullptr;
1005
+ const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
1006
+ if (instance_type && !same_type(cast_type, *instance_type)) {
1007
+ // This is a base pointer to a derived type. If the derived type is registered
1008
+ // with pybind11, we want to make the full derived object available.
1009
+ // In the typical case where itype is polymorphic, we get the correct
1010
+ // derived pointer (which may be != base pointer) by a dynamic_cast to
1011
+ // most derived type. If itype is not polymorphic, we won't get here
1012
+ // except via a user-provided specialization of polymorphic_type_hook,
1013
+ // and the user has promised that no this-pointer adjustment is
1014
+ // required in that case, so it's OK to use static_cast.
1015
+ if (const auto *tpi = get_type_info(*instance_type)) {
1016
+ return {vsrc, tpi};
1017
+ }
1018
+ }
1019
+ // Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer,
1020
+ // so don't do a cast
1021
+ return type_caster_generic::src_and_type(src, cast_type, instance_type);
1022
+ }
1023
+
1024
+ static handle cast(const itype *src, return_value_policy policy, handle parent) {
1025
+ auto st = src_and_type(src);
1026
+ return type_caster_generic::cast(st.first,
1027
+ policy,
1028
+ parent,
1029
+ st.second,
1030
+ make_copy_constructor(src),
1031
+ make_move_constructor(src));
1032
+ }
1033
+
1034
+ static handle cast_holder(const itype *src, const void *holder) {
1035
+ auto st = src_and_type(src);
1036
+ return type_caster_generic::cast(st.first,
1037
+ return_value_policy::take_ownership,
1038
+ {},
1039
+ st.second,
1040
+ nullptr,
1041
+ nullptr,
1042
+ holder);
1043
+ }
1044
+
1045
+ template <typename T>
1046
+ using cast_op_type = detail::cast_op_type<T>;
1047
+
1048
+ // NOLINTNEXTLINE(google-explicit-constructor)
1049
+ operator itype *() { return (type *) value; }
1050
+ // NOLINTNEXTLINE(google-explicit-constructor)
1051
+ operator itype &() {
1052
+ if (!value) {
1053
+ throw reference_cast_error();
1054
+ }
1055
+ return *((itype *) value);
1056
+ }
1057
+
1058
+ protected:
1059
+ using Constructor = void *(*) (const void *);
1060
+
1061
+ /* Only enabled when the types are {copy,move}-constructible *and* when the type
1062
+ does not have a private operator new implementation. A comma operator is used in the
1063
+ decltype argument to apply SFINAE to the public copy/move constructors.*/
1064
+ template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
1065
+ static auto make_copy_constructor(const T *)
1066
+ -> decltype(new T(std::declval<const T>()), Constructor{}) {
1067
+ return [](const void *arg) -> void * { return new T(*reinterpret_cast<const T *>(arg)); };
1068
+ }
1069
+
1070
+ template <typename T, typename = enable_if_t<std::is_move_constructible<T>::value>>
1071
+ static auto make_move_constructor(const T *)
1072
+ -> decltype(new T(std::declval<T &&>()), Constructor{}) {
1073
+ return [](const void *arg) -> void * {
1074
+ return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
1075
+ };
1076
+ }
1077
+
1078
+ static Constructor make_copy_constructor(...) { return nullptr; }
1079
+ static Constructor make_move_constructor(...) { return nullptr; }
1080
+ };
1081
+
1082
+ PYBIND11_NAMESPACE_END(detail)
1083
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/detail/typeid.h ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/typeid.h: Compiler-independent access to type identifiers
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include <cstdio>
13
+ #include <cstdlib>
14
+
15
+ #if defined(__GNUG__)
16
+ # include <cxxabi.h>
17
+ #endif
18
+
19
+ #include "common.h"
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+ PYBIND11_NAMESPACE_BEGIN(detail)
23
+ /// Erase all occurrences of a substring
24
+ inline void erase_all(std::string &string, const std::string &search) {
25
+ for (size_t pos = 0;;) {
26
+ pos = string.find(search, pos);
27
+ if (pos == std::string::npos) {
28
+ break;
29
+ }
30
+ string.erase(pos, search.length());
31
+ }
32
+ }
33
+
34
+ PYBIND11_NOINLINE void clean_type_id(std::string &name) {
35
+ #if defined(__GNUG__)
36
+ int status = 0;
37
+ std::unique_ptr<char, void (*)(void *)> res{
38
+ abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free};
39
+ if (status == 0) {
40
+ name = res.get();
41
+ }
42
+ #else
43
+ detail::erase_all(name, "class ");
44
+ detail::erase_all(name, "struct ");
45
+ detail::erase_all(name, "enum ");
46
+ #endif
47
+ detail::erase_all(name, "pybind11::");
48
+ }
49
+ PYBIND11_NAMESPACE_END(detail)
50
+
51
+ /// Return a string representation of a C++ type
52
+ template <typename T>
53
+ static std::string type_id() {
54
+ std::string name(typeid(T).name());
55
+ detail::clean_type_id(name);
56
+ return name;
57
+ }
58
+
59
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/eigen.h ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/eigen.h: Transparent conversion for dense and sparse Eigen matrices
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ /* HINT: To suppress warnings originating from the Eigen headers, use -isystem.
13
+ See also:
14
+ https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir
15
+ https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler
16
+ */
17
+
18
+ #include "numpy.h"
19
+
20
+ // The C4127 suppression was introduced for Eigen 3.4.0. In theory we could
21
+ // make it version specific, or even remove it later, but considering that
22
+ // 1. C4127 is generally far more distracting than useful for modern template code, and
23
+ // 2. we definitely want to ignore any MSVC warnings originating from Eigen code,
24
+ // it is probably best to keep this around indefinitely.
25
+ #if defined(_MSC_VER)
26
+ # pragma warning(push)
27
+ # pragma warning(disable : 4127) // C4127: conditional expression is constant
28
+ #endif
29
+
30
+ #include <Eigen/Core>
31
+ #include <Eigen/SparseCore>
32
+
33
+ #if defined(_MSC_VER)
34
+ # pragma warning(pop)
35
+ #endif
36
+
37
+ // Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
38
+ // move constructors that break things. We could detect this an explicitly copy, but an extra copy
39
+ // of matrices seems highly undesirable.
40
+ static_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),
41
+ "Eigen support in pybind11 requires Eigen >= 3.2.7");
42
+
43
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
44
+
45
+ // Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
46
+ using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
47
+ template <typename MatrixType>
48
+ using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;
49
+ template <typename MatrixType>
50
+ using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
51
+
52
+ PYBIND11_NAMESPACE_BEGIN(detail)
53
+
54
+ #if EIGEN_VERSION_AT_LEAST(3, 3, 0)
55
+ using EigenIndex = Eigen::Index;
56
+ template <typename Scalar, int Flags, typename StorageIndex>
57
+ using EigenMapSparseMatrix = Eigen::Map<Eigen::SparseMatrix<Scalar, Flags, StorageIndex>>;
58
+ #else
59
+ using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
60
+ template <typename Scalar, int Flags, typename StorageIndex>
61
+ using EigenMapSparseMatrix = Eigen::MappedSparseMatrix<Scalar, Flags, StorageIndex>;
62
+ #endif
63
+
64
+ // Matches Eigen::Map, Eigen::Ref, blocks, etc:
65
+ template <typename T>
66
+ using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>,
67
+ std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
68
+ template <typename T>
69
+ using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
70
+ template <typename T>
71
+ using is_eigen_dense_plain
72
+ = all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>;
73
+ template <typename T>
74
+ using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>;
75
+ // Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This
76
+ // basically covers anything that can be assigned to a dense matrix but that don't have a typical
77
+ // matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and
78
+ // SelfAdjointView fall into this category.
79
+ template <typename T>
80
+ using is_eigen_other
81
+ = all_of<is_template_base_of<Eigen::EigenBase, T>,
82
+ negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>>;
83
+
84
+ // Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
85
+ template <bool EigenRowMajor>
86
+ struct EigenConformable {
87
+ bool conformable = false;
88
+ EigenIndex rows = 0, cols = 0;
89
+ EigenDStride stride{0, 0}; // Only valid if negativestrides is false!
90
+ bool negativestrides = false; // If true, do not use stride!
91
+
92
+ // NOLINTNEXTLINE(google-explicit-constructor)
93
+ EigenConformable(bool fits = false) : conformable{fits} {}
94
+ // Matrix type:
95
+ EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)
96
+ : conformable{true}, rows{r}, cols{c},
97
+ // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.
98
+ // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
99
+ stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)
100
+ : (cstride > 0 ? cstride : 0) /* outer stride */,
101
+ EigenRowMajor ? (cstride > 0 ? cstride : 0)
102
+ : (rstride > 0 ? rstride : 0) /* inner stride */},
103
+ negativestrides{rstride < 0 || cstride < 0} {}
104
+ // Vector type:
105
+ EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)
106
+ : EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}
107
+
108
+ template <typename props>
109
+ bool stride_compatible() const {
110
+ // To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
111
+ // matching strides, or a dimension size of 1 (in which case the stride value is
112
+ // irrelevant)
113
+ return !negativestrides
114
+ && (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()
115
+ || (EigenRowMajor ? cols : rows) == 1)
116
+ && (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()
117
+ || (EigenRowMajor ? rows : cols) == 1);
118
+ }
119
+ // NOLINTNEXTLINE(google-explicit-constructor)
120
+ operator bool() const { return conformable; }
121
+ };
122
+
123
+ template <typename Type>
124
+ struct eigen_extract_stride {
125
+ using type = Type;
126
+ };
127
+ template <typename PlainObjectType, int MapOptions, typename StrideType>
128
+ struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> {
129
+ using type = StrideType;
130
+ };
131
+ template <typename PlainObjectType, int Options, typename StrideType>
132
+ struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> {
133
+ using type = StrideType;
134
+ };
135
+
136
+ // Helper struct for extracting information from an Eigen type
137
+ template <typename Type_>
138
+ struct EigenProps {
139
+ using Type = Type_;
140
+ using Scalar = typename Type::Scalar;
141
+ using StrideType = typename eigen_extract_stride<Type>::type;
142
+ static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,
143
+ size = Type::SizeAtCompileTime;
144
+ static constexpr bool row_major = Type::IsRowMajor,
145
+ vector
146
+ = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
147
+ fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,
148
+ fixed = size != Eigen::Dynamic, // Fully-fixed size
149
+ dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
150
+
151
+ template <EigenIndex i, EigenIndex ifzero>
152
+ using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
153
+ static constexpr EigenIndex inner_stride
154
+ = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,
155
+ outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,
156
+ vector ? size
157
+ : row_major ? cols
158
+ : rows > ::value;
159
+ static constexpr bool dynamic_stride
160
+ = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
161
+ static constexpr bool requires_row_major
162
+ = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
163
+ static constexpr bool requires_col_major
164
+ = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
165
+
166
+ // Takes an input array and determines whether we can make it fit into the Eigen type. If
167
+ // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
168
+ // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
169
+ static EigenConformable<row_major> conformable(const array &a) {
170
+ const auto dims = a.ndim();
171
+ if (dims < 1 || dims > 2) {
172
+ return false;
173
+ }
174
+
175
+ if (dims == 2) { // Matrix type: require exact match (or dynamic)
176
+
177
+ EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),
178
+ np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),
179
+ np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));
180
+ if ((PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && np_rows != rows)
181
+ || (PYBIND11_SILENCE_MSVC_C4127(fixed_cols) && np_cols != cols)) {
182
+ return false;
183
+ }
184
+
185
+ return {np_rows, np_cols, np_rstride, np_cstride};
186
+ }
187
+
188
+ // Otherwise we're storing an n-vector. Only one of the strides will be used, but
189
+ // whichever is used, we want the (single) numpy stride value.
190
+ const EigenIndex n = a.shape(0),
191
+ stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));
192
+
193
+ if (vector) { // Eigen type is a compile-time vector
194
+ if (PYBIND11_SILENCE_MSVC_C4127(fixed) && size != n) {
195
+ return false; // Vector size mismatch
196
+ }
197
+ return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
198
+ }
199
+ if (fixed) {
200
+ // The type has a fixed size, but is not a vector: abort
201
+ return false;
202
+ }
203
+ if (fixed_cols) {
204
+ // Since this isn't a vector, cols must be != 1. We allow this only if it exactly
205
+ // equals the number of elements (rows is Dynamic, and so 1 row is allowed).
206
+ if (cols != n) {
207
+ return false;
208
+ }
209
+ return {1, n, stride};
210
+ } // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
211
+ if (PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && rows != n) {
212
+ return false;
213
+ }
214
+ return {n, 1, stride};
215
+ }
216
+
217
+ static constexpr bool show_writeable
218
+ = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;
219
+ static constexpr bool show_order = is_eigen_dense_map<Type>::value;
220
+ static constexpr bool show_c_contiguous = show_order && requires_row_major;
221
+ static constexpr bool show_f_contiguous
222
+ = !show_c_contiguous && show_order && requires_col_major;
223
+
224
+ static constexpr auto descriptor
225
+ = const_name("numpy.ndarray[") + npy_format_descriptor<Scalar>::name + const_name("[")
226
+ + const_name<fixed_rows>(const_name<(size_t) rows>(), const_name("m")) + const_name(", ")
227
+ + const_name<fixed_cols>(const_name<(size_t) cols>(), const_name("n")) + const_name("]")
228
+ +
229
+ // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to
230
+ // be satisfied: writeable=True (for a mutable reference), and, depending on the map's
231
+ // stride options, possibly f_contiguous or c_contiguous. We include them in the
232
+ // descriptor output to provide some hint as to why a TypeError is occurring (otherwise
233
+ // it can be confusing to see that a function accepts a 'numpy.ndarray[float64[3,2]]' and
234
+ // an error message that you *gave* a numpy.ndarray of the right type and dimensions.
235
+ const_name<show_writeable>(", flags.writeable", "")
236
+ + const_name<show_c_contiguous>(", flags.c_contiguous", "")
237
+ + const_name<show_f_contiguous>(", flags.f_contiguous", "") + const_name("]");
238
+ };
239
+
240
+ // Casts an Eigen type to numpy array. If given a base, the numpy array references the src data,
241
+ // otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array.
242
+ template <typename props>
243
+ handle
244
+ eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
245
+ constexpr ssize_t elem_size = sizeof(typename props::Scalar);
246
+ array a;
247
+ if (props::vector) {
248
+ a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);
249
+ } else {
250
+ a = array({src.rows(), src.cols()},
251
+ {elem_size * src.rowStride(), elem_size * src.colStride()},
252
+ src.data(),
253
+ base);
254
+ }
255
+
256
+ if (!writeable) {
257
+ array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
258
+ }
259
+
260
+ return a.release();
261
+ }
262
+
263
+ // Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
264
+ // reference the Eigen object's data with `base` as the python-registered base class (if omitted,
265
+ // the base will be set to None, and lifetime management is up to the caller). The numpy array is
266
+ // non-writeable if the given type is const.
267
+ template <typename props, typename Type>
268
+ handle eigen_ref_array(Type &src, handle parent = none()) {
269
+ // none here is to get past array's should-we-copy detection, which currently always
270
+ // copies when there is no base. Setting the base to None should be harmless.
271
+ return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
272
+ }
273
+
274
+ // Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a
275
+ // numpy array that references the encapsulated data with a python-side reference to the capsule to
276
+ // tie its destruction to that of any dependent python objects. Const-ness is determined by
277
+ // whether or not the Type of the pointer given is const.
278
+ template <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>>
279
+ handle eigen_encapsulate(Type *src) {
280
+ capsule base(src, [](void *o) { delete static_cast<Type *>(o); });
281
+ return eigen_ref_array<props>(*src, base);
282
+ }
283
+
284
+ // Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
285
+ // types.
286
+ template <typename Type>
287
+ struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {
288
+ using Scalar = typename Type::Scalar;
289
+ using props = EigenProps<Type>;
290
+
291
+ bool load(handle src, bool convert) {
292
+ // If we're in no-convert mode, only load if given an array of the correct type
293
+ if (!convert && !isinstance<array_t<Scalar>>(src)) {
294
+ return false;
295
+ }
296
+
297
+ // Coerce into an array, but don't do type conversion yet; the copy below handles it.
298
+ auto buf = array::ensure(src);
299
+
300
+ if (!buf) {
301
+ return false;
302
+ }
303
+
304
+ auto dims = buf.ndim();
305
+ if (dims < 1 || dims > 2) {
306
+ return false;
307
+ }
308
+
309
+ auto fits = props::conformable(buf);
310
+ if (!fits) {
311
+ return false;
312
+ }
313
+
314
+ // Allocate the new type, then build a numpy reference into it
315
+ value = Type(fits.rows, fits.cols);
316
+ auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value));
317
+ if (dims == 1) {
318
+ ref = ref.squeeze();
319
+ } else if (ref.ndim() == 1) {
320
+ buf = buf.squeeze();
321
+ }
322
+
323
+ int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());
324
+
325
+ if (result < 0) { // Copy failed!
326
+ PyErr_Clear();
327
+ return false;
328
+ }
329
+
330
+ return true;
331
+ }
332
+
333
+ private:
334
+ // Cast implementation
335
+ template <typename CType>
336
+ static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
337
+ switch (policy) {
338
+ case return_value_policy::take_ownership:
339
+ case return_value_policy::automatic:
340
+ return eigen_encapsulate<props>(src);
341
+ case return_value_policy::move:
342
+ return eigen_encapsulate<props>(new CType(std::move(*src)));
343
+ case return_value_policy::copy:
344
+ return eigen_array_cast<props>(*src);
345
+ case return_value_policy::reference:
346
+ case return_value_policy::automatic_reference:
347
+ return eigen_ref_array<props>(*src);
348
+ case return_value_policy::reference_internal:
349
+ return eigen_ref_array<props>(*src, parent);
350
+ default:
351
+ throw cast_error("unhandled return_value_policy: should not happen!");
352
+ };
353
+ }
354
+
355
+ public:
356
+ // Normal returned non-reference, non-const value:
357
+ static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
358
+ return cast_impl(&src, return_value_policy::move, parent);
359
+ }
360
+ // If you return a non-reference const, we mark the numpy array readonly:
361
+ static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
362
+ return cast_impl(&src, return_value_policy::move, parent);
363
+ }
364
+ // lvalue reference return; default (automatic) becomes copy
365
+ static handle cast(Type &src, return_value_policy policy, handle parent) {
366
+ if (policy == return_value_policy::automatic
367
+ || policy == return_value_policy::automatic_reference) {
368
+ policy = return_value_policy::copy;
369
+ }
370
+ return cast_impl(&src, policy, parent);
371
+ }
372
+ // const lvalue reference return; default (automatic) becomes copy
373
+ static handle cast(const Type &src, return_value_policy policy, handle parent) {
374
+ if (policy == return_value_policy::automatic
375
+ || policy == return_value_policy::automatic_reference) {
376
+ policy = return_value_policy::copy;
377
+ }
378
+ return cast(&src, policy, parent);
379
+ }
380
+ // non-const pointer return
381
+ static handle cast(Type *src, return_value_policy policy, handle parent) {
382
+ return cast_impl(src, policy, parent);
383
+ }
384
+ // const pointer return
385
+ static handle cast(const Type *src, return_value_policy policy, handle parent) {
386
+ return cast_impl(src, policy, parent);
387
+ }
388
+
389
+ static constexpr auto name = props::descriptor;
390
+
391
+ // NOLINTNEXTLINE(google-explicit-constructor)
392
+ operator Type *() { return &value; }
393
+ // NOLINTNEXTLINE(google-explicit-constructor)
394
+ operator Type &() { return value; }
395
+ // NOLINTNEXTLINE(google-explicit-constructor)
396
+ operator Type &&() && { return std::move(value); }
397
+ template <typename T>
398
+ using cast_op_type = movable_cast_op_type<T>;
399
+
400
+ private:
401
+ Type value;
402
+ };
403
+
404
+ // Base class for casting reference/map/block/etc. objects back to python.
405
+ template <typename MapType>
406
+ struct eigen_map_caster {
407
+ private:
408
+ using props = EigenProps<MapType>;
409
+
410
+ public:
411
+ // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
412
+ // to stay around), but we'll allow it under the assumption that you know what you're doing
413
+ // (and have an appropriate keep_alive in place). We return a numpy array pointing directly at
414
+ // the ref's data (The numpy array ends up read-only if the ref was to a const matrix type.)
415
+ // Note that this means you need to ensure you don't destroy the object in some other way (e.g.
416
+ // with an appropriate keep_alive, or with a reference to a statically allocated matrix).
417
+ static handle cast(const MapType &src, return_value_policy policy, handle parent) {
418
+ switch (policy) {
419
+ case return_value_policy::copy:
420
+ return eigen_array_cast<props>(src);
421
+ case return_value_policy::reference_internal:
422
+ return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value);
423
+ case return_value_policy::reference:
424
+ case return_value_policy::automatic:
425
+ case return_value_policy::automatic_reference:
426
+ return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value);
427
+ default:
428
+ // move, take_ownership don't make any sense for a ref/map:
429
+ pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type");
430
+ }
431
+ }
432
+
433
+ static constexpr auto name = props::descriptor;
434
+
435
+ // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
436
+ // types but not bound arguments). We still provide them (with an explicitly delete) so that
437
+ // you end up here if you try anyway.
438
+ bool load(handle, bool) = delete;
439
+ operator MapType() = delete;
440
+ template <typename>
441
+ using cast_op_type = MapType;
442
+ };
443
+
444
+ // We can return any map-like object (but can only load Refs, specialized next):
445
+ template <typename Type>
446
+ struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> : eigen_map_caster<Type> {};
447
+
448
+ // Loader for Ref<...> arguments. See the documentation for info on how to make this work without
449
+ // copying (it requires some extra effort in many cases).
450
+ template <typename PlainObjectType, typename StrideType>
451
+ struct type_caster<
452
+ Eigen::Ref<PlainObjectType, 0, StrideType>,
453
+ enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>>
454
+ : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
455
+ private:
456
+ using Type = Eigen::Ref<PlainObjectType, 0, StrideType>;
457
+ using props = EigenProps<Type>;
458
+ using Scalar = typename props::Scalar;
459
+ using MapType = Eigen::Map<PlainObjectType, 0, StrideType>;
460
+ using Array
461
+ = array_t<Scalar,
462
+ array::forcecast
463
+ | ((props::row_major ? props::inner_stride : props::outer_stride) == 1
464
+ ? array::c_style
465
+ : (props::row_major ? props::outer_stride : props::inner_stride) == 1
466
+ ? array::f_style
467
+ : 0)>;
468
+ static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
469
+ // Delay construction (these have no default constructor)
470
+ std::unique_ptr<MapType> map;
471
+ std::unique_ptr<Type> ref;
472
+ // Our array. When possible, this is just a numpy array pointing to the source data, but
473
+ // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an
474
+ // incompatible layout, or is an array of a type that needs to be converted). Using a numpy
475
+ // temporary (rather than an Eigen temporary) saves an extra copy when we need both type
476
+ // conversion and storage order conversion. (Note that we refuse to use this temporary copy
477
+ // when loading an argument for a Ref<M> with M non-const, i.e. a read-write reference).
478
+ Array copy_or_ref;
479
+
480
+ public:
481
+ bool load(handle src, bool convert) {
482
+ // First check whether what we have is already an array of the right type. If not, we
483
+ // can't avoid a copy (because the copy is also going to do type conversion).
484
+ bool need_copy = !isinstance<Array>(src);
485
+
486
+ EigenConformable<props::row_major> fits;
487
+ if (!need_copy) {
488
+ // We don't need a converting copy, but we also need to check whether the strides are
489
+ // compatible with the Ref's stride requirements
490
+ auto aref = reinterpret_borrow<Array>(src);
491
+
492
+ if (aref && (!need_writeable || aref.writeable())) {
493
+ fits = props::conformable(aref);
494
+ if (!fits) {
495
+ return false; // Incompatible dimensions
496
+ }
497
+ if (!fits.template stride_compatible<props>()) {
498
+ need_copy = true;
499
+ } else {
500
+ copy_or_ref = std::move(aref);
501
+ }
502
+ } else {
503
+ need_copy = true;
504
+ }
505
+ }
506
+
507
+ if (need_copy) {
508
+ // We need to copy: If we need a mutable reference, or we're not supposed to convert
509
+ // (either because we're in the no-convert overload pass, or because we're explicitly
510
+ // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
511
+ if (!convert || need_writeable) {
512
+ return false;
513
+ }
514
+
515
+ Array copy = Array::ensure(src);
516
+ if (!copy) {
517
+ return false;
518
+ }
519
+ fits = props::conformable(copy);
520
+ if (!fits || !fits.template stride_compatible<props>()) {
521
+ return false;
522
+ }
523
+ copy_or_ref = std::move(copy);
524
+ loader_life_support::add_patient(copy_or_ref);
525
+ }
526
+
527
+ ref.reset();
528
+ map.reset(new MapType(data(copy_or_ref),
529
+ fits.rows,
530
+ fits.cols,
531
+ make_stride(fits.stride.outer(), fits.stride.inner())));
532
+ ref.reset(new Type(*map));
533
+
534
+ return true;
535
+ }
536
+
537
+ // NOLINTNEXTLINE(google-explicit-constructor)
538
+ operator Type *() { return ref.get(); }
539
+ // NOLINTNEXTLINE(google-explicit-constructor)
540
+ operator Type &() { return *ref; }
541
+ template <typename _T>
542
+ using cast_op_type = pybind11::detail::cast_op_type<_T>;
543
+
544
+ private:
545
+ template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0>
546
+ Scalar *data(Array &a) {
547
+ return a.mutable_data();
548
+ }
549
+
550
+ template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0>
551
+ const Scalar *data(Array &a) {
552
+ return a.data();
553
+ }
554
+
555
+ // Attempt to figure out a constructor of `Stride` that will work.
556
+ // If both strides are fixed, use a default constructor:
557
+ template <typename S>
558
+ using stride_ctor_default = bool_constant<S::InnerStrideAtCompileTime != Eigen::Dynamic
559
+ && S::OuterStrideAtCompileTime != Eigen::Dynamic
560
+ && std::is_default_constructible<S>::value>;
561
+ // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
562
+ // Eigen::Stride, and use it:
563
+ template <typename S>
564
+ using stride_ctor_dual
565
+ = bool_constant<!stride_ctor_default<S>::value
566
+ && std::is_constructible<S, EigenIndex, EigenIndex>::value>;
567
+ // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
568
+ // it (passing whichever stride is dynamic).
569
+ template <typename S>
570
+ using stride_ctor_outer
571
+ = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
572
+ && S::OuterStrideAtCompileTime == Eigen::Dynamic
573
+ && S::InnerStrideAtCompileTime != Eigen::Dynamic
574
+ && std::is_constructible<S, EigenIndex>::value>;
575
+ template <typename S>
576
+ using stride_ctor_inner
577
+ = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
578
+ && S::InnerStrideAtCompileTime == Eigen::Dynamic
579
+ && S::OuterStrideAtCompileTime != Eigen::Dynamic
580
+ && std::is_constructible<S, EigenIndex>::value>;
581
+
582
+ template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0>
583
+ static S make_stride(EigenIndex, EigenIndex) {
584
+ return S();
585
+ }
586
+ template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0>
587
+ static S make_stride(EigenIndex outer, EigenIndex inner) {
588
+ return S(outer, inner);
589
+ }
590
+ template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0>
591
+ static S make_stride(EigenIndex outer, EigenIndex) {
592
+ return S(outer);
593
+ }
594
+ template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0>
595
+ static S make_stride(EigenIndex, EigenIndex inner) {
596
+ return S(inner);
597
+ }
598
+ };
599
+
600
+ // type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
601
+ // EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
602
+ // load() is not supported, but we can cast them into the python domain by first copying to a
603
+ // regular Eigen::Matrix, then casting that.
604
+ template <typename Type>
605
+ struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {
606
+ protected:
607
+ using Matrix
608
+ = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;
609
+ using props = EigenProps<Matrix>;
610
+
611
+ public:
612
+ static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
613
+ handle h = eigen_encapsulate<props>(new Matrix(src));
614
+ return h;
615
+ }
616
+ static handle cast(const Type *src, return_value_policy policy, handle parent) {
617
+ return cast(*src, policy, parent);
618
+ }
619
+
620
+ static constexpr auto name = props::descriptor;
621
+
622
+ // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
623
+ // types but not bound arguments). We still provide them (with an explicitly delete) so that
624
+ // you end up here if you try anyway.
625
+ bool load(handle, bool) = delete;
626
+ operator Type() = delete;
627
+ template <typename>
628
+ using cast_op_type = Type;
629
+ };
630
+
631
+ template <typename Type>
632
+ struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
633
+ using Scalar = typename Type::Scalar;
634
+ using StorageIndex = remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())>;
635
+ using Index = typename Type::Index;
636
+ static constexpr bool rowMajor = Type::IsRowMajor;
637
+
638
+ bool load(handle src, bool) {
639
+ if (!src) {
640
+ return false;
641
+ }
642
+
643
+ auto obj = reinterpret_borrow<object>(src);
644
+ object sparse_module = module_::import("scipy.sparse");
645
+ object matrix_type = sparse_module.attr(rowMajor ? "csr_matrix" : "csc_matrix");
646
+
647
+ if (!type::handle_of(obj).is(matrix_type)) {
648
+ try {
649
+ obj = matrix_type(obj);
650
+ } catch (const error_already_set &) {
651
+ return false;
652
+ }
653
+ }
654
+
655
+ auto values = array_t<Scalar>((object) obj.attr("data"));
656
+ auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices"));
657
+ auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr"));
658
+ auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
659
+ auto nnz = obj.attr("nnz").cast<Index>();
660
+
661
+ if (!values || !innerIndices || !outerIndices) {
662
+ return false;
663
+ }
664
+
665
+ value = EigenMapSparseMatrix<Scalar,
666
+ Type::Flags &(Eigen::RowMajor | Eigen::ColMajor),
667
+ StorageIndex>(shape[0].cast<Index>(),
668
+ shape[1].cast<Index>(),
669
+ nnz,
670
+ outerIndices.mutable_data(),
671
+ innerIndices.mutable_data(),
672
+ values.mutable_data());
673
+
674
+ return true;
675
+ }
676
+
677
+ static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
678
+ const_cast<Type &>(src).makeCompressed();
679
+
680
+ object matrix_type
681
+ = module_::import("scipy.sparse").attr(rowMajor ? "csr_matrix" : "csc_matrix");
682
+
683
+ array data(src.nonZeros(), src.valuePtr());
684
+ array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
685
+ array innerIndices(src.nonZeros(), src.innerIndexPtr());
686
+
687
+ return matrix_type(std::make_tuple(data, innerIndices, outerIndices),
688
+ std::make_pair(src.rows(), src.cols()))
689
+ .release();
690
+ }
691
+
692
+ PYBIND11_TYPE_CASTER(Type,
693
+ const_name<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[",
694
+ "scipy.sparse.csc_matrix[")
695
+ + npy_format_descriptor<Scalar>::name + const_name("]"));
696
+ };
697
+
698
+ PYBIND11_NAMESPACE_END(detail)
699
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/embed.h ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/embed.h: Support for embedding the interpreter
3
+
4
+ Copyright (c) 2017 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+ #include "eval.h"
14
+
15
+ #include <memory>
16
+ #include <vector>
17
+
18
+ #if defined(PYPY_VERSION)
19
+ # error Embedding the interpreter is not supported with PyPy
20
+ #endif
21
+
22
+ #if PY_MAJOR_VERSION >= 3
23
+ # define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
24
+ extern "C" PyObject *pybind11_init_impl_##name(); \
25
+ extern "C" PyObject *pybind11_init_impl_##name() { return pybind11_init_wrapper_##name(); }
26
+ #else
27
+ # define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
28
+ extern "C" void pybind11_init_impl_##name(); \
29
+ extern "C" void pybind11_init_impl_##name() { pybind11_init_wrapper_##name(); }
30
+ #endif
31
+
32
+ /** \rst
33
+ Add a new module to the table of builtins for the interpreter. Must be
34
+ defined in global scope. The first macro parameter is the name of the
35
+ module (without quotes). The second parameter is the variable which will
36
+ be used as the interface to add functions and classes to the module.
37
+
38
+ .. code-block:: cpp
39
+
40
+ PYBIND11_EMBEDDED_MODULE(example, m) {
41
+ // ... initialize functions and classes here
42
+ m.def("foo", []() {
43
+ return "Hello, World!";
44
+ });
45
+ }
46
+ \endrst */
47
+ #define PYBIND11_EMBEDDED_MODULE(name, variable) \
48
+ static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name); \
49
+ static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
50
+ static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \
51
+ auto m = ::pybind11::module_::create_extension_module( \
52
+ PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
53
+ try { \
54
+ PYBIND11_CONCAT(pybind11_init_, name)(m); \
55
+ return m.ptr(); \
56
+ } \
57
+ PYBIND11_CATCH_INIT_EXCEPTIONS \
58
+ } \
59
+ PYBIND11_EMBEDDED_MODULE_IMPL(name) \
60
+ ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)( \
61
+ PYBIND11_TOSTRING(name), PYBIND11_CONCAT(pybind11_init_impl_, name)); \
62
+ void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ \
63
+ & variable) // NOLINT(bugprone-macro-parentheses)
64
+
65
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
66
+ PYBIND11_NAMESPACE_BEGIN(detail)
67
+
68
+ /// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks.
69
+ struct embedded_module {
70
+ #if PY_MAJOR_VERSION >= 3
71
+ using init_t = PyObject *(*) ();
72
+ #else
73
+ using init_t = void (*)();
74
+ #endif
75
+ embedded_module(const char *name, init_t init) {
76
+ if (Py_IsInitialized() != 0) {
77
+ pybind11_fail("Can't add new modules after the interpreter has been initialized");
78
+ }
79
+
80
+ auto result = PyImport_AppendInittab(name, init);
81
+ if (result == -1) {
82
+ pybind11_fail("Insufficient memory to add a new module");
83
+ }
84
+ }
85
+ };
86
+
87
+ struct wide_char_arg_deleter {
88
+ void operator()(wchar_t *ptr) const {
89
+ #if PY_VERSION_HEX >= 0x030500f0
90
+ // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale
91
+ PyMem_RawFree(ptr);
92
+ #else
93
+ delete[] ptr;
94
+ #endif
95
+ }
96
+ };
97
+
98
+ inline wchar_t *widen_chars(const char *safe_arg) {
99
+ #if PY_VERSION_HEX >= 0x030500f0
100
+ wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr);
101
+ #else
102
+ wchar_t *widened_arg = nullptr;
103
+
104
+ // warning C4996: 'mbstowcs': This function or variable may be unsafe.
105
+ # if defined(_MSC_VER)
106
+ # pragma warning(push)
107
+ # pragma warning(disable : 4996)
108
+ # endif
109
+
110
+ # if defined(HAVE_BROKEN_MBSTOWCS) && HAVE_BROKEN_MBSTOWCS
111
+ size_t count = std::strlen(safe_arg);
112
+ # else
113
+ size_t count = std::mbstowcs(nullptr, safe_arg, 0);
114
+ # endif
115
+ if (count != static_cast<size_t>(-1)) {
116
+ widened_arg = new wchar_t[count + 1];
117
+ std::mbstowcs(widened_arg, safe_arg, count + 1);
118
+ }
119
+
120
+ # if defined(_MSC_VER)
121
+ # pragma warning(pop)
122
+ # endif
123
+
124
+ #endif
125
+ return widened_arg;
126
+ }
127
+
128
+ /// Python 2.x/3.x-compatible version of `PySys_SetArgv`
129
+ inline void set_interpreter_argv(int argc, const char *const *argv, bool add_program_dir_to_path) {
130
+ // Before it was special-cased in python 3.8, passing an empty or null argv
131
+ // caused a segfault, so we have to reimplement the special case ourselves.
132
+ bool special_case = (argv == nullptr || argc <= 0);
133
+
134
+ const char *const empty_argv[]{"\0"};
135
+ const char *const *safe_argv = special_case ? empty_argv : argv;
136
+ if (special_case) {
137
+ argc = 1;
138
+ }
139
+
140
+ auto argv_size = static_cast<size_t>(argc);
141
+ #if PY_MAJOR_VERSION >= 3
142
+ // SetArgv* on python 3 takes wchar_t, so we have to convert.
143
+ std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);
144
+ std::vector<std::unique_ptr<wchar_t[], wide_char_arg_deleter>> widened_argv_entries;
145
+ widened_argv_entries.reserve(argv_size);
146
+ for (size_t ii = 0; ii < argv_size; ++ii) {
147
+ widened_argv_entries.emplace_back(widen_chars(safe_argv[ii]));
148
+ if (!widened_argv_entries.back()) {
149
+ // A null here indicates a character-encoding failure or the python
150
+ // interpreter out of memory. Give up.
151
+ return;
152
+ }
153
+ widened_argv[ii] = widened_argv_entries.back().get();
154
+ }
155
+
156
+ auto *pysys_argv = widened_argv.get();
157
+ #else
158
+ // python 2.x
159
+ std::vector<std::string> strings{safe_argv, safe_argv + argv_size};
160
+ std::vector<char *> char_strings{argv_size};
161
+ for (std::size_t i = 0; i < argv_size; ++i)
162
+ char_strings[i] = &strings[i][0];
163
+ char **pysys_argv = char_strings.data();
164
+ #endif
165
+
166
+ PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));
167
+ }
168
+
169
+ PYBIND11_NAMESPACE_END(detail)
170
+
171
+ /** \rst
172
+ Initialize the Python interpreter. No other pybind11 or CPython API functions can be
173
+ called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The
174
+ optional `init_signal_handlers` parameter can be used to skip the registration of
175
+ signal handlers (see the `Python documentation`_ for details). Calling this function
176
+ again after the interpreter has already been initialized is a fatal error.
177
+
178
+ If initializing the Python interpreter fails, then the program is terminated. (This
179
+ is controlled by the CPython runtime and is an exception to pybind11's normal behavior
180
+ of throwing exceptions on errors.)
181
+
182
+ The remaining optional parameters, `argc`, `argv`, and `add_program_dir_to_path` are
183
+ used to populate ``sys.argv`` and ``sys.path``.
184
+ See the |PySys_SetArgvEx documentation|_ for details.
185
+
186
+ .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx
187
+ .. |PySys_SetArgvEx documentation| replace:: ``PySys_SetArgvEx`` documentation
188
+ .. _PySys_SetArgvEx documentation: https://docs.python.org/3/c-api/init.html#c.PySys_SetArgvEx
189
+ \endrst */
190
+ inline void initialize_interpreter(bool init_signal_handlers = true,
191
+ int argc = 0,
192
+ const char *const *argv = nullptr,
193
+ bool add_program_dir_to_path = true) {
194
+ if (Py_IsInitialized() != 0) {
195
+ pybind11_fail("The interpreter is already running");
196
+ }
197
+
198
+ Py_InitializeEx(init_signal_handlers ? 1 : 0);
199
+
200
+ detail::set_interpreter_argv(argc, argv, add_program_dir_to_path);
201
+ }
202
+
203
+ /** \rst
204
+ Shut down the Python interpreter. No pybind11 or CPython API functions can be called
205
+ after this. In addition, pybind11 objects must not outlive the interpreter:
206
+
207
+ .. code-block:: cpp
208
+
209
+ { // BAD
210
+ py::initialize_interpreter();
211
+ auto hello = py::str("Hello, World!");
212
+ py::finalize_interpreter();
213
+ } // <-- BOOM, hello's destructor is called after interpreter shutdown
214
+
215
+ { // GOOD
216
+ py::initialize_interpreter();
217
+ { // scoped
218
+ auto hello = py::str("Hello, World!");
219
+ } // <-- OK, hello is cleaned up properly
220
+ py::finalize_interpreter();
221
+ }
222
+
223
+ { // BETTER
224
+ py::scoped_interpreter guard{};
225
+ auto hello = py::str("Hello, World!");
226
+ }
227
+
228
+ .. warning::
229
+
230
+ The interpreter can be restarted by calling `initialize_interpreter` again.
231
+ Modules created using pybind11 can be safely re-initialized. However, Python
232
+ itself cannot completely unload binary extension modules and there are several
233
+ caveats with regard to interpreter restarting. All the details can be found
234
+ in the CPython documentation. In short, not all interpreter memory may be
235
+ freed, either due to reference cycles or user-created global data.
236
+
237
+ \endrst */
238
+ inline void finalize_interpreter() {
239
+ handle builtins(PyEval_GetBuiltins());
240
+ const char *id = PYBIND11_INTERNALS_ID;
241
+
242
+ // Get the internals pointer (without creating it if it doesn't exist). It's possible for the
243
+ // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()`
244
+ // during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
245
+ detail::internals **internals_ptr_ptr = detail::get_internals_pp();
246
+ // It could also be stashed in builtins, so look there too:
247
+ if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
248
+ internals_ptr_ptr = capsule(builtins[id]);
249
+ }
250
+ // Local internals contains data managed by the current interpreter, so we must clear them to
251
+ // avoid undefined behaviors when initializing another interpreter
252
+ detail::get_local_internals().registered_types_cpp.clear();
253
+ detail::get_local_internals().registered_exception_translators.clear();
254
+
255
+ Py_Finalize();
256
+
257
+ if (internals_ptr_ptr) {
258
+ delete *internals_ptr_ptr;
259
+ *internals_ptr_ptr = nullptr;
260
+ }
261
+ }
262
+
263
+ /** \rst
264
+ Scope guard version of `initialize_interpreter` and `finalize_interpreter`.
265
+ This a move-only guard and only a single instance can exist.
266
+
267
+ See `initialize_interpreter` for a discussion of its constructor arguments.
268
+
269
+ .. code-block:: cpp
270
+
271
+ #include <pybind11/embed.h>
272
+
273
+ int main() {
274
+ py::scoped_interpreter guard{};
275
+ py::print(Hello, World!);
276
+ } // <-- interpreter shutdown
277
+ \endrst */
278
+ class scoped_interpreter {
279
+ public:
280
+ explicit scoped_interpreter(bool init_signal_handlers = true,
281
+ int argc = 0,
282
+ const char *const *argv = nullptr,
283
+ bool add_program_dir_to_path = true) {
284
+ initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);
285
+ }
286
+
287
+ scoped_interpreter(const scoped_interpreter &) = delete;
288
+ scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
289
+ scoped_interpreter &operator=(const scoped_interpreter &) = delete;
290
+ scoped_interpreter &operator=(scoped_interpreter &&) = delete;
291
+
292
+ ~scoped_interpreter() {
293
+ if (is_valid) {
294
+ finalize_interpreter();
295
+ }
296
+ }
297
+
298
+ private:
299
+ bool is_valid = true;
300
+ };
301
+
302
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/eval.h ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/eval.h: Support for evaluating Python expressions and statements
3
+ from strings and files
4
+
5
+ Copyright (c) 2016 Klemens Morgenstern <[email protected]> and
6
+ Wenzel Jakob <[email protected]>
7
+
8
+ All rights reserved. Use of this source code is governed by a
9
+ BSD-style license that can be found in the LICENSE file.
10
+ */
11
+
12
+ #pragma once
13
+
14
+ #include "pybind11.h"
15
+
16
+ #include <utility>
17
+
18
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19
+ PYBIND11_NAMESPACE_BEGIN(detail)
20
+
21
+ inline void ensure_builtins_in_globals(object &global) {
22
+ #if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x03080000
23
+ // Running exec and eval on Python 2 and 3 adds `builtins` module under
24
+ // `__builtins__` key to globals if not yet present.
25
+ // Python 3.8 made PyRun_String behave similarly. Let's also do that for
26
+ // older versions, for consistency. This was missing from PyPy3.8 7.3.7.
27
+ if (!global.contains("__builtins__"))
28
+ global["__builtins__"] = module_::import(PYBIND11_BUILTINS_MODULE);
29
+ #else
30
+ (void) global;
31
+ #endif
32
+ }
33
+
34
+ PYBIND11_NAMESPACE_END(detail)
35
+
36
+ enum eval_mode {
37
+ /// Evaluate a string containing an isolated expression
38
+ eval_expr,
39
+
40
+ /// Evaluate a string containing a single statement. Returns \c none
41
+ eval_single_statement,
42
+
43
+ /// Evaluate a string containing a sequence of statement. Returns \c none
44
+ eval_statements
45
+ };
46
+
47
+ template <eval_mode mode = eval_expr>
48
+ object eval(const str &expr, object global = globals(), object local = object()) {
49
+ if (!local) {
50
+ local = global;
51
+ }
52
+
53
+ detail::ensure_builtins_in_globals(global);
54
+
55
+ /* PyRun_String does not accept a PyObject / encoding specifier,
56
+ this seems to be the only alternative */
57
+ std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr;
58
+
59
+ int start = 0;
60
+ switch (mode) {
61
+ case eval_expr:
62
+ start = Py_eval_input;
63
+ break;
64
+ case eval_single_statement:
65
+ start = Py_single_input;
66
+ break;
67
+ case eval_statements:
68
+ start = Py_file_input;
69
+ break;
70
+ default:
71
+ pybind11_fail("invalid evaluation mode");
72
+ }
73
+
74
+ PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr());
75
+ if (!result) {
76
+ throw error_already_set();
77
+ }
78
+ return reinterpret_steal<object>(result);
79
+ }
80
+
81
+ template <eval_mode mode = eval_expr, size_t N>
82
+ object eval(const char (&s)[N], object global = globals(), object local = object()) {
83
+ /* Support raw string literals by removing common leading whitespace */
84
+ auto expr = (s[0] == '\n') ? str(module_::import("textwrap").attr("dedent")(s)) : str(s);
85
+ return eval<mode>(expr, std::move(global), std::move(local));
86
+ }
87
+
88
+ inline void exec(const str &expr, object global = globals(), object local = object()) {
89
+ eval<eval_statements>(expr, std::move(global), std::move(local));
90
+ }
91
+
92
+ template <size_t N>
93
+ void exec(const char (&s)[N], object global = globals(), object local = object()) {
94
+ eval<eval_statements>(s, std::move(global), std::move(local));
95
+ }
96
+
97
+ #if defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x03000000
98
+ template <eval_mode mode = eval_statements>
99
+ object eval_file(str, object, object) {
100
+ pybind11_fail("eval_file not supported in PyPy3. Use eval");
101
+ }
102
+ template <eval_mode mode = eval_statements>
103
+ object eval_file(str, object) {
104
+ pybind11_fail("eval_file not supported in PyPy3. Use eval");
105
+ }
106
+ template <eval_mode mode = eval_statements>
107
+ object eval_file(str) {
108
+ pybind11_fail("eval_file not supported in PyPy3. Use eval");
109
+ }
110
+ #else
111
+ template <eval_mode mode = eval_statements>
112
+ object eval_file(str fname, object global = globals(), object local = object()) {
113
+ if (!local) {
114
+ local = global;
115
+ }
116
+
117
+ detail::ensure_builtins_in_globals(global);
118
+
119
+ int start = 0;
120
+ switch (mode) {
121
+ case eval_expr:
122
+ start = Py_eval_input;
123
+ break;
124
+ case eval_single_statement:
125
+ start = Py_single_input;
126
+ break;
127
+ case eval_statements:
128
+ start = Py_file_input;
129
+ break;
130
+ default:
131
+ pybind11_fail("invalid evaluation mode");
132
+ }
133
+
134
+ int closeFile = 1;
135
+ std::string fname_str = (std::string) fname;
136
+ # if PY_VERSION_HEX >= 0x03040000
137
+ FILE *f = _Py_fopen_obj(fname.ptr(), "r");
138
+ # elif PY_VERSION_HEX >= 0x03000000
139
+ FILE *f = _Py_fopen(fname.ptr(), "r");
140
+ # else
141
+ /* No unicode support in open() :( */
142
+ auto fobj = reinterpret_steal<object>(
143
+ PyFile_FromString(const_cast<char *>(fname_str.c_str()), const_cast<char *>("r")));
144
+ FILE *f = nullptr;
145
+ if (fobj)
146
+ f = PyFile_AsFile(fobj.ptr());
147
+ closeFile = 0;
148
+ # endif
149
+ if (!f) {
150
+ PyErr_Clear();
151
+ pybind11_fail("File \"" + fname_str + "\" could not be opened!");
152
+ }
153
+
154
+ // In Python2, this should be encoded by getfilesystemencoding.
155
+ // We don't boher setting it since Python2 is past EOL anyway.
156
+ // See PR#3233
157
+ # if PY_VERSION_HEX >= 0x03000000
158
+ if (!global.contains("__file__")) {
159
+ global["__file__"] = std::move(fname);
160
+ }
161
+ # endif
162
+
163
+ # if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION)
164
+ PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(), local.ptr());
165
+ (void) closeFile;
166
+ # else
167
+ PyObject *result
168
+ = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), local.ptr(), closeFile);
169
+ # endif
170
+
171
+ if (!result) {
172
+ throw error_already_set();
173
+ }
174
+ return reinterpret_steal<object>(result);
175
+ }
176
+ #endif
177
+
178
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/functional.h ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/functional.h: std::function<> support
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+
14
+ #include <functional>
15
+
16
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
17
+ PYBIND11_NAMESPACE_BEGIN(detail)
18
+
19
+ template <typename Return, typename... Args>
20
+ struct type_caster<std::function<Return(Args...)>> {
21
+ using type = std::function<Return(Args...)>;
22
+ using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;
23
+ using function_type = Return (*)(Args...);
24
+
25
+ public:
26
+ bool load(handle src, bool convert) {
27
+ if (src.is_none()) {
28
+ // Defer accepting None to other overloads (if we aren't in convert mode):
29
+ if (!convert) {
30
+ return false;
31
+ }
32
+ return true;
33
+ }
34
+
35
+ if (!isinstance<function>(src)) {
36
+ return false;
37
+ }
38
+
39
+ auto func = reinterpret_borrow<function>(src);
40
+
41
+ /*
42
+ When passing a C++ function as an argument to another C++
43
+ function via Python, every function call would normally involve
44
+ a full C++ -> Python -> C++ roundtrip, which can be prohibitive.
45
+ Here, we try to at least detect the case where the function is
46
+ stateless (i.e. function pointer or lambda function without
47
+ captured variables), in which case the roundtrip can be avoided.
48
+ */
49
+ if (auto cfunc = func.cpp_function()) {
50
+ auto *cfunc_self = PyCFunction_GET_SELF(cfunc.ptr());
51
+ if (isinstance<capsule>(cfunc_self)) {
52
+ auto c = reinterpret_borrow<capsule>(cfunc_self);
53
+ auto *rec = (function_record *) c;
54
+
55
+ while (rec != nullptr) {
56
+ if (rec->is_stateless
57
+ && same_type(typeid(function_type),
58
+ *reinterpret_cast<const std::type_info *>(rec->data[1]))) {
59
+ struct capture {
60
+ function_type f;
61
+ };
62
+ value = ((capture *) &rec->data)->f;
63
+ return true;
64
+ }
65
+ rec = rec->next;
66
+ }
67
+ }
68
+ // PYPY segfaults here when passing builtin function like sum.
69
+ // Raising an fail exception here works to prevent the segfault, but only on gcc.
70
+ // See PR #1413 for full details
71
+ }
72
+
73
+ // ensure GIL is held during functor destruction
74
+ struct func_handle {
75
+ function f;
76
+ #if !(defined(_MSC_VER) && _MSC_VER == 1916 && defined(PYBIND11_CPP17))
77
+ // This triggers a syntax error under very special conditions (very weird indeed).
78
+ explicit
79
+ #endif
80
+ func_handle(function &&f_) noexcept
81
+ : f(std::move(f_)) {
82
+ }
83
+ func_handle(const func_handle &f_) { operator=(f_); }
84
+ func_handle &operator=(const func_handle &f_) {
85
+ gil_scoped_acquire acq;
86
+ f = f_.f;
87
+ return *this;
88
+ }
89
+ ~func_handle() {
90
+ gil_scoped_acquire acq;
91
+ function kill_f(std::move(f));
92
+ }
93
+ };
94
+
95
+ // to emulate 'move initialization capture' in C++11
96
+ struct func_wrapper {
97
+ func_handle hfunc;
98
+ explicit func_wrapper(func_handle &&hf) noexcept : hfunc(std::move(hf)) {}
99
+ Return operator()(Args... args) const {
100
+ gil_scoped_acquire acq;
101
+ object retval(hfunc.f(std::forward<Args>(args)...));
102
+ /* Visual studio 2015 parser issue: need parentheses around this expression */
103
+ return (retval.template cast<Return>());
104
+ }
105
+ };
106
+
107
+ value = func_wrapper(func_handle(std::move(func)));
108
+ return true;
109
+ }
110
+
111
+ template <typename Func>
112
+ static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) {
113
+ if (!f_) {
114
+ return none().inc_ref();
115
+ }
116
+
117
+ auto result = f_.template target<function_type>();
118
+ if (result) {
119
+ return cpp_function(*result, policy).release();
120
+ }
121
+ return cpp_function(std::forward<Func>(f_), policy).release();
122
+ }
123
+
124
+ PYBIND11_TYPE_CASTER(type,
125
+ const_name("Callable[[") + concat(make_caster<Args>::name...)
126
+ + const_name("], ") + make_caster<retval_type>::name
127
+ + const_name("]"));
128
+ };
129
+
130
+ PYBIND11_NAMESPACE_END(detail)
131
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/gil.h ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/gil.h: RAII helpers for managing the GIL
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "detail/common.h"
13
+ #include "detail/internals.h"
14
+
15
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
16
+
17
+ PYBIND11_NAMESPACE_BEGIN(detail)
18
+
19
+ // forward declarations
20
+ PyThreadState *get_thread_state_unchecked();
21
+
22
+ PYBIND11_NAMESPACE_END(detail)
23
+
24
+ #if defined(WITH_THREAD) && !defined(PYPY_VERSION)
25
+
26
+ /* The functions below essentially reproduce the PyGILState_* API using a RAII
27
+ * pattern, but there are a few important differences:
28
+ *
29
+ * 1. When acquiring the GIL from an non-main thread during the finalization
30
+ * phase, the GILState API blindly terminates the calling thread, which
31
+ * is often not what is wanted. This API does not do this.
32
+ *
33
+ * 2. The gil_scoped_release function can optionally cut the relationship
34
+ * of a PyThreadState and its associated thread, which allows moving it to
35
+ * another thread (this is a fairly rare/advanced use case).
36
+ *
37
+ * 3. The reference count of an acquired thread state can be controlled. This
38
+ * can be handy to prevent cases where callbacks issued from an external
39
+ * thread would otherwise constantly construct and destroy thread state data
40
+ * structures.
41
+ *
42
+ * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
43
+ * example which uses features 2 and 3 to migrate the Python thread of
44
+ * execution to another thread (to run the event loop on the original thread,
45
+ * in this case).
46
+ */
47
+
48
+ class gil_scoped_acquire {
49
+ public:
50
+ PYBIND11_NOINLINE gil_scoped_acquire() {
51
+ auto &internals = detail::get_internals();
52
+ tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
53
+
54
+ if (!tstate) {
55
+ /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if
56
+ calling from a Python thread). Since we use a different key, this ensures
57
+ we don't create a new thread state and deadlock in PyEval_AcquireThread
58
+ below. Note we don't save this state with internals.tstate, since we don't
59
+ create it we would fail to clear it (its reference count should be > 0). */
60
+ tstate = PyGILState_GetThisThreadState();
61
+ }
62
+
63
+ if (!tstate) {
64
+ tstate = PyThreadState_New(internals.istate);
65
+ # if !defined(NDEBUG)
66
+ if (!tstate) {
67
+ pybind11_fail("scoped_acquire: could not create thread state!");
68
+ }
69
+ # endif
70
+ tstate->gilstate_counter = 0;
71
+ PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
72
+ } else {
73
+ release = detail::get_thread_state_unchecked() != tstate;
74
+ }
75
+
76
+ if (release) {
77
+ PyEval_AcquireThread(tstate);
78
+ }
79
+
80
+ inc_ref();
81
+ }
82
+
83
+ void inc_ref() { ++tstate->gilstate_counter; }
84
+
85
+ PYBIND11_NOINLINE void dec_ref() {
86
+ --tstate->gilstate_counter;
87
+ # if !defined(NDEBUG)
88
+ if (detail::get_thread_state_unchecked() != tstate) {
89
+ pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
90
+ }
91
+ if (tstate->gilstate_counter < 0) {
92
+ pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
93
+ }
94
+ # endif
95
+ if (tstate->gilstate_counter == 0) {
96
+ # if !defined(NDEBUG)
97
+ if (!release) {
98
+ pybind11_fail("scoped_acquire::dec_ref(): internal error!");
99
+ }
100
+ # endif
101
+ PyThreadState_Clear(tstate);
102
+ if (active) {
103
+ PyThreadState_DeleteCurrent();
104
+ }
105
+ PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
106
+ release = false;
107
+ }
108
+ }
109
+
110
+ /// This method will disable the PyThreadState_DeleteCurrent call and the
111
+ /// GIL won't be acquired. This method should be used if the interpreter
112
+ /// could be shutting down when this is called, as thread deletion is not
113
+ /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
114
+ /// protect subsequent code.
115
+ PYBIND11_NOINLINE void disarm() { active = false; }
116
+
117
+ PYBIND11_NOINLINE ~gil_scoped_acquire() {
118
+ dec_ref();
119
+ if (release) {
120
+ PyEval_SaveThread();
121
+ }
122
+ }
123
+
124
+ private:
125
+ PyThreadState *tstate = nullptr;
126
+ bool release = true;
127
+ bool active = true;
128
+ };
129
+
130
+ class gil_scoped_release {
131
+ public:
132
+ explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
133
+ // `get_internals()` must be called here unconditionally in order to initialize
134
+ // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
135
+ // initialization race could occur as multiple threads try `gil_scoped_acquire`.
136
+ auto &internals = detail::get_internals();
137
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
138
+ tstate = PyEval_SaveThread();
139
+ if (disassoc) {
140
+ // Python >= 3.7 can remove this, it's an int before 3.7
141
+ // NOLINTNEXTLINE(readability-qualified-auto)
142
+ auto key = internals.tstate;
143
+ PYBIND11_TLS_DELETE_VALUE(key);
144
+ }
145
+ }
146
+
147
+ /// This method will disable the PyThreadState_DeleteCurrent call and the
148
+ /// GIL won't be acquired. This method should be used if the interpreter
149
+ /// could be shutting down when this is called, as thread deletion is not
150
+ /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
151
+ /// protect subsequent code.
152
+ PYBIND11_NOINLINE void disarm() { active = false; }
153
+
154
+ ~gil_scoped_release() {
155
+ if (!tstate) {
156
+ return;
157
+ }
158
+ // `PyEval_RestoreThread()` should not be called if runtime is finalizing
159
+ if (active) {
160
+ PyEval_RestoreThread(tstate);
161
+ }
162
+ if (disassoc) {
163
+ // Python >= 3.7 can remove this, it's an int before 3.7
164
+ // NOLINTNEXTLINE(readability-qualified-auto)
165
+ auto key = detail::get_internals().tstate;
166
+ PYBIND11_TLS_REPLACE_VALUE(key, tstate);
167
+ }
168
+ }
169
+
170
+ private:
171
+ PyThreadState *tstate;
172
+ bool disassoc;
173
+ bool active = true;
174
+ };
175
+ #elif defined(PYPY_VERSION)
176
+ class gil_scoped_acquire {
177
+ PyGILState_STATE state;
178
+
179
+ public:
180
+ gil_scoped_acquire() { state = PyGILState_Ensure(); }
181
+ ~gil_scoped_acquire() { PyGILState_Release(state); }
182
+ void disarm() {}
183
+ };
184
+
185
+ class gil_scoped_release {
186
+ PyThreadState *state;
187
+
188
+ public:
189
+ gil_scoped_release() { state = PyEval_SaveThread(); }
190
+ ~gil_scoped_release() { PyEval_RestoreThread(state); }
191
+ void disarm() {}
192
+ };
193
+ #else
194
+ class gil_scoped_acquire {
195
+ void disarm() {}
196
+ };
197
+ class gil_scoped_release {
198
+ void disarm() {}
199
+ };
200
+ #endif
201
+
202
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/iostream.h ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python
3
+
4
+ Copyright (c) 2017 Henry F. Schreiner
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+
9
+ WARNING: The implementation in this file is NOT thread safe. Multiple
10
+ threads writing to a redirected ostream concurrently cause data races
11
+ and potentially buffer overflows. Therefore it is currently a requirement
12
+ that all (possibly) concurrent redirected ostream writes are protected by
13
+ a mutex.
14
+ #HelpAppreciated: Work on iostream.h thread safety.
15
+ For more background see the discussions under
16
+ https://github.com/pybind/pybind11/pull/2982 and
17
+ https://github.com/pybind/pybind11/pull/2995.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include "pybind11.h"
23
+
24
+ #include <algorithm>
25
+ #include <cstring>
26
+ #include <iostream>
27
+ #include <iterator>
28
+ #include <memory>
29
+ #include <ostream>
30
+ #include <streambuf>
31
+ #include <string>
32
+ #include <utility>
33
+
34
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
35
+ PYBIND11_NAMESPACE_BEGIN(detail)
36
+
37
+ // Buffer that writes to Python instead of C++
38
+ class pythonbuf : public std::streambuf {
39
+ private:
40
+ using traits_type = std::streambuf::traits_type;
41
+
42
+ const size_t buf_size;
43
+ std::unique_ptr<char[]> d_buffer;
44
+ object pywrite;
45
+ object pyflush;
46
+
47
+ int overflow(int c) override {
48
+ if (!traits_type::eq_int_type(c, traits_type::eof())) {
49
+ *pptr() = traits_type::to_char_type(c);
50
+ pbump(1);
51
+ }
52
+ return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();
53
+ }
54
+
55
+ // Computes how many bytes at the end of the buffer are part of an
56
+ // incomplete sequence of UTF-8 bytes.
57
+ // Precondition: pbase() < pptr()
58
+ size_t utf8_remainder() const {
59
+ const auto rbase = std::reverse_iterator<char *>(pbase());
60
+ const auto rpptr = std::reverse_iterator<char *>(pptr());
61
+ auto is_ascii = [](char c) { return (static_cast<unsigned char>(c) & 0x80) == 0x00; };
62
+ auto is_leading = [](char c) { return (static_cast<unsigned char>(c) & 0xC0) == 0xC0; };
63
+ auto is_leading_2b = [](char c) { return static_cast<unsigned char>(c) <= 0xDF; };
64
+ auto is_leading_3b = [](char c) { return static_cast<unsigned char>(c) <= 0xEF; };
65
+ // If the last character is ASCII, there are no incomplete code points
66
+ if (is_ascii(*rpptr)) {
67
+ return 0;
68
+ }
69
+ // Otherwise, work back from the end of the buffer and find the first
70
+ // UTF-8 leading byte
71
+ const auto rpend = rbase - rpptr >= 3 ? rpptr + 3 : rbase;
72
+ const auto leading = std::find_if(rpptr, rpend, is_leading);
73
+ if (leading == rbase) {
74
+ return 0;
75
+ }
76
+ const auto dist = static_cast<size_t>(leading - rpptr);
77
+ size_t remainder = 0;
78
+
79
+ if (dist == 0) {
80
+ remainder = 1; // 1-byte code point is impossible
81
+ } else if (dist == 1) {
82
+ remainder = is_leading_2b(*leading) ? 0 : dist + 1;
83
+ } else if (dist == 2) {
84
+ remainder = is_leading_3b(*leading) ? 0 : dist + 1;
85
+ }
86
+ // else if (dist >= 3), at least 4 bytes before encountering an UTF-8
87
+ // leading byte, either no remainder or invalid UTF-8.
88
+ // Invalid UTF-8 will cause an exception later when converting
89
+ // to a Python string, so that's not handled here.
90
+ return remainder;
91
+ }
92
+
93
+ // This function must be non-virtual to be called in a destructor.
94
+ int _sync() {
95
+ if (pbase() != pptr()) { // If buffer is not empty
96
+ gil_scoped_acquire tmp;
97
+ // This subtraction cannot be negative, so dropping the sign.
98
+ auto size = static_cast<size_t>(pptr() - pbase());
99
+ size_t remainder = utf8_remainder();
100
+
101
+ if (size > remainder) {
102
+ str line(pbase(), size - remainder);
103
+ pywrite(line);
104
+ pyflush();
105
+ }
106
+
107
+ // Copy the remainder at the end of the buffer to the beginning:
108
+ if (remainder > 0) {
109
+ std::memmove(pbase(), pptr() - remainder, remainder);
110
+ }
111
+ setp(pbase(), epptr());
112
+ pbump(static_cast<int>(remainder));
113
+ }
114
+ return 0;
115
+ }
116
+
117
+ int sync() override { return _sync(); }
118
+
119
+ public:
120
+ explicit pythonbuf(const object &pyostream, size_t buffer_size = 1024)
121
+ : buf_size(buffer_size), d_buffer(new char[buf_size]), pywrite(pyostream.attr("write")),
122
+ pyflush(pyostream.attr("flush")) {
123
+ setp(d_buffer.get(), d_buffer.get() + buf_size - 1);
124
+ }
125
+
126
+ pythonbuf(pythonbuf &&) = default;
127
+
128
+ /// Sync before destroy
129
+ ~pythonbuf() override { _sync(); }
130
+ };
131
+
132
+ PYBIND11_NAMESPACE_END(detail)
133
+
134
+ /** \rst
135
+ This a move-only guard that redirects output.
136
+
137
+ .. code-block:: cpp
138
+
139
+ #include <pybind11/iostream.h>
140
+
141
+ ...
142
+
143
+ {
144
+ py::scoped_ostream_redirect output;
145
+ std::cout << "Hello, World!"; // Python stdout
146
+ } // <-- return std::cout to normal
147
+
148
+ You can explicitly pass the c++ stream and the python object,
149
+ for example to guard stderr instead.
150
+
151
+ .. code-block:: cpp
152
+
153
+ {
154
+ py::scoped_ostream_redirect output{
155
+ std::cerr, py::module::import("sys").attr("stderr")};
156
+ std::cout << "Hello, World!";
157
+ }
158
+ \endrst */
159
+ class scoped_ostream_redirect {
160
+ protected:
161
+ std::streambuf *old;
162
+ std::ostream &costream;
163
+ detail::pythonbuf buffer;
164
+
165
+ public:
166
+ explicit scoped_ostream_redirect(std::ostream &costream = std::cout,
167
+ const object &pyostream
168
+ = module_::import("sys").attr("stdout"))
169
+ : costream(costream), buffer(pyostream) {
170
+ old = costream.rdbuf(&buffer);
171
+ }
172
+
173
+ ~scoped_ostream_redirect() { costream.rdbuf(old); }
174
+
175
+ scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
176
+ scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;
177
+ scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;
178
+ scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
179
+ };
180
+
181
+ /** \rst
182
+ Like `scoped_ostream_redirect`, but redirects cerr by default. This class
183
+ is provided primary to make ``py::call_guard`` easier to make.
184
+
185
+ .. code-block:: cpp
186
+
187
+ m.def("noisy_func", &noisy_func,
188
+ py::call_guard<scoped_ostream_redirect,
189
+ scoped_estream_redirect>());
190
+
191
+ \endrst */
192
+ class scoped_estream_redirect : public scoped_ostream_redirect {
193
+ public:
194
+ explicit scoped_estream_redirect(std::ostream &costream = std::cerr,
195
+ const object &pyostream
196
+ = module_::import("sys").attr("stderr"))
197
+ : scoped_ostream_redirect(costream, pyostream) {}
198
+ };
199
+
200
+ PYBIND11_NAMESPACE_BEGIN(detail)
201
+
202
+ // Class to redirect output as a context manager. C++ backend.
203
+ class OstreamRedirect {
204
+ bool do_stdout_;
205
+ bool do_stderr_;
206
+ std::unique_ptr<scoped_ostream_redirect> redirect_stdout;
207
+ std::unique_ptr<scoped_estream_redirect> redirect_stderr;
208
+
209
+ public:
210
+ explicit OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
211
+ : do_stdout_(do_stdout), do_stderr_(do_stderr) {}
212
+
213
+ void enter() {
214
+ if (do_stdout_) {
215
+ redirect_stdout.reset(new scoped_ostream_redirect());
216
+ }
217
+ if (do_stderr_) {
218
+ redirect_stderr.reset(new scoped_estream_redirect());
219
+ }
220
+ }
221
+
222
+ void exit() {
223
+ redirect_stdout.reset();
224
+ redirect_stderr.reset();
225
+ }
226
+ };
227
+
228
+ PYBIND11_NAMESPACE_END(detail)
229
+
230
+ /** \rst
231
+ This is a helper function to add a C++ redirect context manager to Python
232
+ instead of using a C++ guard. To use it, add the following to your binding code:
233
+
234
+ .. code-block:: cpp
235
+
236
+ #include <pybind11/iostream.h>
237
+
238
+ ...
239
+
240
+ py::add_ostream_redirect(m, "ostream_redirect");
241
+
242
+ You now have a Python context manager that redirects your output:
243
+
244
+ .. code-block:: python
245
+
246
+ with m.ostream_redirect():
247
+ m.print_to_cout_function()
248
+
249
+ This manager can optionally be told which streams to operate on:
250
+
251
+ .. code-block:: python
252
+
253
+ with m.ostream_redirect(stdout=true, stderr=true):
254
+ m.noisy_function_with_error_printing()
255
+
256
+ \endrst */
257
+ inline class_<detail::OstreamRedirect>
258
+ add_ostream_redirect(module_ m, const std::string &name = "ostream_redirect") {
259
+ return class_<detail::OstreamRedirect>(std::move(m), name.c_str(), module_local())
260
+ .def(init<bool, bool>(), arg("stdout") = true, arg("stderr") = true)
261
+ .def("__enter__", &detail::OstreamRedirect::enter)
262
+ .def("__exit__", [](detail::OstreamRedirect &self_, const args &) { self_.exit(); });
263
+ }
264
+
265
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/numpy.h ADDED
@@ -0,0 +1,1958 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/numpy.h: Basic NumPy support, vectorize() wrapper
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+ #include "complex.h"
14
+
15
+ #include <algorithm>
16
+ #include <array>
17
+ #include <cstdint>
18
+ #include <cstdlib>
19
+ #include <cstring>
20
+ #include <functional>
21
+ #include <numeric>
22
+ #include <sstream>
23
+ #include <string>
24
+ #include <type_traits>
25
+ #include <typeindex>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ /* This will be true on all flat address space platforms and allows us to reduce the
30
+ whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size
31
+ and dimension types (e.g. shape, strides, indexing), instead of inflicting this
32
+ upon the library user. */
33
+ static_assert(sizeof(::pybind11::ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t");
34
+ static_assert(std::is_signed<Py_intptr_t>::value, "Py_intptr_t must be signed");
35
+ // We now can reinterpret_cast between py::ssize_t and Py_intptr_t (MSVC + PyPy cares)
36
+
37
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
38
+
39
+ class array; // Forward declaration
40
+
41
+ PYBIND11_NAMESPACE_BEGIN(detail)
42
+
43
+ template <>
44
+ struct handle_type_name<array> {
45
+ static constexpr auto name = const_name("numpy.ndarray");
46
+ };
47
+
48
+ template <typename type, typename SFINAE = void>
49
+ struct npy_format_descriptor;
50
+
51
+ struct PyArrayDescr_Proxy {
52
+ PyObject_HEAD
53
+ PyObject *typeobj;
54
+ char kind;
55
+ char type;
56
+ char byteorder;
57
+ char flags;
58
+ int type_num;
59
+ int elsize;
60
+ int alignment;
61
+ char *subarray;
62
+ PyObject *fields;
63
+ PyObject *names;
64
+ };
65
+
66
+ struct PyArray_Proxy {
67
+ PyObject_HEAD
68
+ char *data;
69
+ int nd;
70
+ ssize_t *dimensions;
71
+ ssize_t *strides;
72
+ PyObject *base;
73
+ PyObject *descr;
74
+ int flags;
75
+ };
76
+
77
+ struct PyVoidScalarObject_Proxy {
78
+ PyObject_VAR_HEAD char *obval;
79
+ PyArrayDescr_Proxy *descr;
80
+ int flags;
81
+ PyObject *base;
82
+ };
83
+
84
+ struct numpy_type_info {
85
+ PyObject *dtype_ptr;
86
+ std::string format_str;
87
+ };
88
+
89
+ struct numpy_internals {
90
+ std::unordered_map<std::type_index, numpy_type_info> registered_dtypes;
91
+
92
+ numpy_type_info *get_type_info(const std::type_info &tinfo, bool throw_if_missing = true) {
93
+ auto it = registered_dtypes.find(std::type_index(tinfo));
94
+ if (it != registered_dtypes.end()) {
95
+ return &(it->second);
96
+ }
97
+ if (throw_if_missing) {
98
+ pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name());
99
+ }
100
+ return nullptr;
101
+ }
102
+
103
+ template <typename T>
104
+ numpy_type_info *get_type_info(bool throw_if_missing = true) {
105
+ return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing);
106
+ }
107
+ };
108
+
109
+ PYBIND11_NOINLINE void load_numpy_internals(numpy_internals *&ptr) {
110
+ ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals");
111
+ }
112
+
113
+ inline numpy_internals &get_numpy_internals() {
114
+ static numpy_internals *ptr = nullptr;
115
+ if (!ptr) {
116
+ load_numpy_internals(ptr);
117
+ }
118
+ return *ptr;
119
+ }
120
+
121
+ template <typename T>
122
+ struct same_size {
123
+ template <typename U>
124
+ using as = bool_constant<sizeof(T) == sizeof(U)>;
125
+ };
126
+
127
+ template <typename Concrete>
128
+ constexpr int platform_lookup() {
129
+ return -1;
130
+ }
131
+
132
+ // Lookup a type according to its size, and return a value corresponding to the NumPy typenum.
133
+ template <typename Concrete, typename T, typename... Ts, typename... Ints>
134
+ constexpr int platform_lookup(int I, Ints... Is) {
135
+ return sizeof(Concrete) == sizeof(T) ? I : platform_lookup<Concrete, Ts...>(Is...);
136
+ }
137
+
138
+ struct npy_api {
139
+ enum constants {
140
+ NPY_ARRAY_C_CONTIGUOUS_ = 0x0001,
141
+ NPY_ARRAY_F_CONTIGUOUS_ = 0x0002,
142
+ NPY_ARRAY_OWNDATA_ = 0x0004,
143
+ NPY_ARRAY_FORCECAST_ = 0x0010,
144
+ NPY_ARRAY_ENSUREARRAY_ = 0x0040,
145
+ NPY_ARRAY_ALIGNED_ = 0x0100,
146
+ NPY_ARRAY_WRITEABLE_ = 0x0400,
147
+ NPY_BOOL_ = 0,
148
+ NPY_BYTE_,
149
+ NPY_UBYTE_,
150
+ NPY_SHORT_,
151
+ NPY_USHORT_,
152
+ NPY_INT_,
153
+ NPY_UINT_,
154
+ NPY_LONG_,
155
+ NPY_ULONG_,
156
+ NPY_LONGLONG_,
157
+ NPY_ULONGLONG_,
158
+ NPY_FLOAT_,
159
+ NPY_DOUBLE_,
160
+ NPY_LONGDOUBLE_,
161
+ NPY_CFLOAT_,
162
+ NPY_CDOUBLE_,
163
+ NPY_CLONGDOUBLE_,
164
+ NPY_OBJECT_ = 17,
165
+ NPY_STRING_,
166
+ NPY_UNICODE_,
167
+ NPY_VOID_,
168
+ // Platform-dependent normalization
169
+ NPY_INT8_ = NPY_BYTE_,
170
+ NPY_UINT8_ = NPY_UBYTE_,
171
+ NPY_INT16_ = NPY_SHORT_,
172
+ NPY_UINT16_ = NPY_USHORT_,
173
+ // `npy_common.h` defines the integer aliases. In order, it checks:
174
+ // NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR
175
+ // and assigns the alias to the first matching size, so we should check in this order.
176
+ NPY_INT32_
177
+ = platform_lookup<std::int32_t, long, int, short>(NPY_LONG_, NPY_INT_, NPY_SHORT_),
178
+ NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>(
179
+ NPY_ULONG_, NPY_UINT_, NPY_USHORT_),
180
+ NPY_INT64_
181
+ = platform_lookup<std::int64_t, long, long long, int>(NPY_LONG_, NPY_LONGLONG_, NPY_INT_),
182
+ NPY_UINT64_
183
+ = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>(
184
+ NPY_ULONG_, NPY_ULONGLONG_, NPY_UINT_),
185
+ };
186
+
187
+ struct PyArray_Dims {
188
+ Py_intptr_t *ptr;
189
+ int len;
190
+ };
191
+
192
+ static npy_api &get() {
193
+ static npy_api api = lookup();
194
+ return api;
195
+ }
196
+
197
+ bool PyArray_Check_(PyObject *obj) const {
198
+ return PyObject_TypeCheck(obj, PyArray_Type_) != 0;
199
+ }
200
+ bool PyArrayDescr_Check_(PyObject *obj) const {
201
+ return PyObject_TypeCheck(obj, PyArrayDescr_Type_) != 0;
202
+ }
203
+
204
+ unsigned int (*PyArray_GetNDArrayCFeatureVersion_)();
205
+ PyObject *(*PyArray_DescrFromType_)(int);
206
+ PyObject *(*PyArray_NewFromDescr_)(PyTypeObject *,
207
+ PyObject *,
208
+ int,
209
+ Py_intptr_t const *,
210
+ Py_intptr_t const *,
211
+ void *,
212
+ int,
213
+ PyObject *);
214
+ // Unused. Not removed because that affects ABI of the class.
215
+ PyObject *(*PyArray_DescrNewFromType_)(int);
216
+ int (*PyArray_CopyInto_)(PyObject *, PyObject *);
217
+ PyObject *(*PyArray_NewCopy_)(PyObject *, int);
218
+ PyTypeObject *PyArray_Type_;
219
+ PyTypeObject *PyVoidArrType_Type_;
220
+ PyTypeObject *PyArrayDescr_Type_;
221
+ PyObject *(*PyArray_DescrFromScalar_)(PyObject *);
222
+ PyObject *(*PyArray_FromAny_)(PyObject *, PyObject *, int, int, int, PyObject *);
223
+ int (*PyArray_DescrConverter_)(PyObject *, PyObject **);
224
+ bool (*PyArray_EquivTypes_)(PyObject *, PyObject *);
225
+ int (*PyArray_GetArrayParamsFromObject_)(PyObject *,
226
+ PyObject *,
227
+ unsigned char,
228
+ PyObject **,
229
+ int *,
230
+ Py_intptr_t *,
231
+ PyObject **,
232
+ PyObject *);
233
+ PyObject *(*PyArray_Squeeze_)(PyObject *);
234
+ // Unused. Not removed because that affects ABI of the class.
235
+ int (*PyArray_SetBaseObject_)(PyObject *, PyObject *);
236
+ PyObject *(*PyArray_Resize_)(PyObject *, PyArray_Dims *, int, int);
237
+ PyObject *(*PyArray_Newshape_)(PyObject *, PyArray_Dims *, int);
238
+ PyObject *(*PyArray_View_)(PyObject *, PyObject *, PyObject *);
239
+
240
+ private:
241
+ enum functions {
242
+ API_PyArray_GetNDArrayCFeatureVersion = 211,
243
+ API_PyArray_Type = 2,
244
+ API_PyArrayDescr_Type = 3,
245
+ API_PyVoidArrType_Type = 39,
246
+ API_PyArray_DescrFromType = 45,
247
+ API_PyArray_DescrFromScalar = 57,
248
+ API_PyArray_FromAny = 69,
249
+ API_PyArray_Resize = 80,
250
+ API_PyArray_CopyInto = 82,
251
+ API_PyArray_NewCopy = 85,
252
+ API_PyArray_NewFromDescr = 94,
253
+ API_PyArray_DescrNewFromType = 96,
254
+ API_PyArray_Newshape = 135,
255
+ API_PyArray_Squeeze = 136,
256
+ API_PyArray_View = 137,
257
+ API_PyArray_DescrConverter = 174,
258
+ API_PyArray_EquivTypes = 182,
259
+ API_PyArray_GetArrayParamsFromObject = 278,
260
+ API_PyArray_SetBaseObject = 282
261
+ };
262
+
263
+ static npy_api lookup() {
264
+ module_ m = module_::import("numpy.core.multiarray");
265
+ auto c = m.attr("_ARRAY_API");
266
+ #if PY_MAJOR_VERSION >= 3
267
+ void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), NULL);
268
+ #else
269
+ void **api_ptr = (void **) PyCObject_AsVoidPtr(c.ptr());
270
+ #endif
271
+ npy_api api;
272
+ #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
273
+ DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion);
274
+ if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7) {
275
+ pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0");
276
+ }
277
+ DECL_NPY_API(PyArray_Type);
278
+ DECL_NPY_API(PyVoidArrType_Type);
279
+ DECL_NPY_API(PyArrayDescr_Type);
280
+ DECL_NPY_API(PyArray_DescrFromType);
281
+ DECL_NPY_API(PyArray_DescrFromScalar);
282
+ DECL_NPY_API(PyArray_FromAny);
283
+ DECL_NPY_API(PyArray_Resize);
284
+ DECL_NPY_API(PyArray_CopyInto);
285
+ DECL_NPY_API(PyArray_NewCopy);
286
+ DECL_NPY_API(PyArray_NewFromDescr);
287
+ DECL_NPY_API(PyArray_DescrNewFromType);
288
+ DECL_NPY_API(PyArray_Newshape);
289
+ DECL_NPY_API(PyArray_Squeeze);
290
+ DECL_NPY_API(PyArray_View);
291
+ DECL_NPY_API(PyArray_DescrConverter);
292
+ DECL_NPY_API(PyArray_EquivTypes);
293
+ DECL_NPY_API(PyArray_GetArrayParamsFromObject);
294
+ DECL_NPY_API(PyArray_SetBaseObject);
295
+
296
+ #undef DECL_NPY_API
297
+ return api;
298
+ }
299
+ };
300
+
301
+ inline PyArray_Proxy *array_proxy(void *ptr) { return reinterpret_cast<PyArray_Proxy *>(ptr); }
302
+
303
+ inline const PyArray_Proxy *array_proxy(const void *ptr) {
304
+ return reinterpret_cast<const PyArray_Proxy *>(ptr);
305
+ }
306
+
307
+ inline PyArrayDescr_Proxy *array_descriptor_proxy(PyObject *ptr) {
308
+ return reinterpret_cast<PyArrayDescr_Proxy *>(ptr);
309
+ }
310
+
311
+ inline const PyArrayDescr_Proxy *array_descriptor_proxy(const PyObject *ptr) {
312
+ return reinterpret_cast<const PyArrayDescr_Proxy *>(ptr);
313
+ }
314
+
315
+ inline bool check_flags(const void *ptr, int flag) {
316
+ return (flag == (array_proxy(ptr)->flags & flag));
317
+ }
318
+
319
+ template <typename T>
320
+ struct is_std_array : std::false_type {};
321
+ template <typename T, size_t N>
322
+ struct is_std_array<std::array<T, N>> : std::true_type {};
323
+ template <typename T>
324
+ struct is_complex : std::false_type {};
325
+ template <typename T>
326
+ struct is_complex<std::complex<T>> : std::true_type {};
327
+
328
+ template <typename T>
329
+ struct array_info_scalar {
330
+ using type = T;
331
+ static constexpr bool is_array = false;
332
+ static constexpr bool is_empty = false;
333
+ static constexpr auto extents = const_name("");
334
+ static void append_extents(list & /* shape */) {}
335
+ };
336
+ // Computes underlying type and a comma-separated list of extents for array
337
+ // types (any mix of std::array and built-in arrays). An array of char is
338
+ // treated as scalar because it gets special handling.
339
+ template <typename T>
340
+ struct array_info : array_info_scalar<T> {};
341
+ template <typename T, size_t N>
342
+ struct array_info<std::array<T, N>> {
343
+ using type = typename array_info<T>::type;
344
+ static constexpr bool is_array = true;
345
+ static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty;
346
+ static constexpr size_t extent = N;
347
+
348
+ // appends the extents to shape
349
+ static void append_extents(list &shape) {
350
+ shape.append(N);
351
+ array_info<T>::append_extents(shape);
352
+ }
353
+
354
+ static constexpr auto extents = const_name<array_info<T>::is_array>(
355
+ concat(const_name<N>(), array_info<T>::extents), const_name<N>());
356
+ };
357
+ // For numpy we have special handling for arrays of characters, so we don't include
358
+ // the size in the array extents.
359
+ template <size_t N>
360
+ struct array_info<char[N]> : array_info_scalar<char[N]> {};
361
+ template <size_t N>
362
+ struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> {};
363
+ template <typename T, size_t N>
364
+ struct array_info<T[N]> : array_info<std::array<T, N>> {};
365
+ template <typename T>
366
+ using remove_all_extents_t = typename array_info<T>::type;
367
+
368
+ template <typename T>
369
+ using is_pod_struct
370
+ = all_of<std::is_standard_layout<T>, // since we're accessing directly in memory
371
+ // we need a standard layout type
372
+ #if defined(__GLIBCXX__) \
373
+ && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150426 || __GLIBCXX__ == 20150623 \
374
+ || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)
375
+ // libstdc++ < 5 (including versions 4.8.5, 4.9.3 and 4.9.4 which were released after
376
+ // 5) don't implement is_trivially_copyable, so approximate it
377
+ std::is_trivially_destructible<T>,
378
+ satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>,
379
+ #else
380
+ std::is_trivially_copyable<T>,
381
+ #endif
382
+ satisfies_none_of<T,
383
+ std::is_reference,
384
+ std::is_array,
385
+ is_std_array,
386
+ std::is_arithmetic,
387
+ is_complex,
388
+ std::is_enum>>;
389
+
390
+ // Replacement for std::is_pod (deprecated in C++20)
391
+ template <typename T>
392
+ using is_pod = all_of<std::is_standard_layout<T>, std::is_trivial<T>>;
393
+
394
+ template <ssize_t Dim = 0, typename Strides>
395
+ ssize_t byte_offset_unsafe(const Strides &) {
396
+ return 0;
397
+ }
398
+ template <ssize_t Dim = 0, typename Strides, typename... Ix>
399
+ ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) {
400
+ return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...);
401
+ }
402
+
403
+ /**
404
+ * Proxy class providing unsafe, unchecked const access to array data. This is constructed through
405
+ * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`. `Dims`
406
+ * will be -1 for dimensions determined at runtime.
407
+ */
408
+ template <typename T, ssize_t Dims>
409
+ class unchecked_reference {
410
+ protected:
411
+ static constexpr bool Dynamic = Dims < 0;
412
+ const unsigned char *data_;
413
+ // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to
414
+ // make large performance gains on big, nested loops, but requires compile-time dimensions
415
+ conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>> shape_, strides_;
416
+ const ssize_t dims_;
417
+
418
+ friend class pybind11::array;
419
+ // Constructor for compile-time dimensions:
420
+ template <bool Dyn = Dynamic>
421
+ unchecked_reference(const void *data,
422
+ const ssize_t *shape,
423
+ const ssize_t *strides,
424
+ enable_if_t<!Dyn, ssize_t>)
425
+ : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
426
+ for (size_t i = 0; i < (size_t) dims_; i++) {
427
+ shape_[i] = shape[i];
428
+ strides_[i] = strides[i];
429
+ }
430
+ }
431
+ // Constructor for runtime dimensions:
432
+ template <bool Dyn = Dynamic>
433
+ unchecked_reference(const void *data,
434
+ const ssize_t *shape,
435
+ const ssize_t *strides,
436
+ enable_if_t<Dyn, ssize_t> dims)
437
+ : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides},
438
+ dims_{dims} {}
439
+
440
+ public:
441
+ /**
442
+ * Unchecked const reference access to data at the given indices. For a compile-time known
443
+ * number of dimensions, this requires the correct number of arguments; for run-time
444
+ * dimensionality, this is not checked (and so is up to the caller to use safely).
445
+ */
446
+ template <typename... Ix>
447
+ const T &operator()(Ix... index) const {
448
+ static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
449
+ "Invalid number of indices for unchecked array reference");
450
+ return *reinterpret_cast<const T *>(data_
451
+ + byte_offset_unsafe(strides_, ssize_t(index)...));
452
+ }
453
+ /**
454
+ * Unchecked const reference access to data; this operator only participates if the reference
455
+ * is to a 1-dimensional array. When present, this is exactly equivalent to `obj(index)`.
456
+ */
457
+ template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
458
+ const T &operator[](ssize_t index) const {
459
+ return operator()(index);
460
+ }
461
+
462
+ /// Pointer access to the data at the given indices.
463
+ template <typename... Ix>
464
+ const T *data(Ix... ix) const {
465
+ return &operator()(ssize_t(ix)...);
466
+ }
467
+
468
+ /// Returns the item size, i.e. sizeof(T)
469
+ constexpr static ssize_t itemsize() { return sizeof(T); }
470
+
471
+ /// Returns the shape (i.e. size) of dimension `dim`
472
+ ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; }
473
+
474
+ /// Returns the number of dimensions of the array
475
+ ssize_t ndim() const { return dims_; }
476
+
477
+ /// Returns the total number of elements in the referenced array, i.e. the product of the
478
+ /// shapes
479
+ template <bool Dyn = Dynamic>
480
+ enable_if_t<!Dyn, ssize_t> size() const {
481
+ return std::accumulate(
482
+ shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());
483
+ }
484
+ template <bool Dyn = Dynamic>
485
+ enable_if_t<Dyn, ssize_t> size() const {
486
+ return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
487
+ }
488
+
489
+ /// Returns the total number of bytes used by the referenced data. Note that the actual span
490
+ /// in memory may be larger if the referenced array has non-contiguous strides (e.g. for a
491
+ /// slice).
492
+ ssize_t nbytes() const { return size() * itemsize(); }
493
+ };
494
+
495
+ template <typename T, ssize_t Dims>
496
+ class unchecked_mutable_reference : public unchecked_reference<T, Dims> {
497
+ friend class pybind11::array;
498
+ using ConstBase = unchecked_reference<T, Dims>;
499
+ using ConstBase::ConstBase;
500
+ using ConstBase::Dynamic;
501
+
502
+ public:
503
+ // Bring in const-qualified versions from base class
504
+ using ConstBase::operator();
505
+ using ConstBase::operator[];
506
+
507
+ /// Mutable, unchecked access to data at the given indices.
508
+ template <typename... Ix>
509
+ T &operator()(Ix... index) {
510
+ static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
511
+ "Invalid number of indices for unchecked array reference");
512
+ return const_cast<T &>(ConstBase::operator()(index...));
513
+ }
514
+ /**
515
+ * Mutable, unchecked access data at the given index; this operator only participates if the
516
+ * reference is to a 1-dimensional array (or has runtime dimensions). When present, this is
517
+ * exactly equivalent to `obj(index)`.
518
+ */
519
+ template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
520
+ T &operator[](ssize_t index) {
521
+ return operator()(index);
522
+ }
523
+
524
+ /// Mutable pointer access to the data at the given indices.
525
+ template <typename... Ix>
526
+ T *mutable_data(Ix... ix) {
527
+ return &operator()(ssize_t(ix)...);
528
+ }
529
+ };
530
+
531
+ template <typename T, ssize_t Dim>
532
+ struct type_caster<unchecked_reference<T, Dim>> {
533
+ static_assert(Dim == 0 && Dim > 0 /* always fail */,
534
+ "unchecked array proxy object is not castable");
535
+ };
536
+ template <typename T, ssize_t Dim>
537
+ struct type_caster<unchecked_mutable_reference<T, Dim>>
538
+ : type_caster<unchecked_reference<T, Dim>> {};
539
+
540
+ PYBIND11_NAMESPACE_END(detail)
541
+
542
+ class dtype : public object {
543
+ public:
544
+ PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_);
545
+
546
+ explicit dtype(const buffer_info &info) {
547
+ dtype descr(_dtype_from_pep3118()(PYBIND11_STR_TYPE(info.format)));
548
+ // If info.itemsize == 0, use the value calculated from the format string
549
+ m_ptr = descr.strip_padding(info.itemsize != 0 ? info.itemsize : descr.itemsize())
550
+ .release()
551
+ .ptr();
552
+ }
553
+
554
+ explicit dtype(const std::string &format) {
555
+ m_ptr = from_args(pybind11::str(format)).release().ptr();
556
+ }
557
+
558
+ explicit dtype(const char *format) : dtype(std::string(format)) {}
559
+
560
+ dtype(list names, list formats, list offsets, ssize_t itemsize) {
561
+ dict args;
562
+ args["names"] = std::move(names);
563
+ args["formats"] = std::move(formats);
564
+ args["offsets"] = std::move(offsets);
565
+ args["itemsize"] = pybind11::int_(itemsize);
566
+ m_ptr = from_args(std::move(args)).release().ptr();
567
+ }
568
+
569
+ /// This is essentially the same as calling numpy.dtype(args) in Python.
570
+ static dtype from_args(object args) {
571
+ PyObject *ptr = nullptr;
572
+ if ((detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) == 0) || !ptr) {
573
+ throw error_already_set();
574
+ }
575
+ return reinterpret_steal<dtype>(ptr);
576
+ }
577
+
578
+ /// Return dtype associated with a C++ type.
579
+ template <typename T>
580
+ static dtype of() {
581
+ return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype();
582
+ }
583
+
584
+ /// Size of the data type in bytes.
585
+ ssize_t itemsize() const { return detail::array_descriptor_proxy(m_ptr)->elsize; }
586
+
587
+ /// Returns true for structured data types.
588
+ bool has_fields() const { return detail::array_descriptor_proxy(m_ptr)->names != nullptr; }
589
+
590
+ /// Single-character code for dtype's kind.
591
+ /// For example, floating point types are 'f' and integral types are 'i'.
592
+ char kind() const { return detail::array_descriptor_proxy(m_ptr)->kind; }
593
+
594
+ /// Single-character for dtype's type.
595
+ /// For example, ``float`` is 'f', ``double`` 'd', ``int`` 'i', and ``long`` 'l'.
596
+ char char_() const {
597
+ // Note: The signature, `dtype::char_` follows the naming of NumPy's
598
+ // public Python API (i.e., ``dtype.char``), rather than its internal
599
+ // C API (``PyArray_Descr::type``).
600
+ return detail::array_descriptor_proxy(m_ptr)->type;
601
+ }
602
+
603
+ private:
604
+ static object _dtype_from_pep3118() {
605
+ static PyObject *obj = module_::import("numpy.core._internal")
606
+ .attr("_dtype_from_pep3118")
607
+ .cast<object>()
608
+ .release()
609
+ .ptr();
610
+ return reinterpret_borrow<object>(obj);
611
+ }
612
+
613
+ dtype strip_padding(ssize_t itemsize) {
614
+ // Recursively strip all void fields with empty names that are generated for
615
+ // padding fields (as of NumPy v1.11).
616
+ if (!has_fields()) {
617
+ return *this;
618
+ }
619
+
620
+ struct field_descr {
621
+ PYBIND11_STR_TYPE name;
622
+ object format;
623
+ pybind11::int_ offset;
624
+ };
625
+ std::vector<field_descr> field_descriptors;
626
+
627
+ for (auto field : attr("fields").attr("items")()) {
628
+ auto spec = field.cast<tuple>();
629
+ auto name = spec[0].cast<pybind11::str>();
630
+ auto format = spec[1].cast<tuple>()[0].cast<dtype>();
631
+ auto offset = spec[1].cast<tuple>()[1].cast<pybind11::int_>();
632
+ if ((len(name) == 0u) && format.kind() == 'V') {
633
+ continue;
634
+ }
635
+ field_descriptors.push_back(
636
+ {(PYBIND11_STR_TYPE) name, format.strip_padding(format.itemsize()), offset});
637
+ }
638
+
639
+ std::sort(field_descriptors.begin(),
640
+ field_descriptors.end(),
641
+ [](const field_descr &a, const field_descr &b) {
642
+ return a.offset.cast<int>() < b.offset.cast<int>();
643
+ });
644
+
645
+ list names, formats, offsets;
646
+ for (auto &descr : field_descriptors) {
647
+ names.append(descr.name);
648
+ formats.append(descr.format);
649
+ offsets.append(descr.offset);
650
+ }
651
+ return dtype(std::move(names), std::move(formats), std::move(offsets), itemsize);
652
+ }
653
+ };
654
+
655
+ class array : public buffer {
656
+ public:
657
+ PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array)
658
+
659
+ enum {
660
+ c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_,
661
+ f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_,
662
+ forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_
663
+ };
664
+
665
+ array() : array(0, static_cast<const double *>(nullptr)) {}
666
+
667
+ using ShapeContainer = detail::any_container<ssize_t>;
668
+ using StridesContainer = detail::any_container<ssize_t>;
669
+
670
+ // Constructs an array taking shape/strides from arbitrary container types
671
+ array(const pybind11::dtype &dt,
672
+ ShapeContainer shape,
673
+ StridesContainer strides,
674
+ const void *ptr = nullptr,
675
+ handle base = handle()) {
676
+
677
+ if (strides->empty()) {
678
+ *strides = detail::c_strides(*shape, dt.itemsize());
679
+ }
680
+
681
+ auto ndim = shape->size();
682
+ if (ndim != strides->size()) {
683
+ pybind11_fail("NumPy: shape ndim doesn't match strides ndim");
684
+ }
685
+ auto descr = dt;
686
+
687
+ int flags = 0;
688
+ if (base && ptr) {
689
+ if (isinstance<array>(base)) {
690
+ /* Copy flags from base (except ownership bit) */
691
+ flags = reinterpret_borrow<array>(base).flags()
692
+ & ~detail::npy_api::NPY_ARRAY_OWNDATA_;
693
+ } else {
694
+ /* Writable by default, easy to downgrade later on if needed */
695
+ flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;
696
+ }
697
+ }
698
+
699
+ auto &api = detail::npy_api::get();
700
+ auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_(
701
+ api.PyArray_Type_,
702
+ descr.release().ptr(),
703
+ (int) ndim,
704
+ // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
705
+ reinterpret_cast<Py_intptr_t *>(shape->data()),
706
+ reinterpret_cast<Py_intptr_t *>(strides->data()),
707
+ const_cast<void *>(ptr),
708
+ flags,
709
+ nullptr));
710
+ if (!tmp) {
711
+ throw error_already_set();
712
+ }
713
+ if (ptr) {
714
+ if (base) {
715
+ api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr());
716
+ } else {
717
+ tmp = reinterpret_steal<object>(
718
+ api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));
719
+ }
720
+ }
721
+ m_ptr = tmp.release().ptr();
722
+ }
723
+
724
+ array(const pybind11::dtype &dt,
725
+ ShapeContainer shape,
726
+ const void *ptr = nullptr,
727
+ handle base = handle())
728
+ : array(dt, std::move(shape), {}, ptr, base) {}
729
+
730
+ template <typename T,
731
+ typename
732
+ = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>>
733
+ array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle())
734
+ : array(dt, {{count}}, ptr, base) {}
735
+
736
+ template <typename T>
737
+ array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle())
738
+ : array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) {}
739
+
740
+ template <typename T>
741
+ array(ShapeContainer shape, const T *ptr, handle base = handle())
742
+ : array(std::move(shape), {}, ptr, base) {}
743
+
744
+ template <typename T>
745
+ explicit array(ssize_t count, const T *ptr, handle base = handle())
746
+ : array({count}, {}, ptr, base) {}
747
+
748
+ explicit array(const buffer_info &info, handle base = handle())
749
+ : array(pybind11::dtype(info), info.shape, info.strides, info.ptr, base) {}
750
+
751
+ /// Array descriptor (dtype)
752
+ pybind11::dtype dtype() const {
753
+ return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr);
754
+ }
755
+
756
+ /// Total number of elements
757
+ ssize_t size() const {
758
+ return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
759
+ }
760
+
761
+ /// Byte size of a single element
762
+ ssize_t itemsize() const {
763
+ return detail::array_descriptor_proxy(detail::array_proxy(m_ptr)->descr)->elsize;
764
+ }
765
+
766
+ /// Total number of bytes
767
+ ssize_t nbytes() const { return size() * itemsize(); }
768
+
769
+ /// Number of dimensions
770
+ ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; }
771
+
772
+ /// Base object
773
+ object base() const { return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base); }
774
+
775
+ /// Dimensions of the array
776
+ const ssize_t *shape() const { return detail::array_proxy(m_ptr)->dimensions; }
777
+
778
+ /// Dimension along a given axis
779
+ ssize_t shape(ssize_t dim) const {
780
+ if (dim >= ndim()) {
781
+ fail_dim_check(dim, "invalid axis");
782
+ }
783
+ return shape()[dim];
784
+ }
785
+
786
+ /// Strides of the array
787
+ const ssize_t *strides() const { return detail::array_proxy(m_ptr)->strides; }
788
+
789
+ /// Stride along a given axis
790
+ ssize_t strides(ssize_t dim) const {
791
+ if (dim >= ndim()) {
792
+ fail_dim_check(dim, "invalid axis");
793
+ }
794
+ return strides()[dim];
795
+ }
796
+
797
+ /// Return the NumPy array flags
798
+ int flags() const { return detail::array_proxy(m_ptr)->flags; }
799
+
800
+ /// If set, the array is writeable (otherwise the buffer is read-only)
801
+ bool writeable() const {
802
+ return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_);
803
+ }
804
+
805
+ /// If set, the array owns the data (will be freed when the array is deleted)
806
+ bool owndata() const {
807
+ return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_);
808
+ }
809
+
810
+ /// Pointer to the contained data. If index is not provided, points to the
811
+ /// beginning of the buffer. May throw if the index would lead to out of bounds access.
812
+ template <typename... Ix>
813
+ const void *data(Ix... index) const {
814
+ return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
815
+ }
816
+
817
+ /// Mutable pointer to the contained data. If index is not provided, points to the
818
+ /// beginning of the buffer. May throw if the index would lead to out of bounds access.
819
+ /// May throw if the array is not writeable.
820
+ template <typename... Ix>
821
+ void *mutable_data(Ix... index) {
822
+ check_writeable();
823
+ return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
824
+ }
825
+
826
+ /// Byte offset from beginning of the array to a given index (full or partial).
827
+ /// May throw if the index would lead to out of bounds access.
828
+ template <typename... Ix>
829
+ ssize_t offset_at(Ix... index) const {
830
+ if ((ssize_t) sizeof...(index) > ndim()) {
831
+ fail_dim_check(sizeof...(index), "too many indices for an array");
832
+ }
833
+ return byte_offset(ssize_t(index)...);
834
+ }
835
+
836
+ ssize_t offset_at() const { return 0; }
837
+
838
+ /// Item count from beginning of the array to a given index (full or partial).
839
+ /// May throw if the index would lead to out of bounds access.
840
+ template <typename... Ix>
841
+ ssize_t index_at(Ix... index) const {
842
+ return offset_at(index...) / itemsize();
843
+ }
844
+
845
+ /**
846
+ * Returns a proxy object that provides access to the array's data without bounds or
847
+ * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with
848
+ * care: the array must not be destroyed or reshaped for the duration of the returned object,
849
+ * and the caller must take care not to access invalid dimensions or dimension indices.
850
+ */
851
+ template <typename T, ssize_t Dims = -1>
852
+ detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
853
+ if (PYBIND11_SILENCE_MSVC_C4127(Dims >= 0) && ndim() != Dims) {
854
+ throw std::domain_error("array has incorrect number of dimensions: "
855
+ + std::to_string(ndim()) + "; expected "
856
+ + std::to_string(Dims));
857
+ }
858
+ return detail::unchecked_mutable_reference<T, Dims>(
859
+ mutable_data(), shape(), strides(), ndim());
860
+ }
861
+
862
+ /**
863
+ * Returns a proxy object that provides const access to the array's data without bounds or
864
+ * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the
865
+ * underlying array have the `writable` flag. Use with care: the array must not be destroyed
866
+ * or reshaped for the duration of the returned object, and the caller must take care not to
867
+ * access invalid dimensions or dimension indices.
868
+ */
869
+ template <typename T, ssize_t Dims = -1>
870
+ detail::unchecked_reference<T, Dims> unchecked() const & {
871
+ if (PYBIND11_SILENCE_MSVC_C4127(Dims >= 0) && ndim() != Dims) {
872
+ throw std::domain_error("array has incorrect number of dimensions: "
873
+ + std::to_string(ndim()) + "; expected "
874
+ + std::to_string(Dims));
875
+ }
876
+ return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());
877
+ }
878
+
879
+ /// Return a new view with all of the dimensions of length 1 removed
880
+ array squeeze() {
881
+ auto &api = detail::npy_api::get();
882
+ return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));
883
+ }
884
+
885
+ /// Resize array to given shape
886
+ /// If refcheck is true and more that one reference exist to this array
887
+ /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change
888
+ void resize(ShapeContainer new_shape, bool refcheck = true) {
889
+ detail::npy_api::PyArray_Dims d
890
+ = {// Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
891
+ reinterpret_cast<Py_intptr_t *>(new_shape->data()),
892
+ int(new_shape->size())};
893
+ // try to resize, set ordering param to -1 cause it's not used anyway
894
+ auto new_array = reinterpret_steal<object>(
895
+ detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1));
896
+ if (!new_array) {
897
+ throw error_already_set();
898
+ }
899
+ if (isinstance<array>(new_array)) {
900
+ *this = std::move(new_array);
901
+ }
902
+ }
903
+
904
+ /// Optional `order` parameter omitted, to be added as needed.
905
+ array reshape(ShapeContainer new_shape) {
906
+ detail::npy_api::PyArray_Dims d
907
+ = {reinterpret_cast<Py_intptr_t *>(new_shape->data()), int(new_shape->size())};
908
+ auto new_array
909
+ = reinterpret_steal<array>(detail::npy_api::get().PyArray_Newshape_(m_ptr, &d, 0));
910
+ if (!new_array) {
911
+ throw error_already_set();
912
+ }
913
+ return new_array;
914
+ }
915
+
916
+ /// Create a view of an array in a different data type.
917
+ /// This function may fundamentally reinterpret the data in the array.
918
+ /// It is the responsibility of the caller to ensure that this is safe.
919
+ /// Only supports the `dtype` argument, the `type` argument is omitted,
920
+ /// to be added as needed.
921
+ array view(const std::string &dtype) {
922
+ auto &api = detail::npy_api::get();
923
+ auto new_view = reinterpret_steal<array>(api.PyArray_View_(
924
+ m_ptr, dtype::from_args(pybind11::str(dtype)).release().ptr(), nullptr));
925
+ if (!new_view) {
926
+ throw error_already_set();
927
+ }
928
+ return new_view;
929
+ }
930
+
931
+ /// Ensure that the argument is a NumPy array
932
+ /// In case of an error, nullptr is returned and the Python error is cleared.
933
+ static array ensure(handle h, int ExtraFlags = 0) {
934
+ auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));
935
+ if (!result) {
936
+ PyErr_Clear();
937
+ }
938
+ return result;
939
+ }
940
+
941
+ protected:
942
+ template <typename, typename>
943
+ friend struct detail::npy_format_descriptor;
944
+
945
+ void fail_dim_check(ssize_t dim, const std::string &msg) const {
946
+ throw index_error(msg + ": " + std::to_string(dim) + " (ndim = " + std::to_string(ndim())
947
+ + ")");
948
+ }
949
+
950
+ template <typename... Ix>
951
+ ssize_t byte_offset(Ix... index) const {
952
+ check_dimensions(index...);
953
+ return detail::byte_offset_unsafe(strides(), ssize_t(index)...);
954
+ }
955
+
956
+ void check_writeable() const {
957
+ if (!writeable()) {
958
+ throw std::domain_error("array is not writeable");
959
+ }
960
+ }
961
+
962
+ template <typename... Ix>
963
+ void check_dimensions(Ix... index) const {
964
+ check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);
965
+ }
966
+
967
+ void check_dimensions_impl(ssize_t, const ssize_t *) const {}
968
+
969
+ template <typename... Ix>
970
+ void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const {
971
+ if (i >= *shape) {
972
+ throw index_error(std::string("index ") + std::to_string(i)
973
+ + " is out of bounds for axis " + std::to_string(axis)
974
+ + " with size " + std::to_string(*shape));
975
+ }
976
+ check_dimensions_impl(axis + 1, shape + 1, index...);
977
+ }
978
+
979
+ /// Create array from any object -- always returns a new reference
980
+ static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) {
981
+ if (ptr == nullptr) {
982
+ PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array from a nullptr");
983
+ return nullptr;
984
+ }
985
+ return detail::npy_api::get().PyArray_FromAny_(
986
+ ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
987
+ }
988
+ };
989
+
990
+ template <typename T, int ExtraFlags = array::forcecast>
991
+ class array_t : public array {
992
+ private:
993
+ struct private_ctor {};
994
+ // Delegating constructor needed when both moving and accessing in the same constructor
995
+ array_t(private_ctor,
996
+ ShapeContainer &&shape,
997
+ StridesContainer &&strides,
998
+ const T *ptr,
999
+ handle base)
1000
+ : array(std::move(shape), std::move(strides), ptr, base) {}
1001
+
1002
+ public:
1003
+ static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t");
1004
+
1005
+ using value_type = T;
1006
+
1007
+ array_t() : array(0, static_cast<const T *>(nullptr)) {}
1008
+ array_t(handle h, borrowed_t) : array(h, borrowed_t{}) {}
1009
+ array_t(handle h, stolen_t) : array(h, stolen_t{}) {}
1010
+
1011
+ PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead")
1012
+ array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) {
1013
+ if (!m_ptr) {
1014
+ PyErr_Clear();
1015
+ }
1016
+ if (!is_borrowed) {
1017
+ Py_XDECREF(h.ptr());
1018
+ }
1019
+ }
1020
+
1021
+ // NOLINTNEXTLINE(google-explicit-constructor)
1022
+ array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {
1023
+ if (!m_ptr) {
1024
+ throw error_already_set();
1025
+ }
1026
+ }
1027
+
1028
+ explicit array_t(const buffer_info &info, handle base = handle()) : array(info, base) {}
1029
+
1030
+ array_t(ShapeContainer shape,
1031
+ StridesContainer strides,
1032
+ const T *ptr = nullptr,
1033
+ handle base = handle())
1034
+ : array(std::move(shape), std::move(strides), ptr, base) {}
1035
+
1036
+ explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
1037
+ : array_t(private_ctor{},
1038
+ std::move(shape),
1039
+ (ExtraFlags & f_style) != 0 ? detail::f_strides(*shape, itemsize())
1040
+ : detail::c_strides(*shape, itemsize()),
1041
+ ptr,
1042
+ base) {}
1043
+
1044
+ explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle())
1045
+ : array({count}, {}, ptr, base) {}
1046
+
1047
+ constexpr ssize_t itemsize() const { return sizeof(T); }
1048
+
1049
+ template <typename... Ix>
1050
+ ssize_t index_at(Ix... index) const {
1051
+ return offset_at(index...) / itemsize();
1052
+ }
1053
+
1054
+ template <typename... Ix>
1055
+ const T *data(Ix... index) const {
1056
+ return static_cast<const T *>(array::data(index...));
1057
+ }
1058
+
1059
+ template <typename... Ix>
1060
+ T *mutable_data(Ix... index) {
1061
+ return static_cast<T *>(array::mutable_data(index...));
1062
+ }
1063
+
1064
+ // Reference to element at a given index
1065
+ template <typename... Ix>
1066
+ const T &at(Ix... index) const {
1067
+ if ((ssize_t) sizeof...(index) != ndim()) {
1068
+ fail_dim_check(sizeof...(index), "index dimension mismatch");
1069
+ }
1070
+ return *(static_cast<const T *>(array::data())
1071
+ + byte_offset(ssize_t(index)...) / itemsize());
1072
+ }
1073
+
1074
+ // Mutable reference to element at a given index
1075
+ template <typename... Ix>
1076
+ T &mutable_at(Ix... index) {
1077
+ if ((ssize_t) sizeof...(index) != ndim()) {
1078
+ fail_dim_check(sizeof...(index), "index dimension mismatch");
1079
+ }
1080
+ return *(static_cast<T *>(array::mutable_data())
1081
+ + byte_offset(ssize_t(index)...) / itemsize());
1082
+ }
1083
+
1084
+ /**
1085
+ * Returns a proxy object that provides access to the array's data without bounds or
1086
+ * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with
1087
+ * care: the array must not be destroyed or reshaped for the duration of the returned object,
1088
+ * and the caller must take care not to access invalid dimensions or dimension indices.
1089
+ */
1090
+ template <ssize_t Dims = -1>
1091
+ detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
1092
+ return array::mutable_unchecked<T, Dims>();
1093
+ }
1094
+
1095
+ /**
1096
+ * Returns a proxy object that provides const access to the array's data without bounds or
1097
+ * dimensionality checking. Unlike `unchecked()`, this does not require that the underlying
1098
+ * array have the `writable` flag. Use with care: the array must not be destroyed or reshaped
1099
+ * for the duration of the returned object, and the caller must take care not to access invalid
1100
+ * dimensions or dimension indices.
1101
+ */
1102
+ template <ssize_t Dims = -1>
1103
+ detail::unchecked_reference<T, Dims> unchecked() const & {
1104
+ return array::unchecked<T, Dims>();
1105
+ }
1106
+
1107
+ /// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert
1108
+ /// it). In case of an error, nullptr is returned and the Python error is cleared.
1109
+ static array_t ensure(handle h) {
1110
+ auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));
1111
+ if (!result) {
1112
+ PyErr_Clear();
1113
+ }
1114
+ return result;
1115
+ }
1116
+
1117
+ static bool check_(handle h) {
1118
+ const auto &api = detail::npy_api::get();
1119
+ return api.PyArray_Check_(h.ptr())
1120
+ && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr,
1121
+ dtype::of<T>().ptr())
1122
+ && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style));
1123
+ }
1124
+
1125
+ protected:
1126
+ /// Create array from any object -- always returns a new reference
1127
+ static PyObject *raw_array_t(PyObject *ptr) {
1128
+ if (ptr == nullptr) {
1129
+ PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr");
1130
+ return nullptr;
1131
+ }
1132
+ return detail::npy_api::get().PyArray_FromAny_(ptr,
1133
+ dtype::of<T>().release().ptr(),
1134
+ 0,
1135
+ 0,
1136
+ detail::npy_api::NPY_ARRAY_ENSUREARRAY_
1137
+ | ExtraFlags,
1138
+ nullptr);
1139
+ }
1140
+ };
1141
+
1142
+ template <typename T>
1143
+ struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1144
+ static std::string format() {
1145
+ return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::format();
1146
+ }
1147
+ };
1148
+
1149
+ template <size_t N>
1150
+ struct format_descriptor<char[N]> {
1151
+ static std::string format() { return std::to_string(N) + "s"; }
1152
+ };
1153
+ template <size_t N>
1154
+ struct format_descriptor<std::array<char, N>> {
1155
+ static std::string format() { return std::to_string(N) + "s"; }
1156
+ };
1157
+
1158
+ template <typename T>
1159
+ struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> {
1160
+ static std::string format() {
1161
+ return format_descriptor<
1162
+ typename std::remove_cv<typename std::underlying_type<T>::type>::type>::format();
1163
+ }
1164
+ };
1165
+
1166
+ template <typename T>
1167
+ struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {
1168
+ static std::string format() {
1169
+ using namespace detail;
1170
+ static constexpr auto extents = const_name("(") + array_info<T>::extents + const_name(")");
1171
+ return extents.text + format_descriptor<remove_all_extents_t<T>>::format();
1172
+ }
1173
+ };
1174
+
1175
+ PYBIND11_NAMESPACE_BEGIN(detail)
1176
+ template <typename T, int ExtraFlags>
1177
+ struct pyobject_caster<array_t<T, ExtraFlags>> {
1178
+ using type = array_t<T, ExtraFlags>;
1179
+
1180
+ bool load(handle src, bool convert) {
1181
+ if (!convert && !type::check_(src)) {
1182
+ return false;
1183
+ }
1184
+ value = type::ensure(src);
1185
+ return static_cast<bool>(value);
1186
+ }
1187
+
1188
+ static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1189
+ return src.inc_ref();
1190
+ }
1191
+ PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
1192
+ };
1193
+
1194
+ template <typename T>
1195
+ struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1196
+ static bool compare(const buffer_info &b) {
1197
+ return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());
1198
+ }
1199
+ };
1200
+
1201
+ template <typename T, typename = void>
1202
+ struct npy_format_descriptor_name;
1203
+
1204
+ template <typename T>
1205
+ struct npy_format_descriptor_name<T, enable_if_t<std::is_integral<T>::value>> {
1206
+ static constexpr auto name = const_name<std::is_same<T, bool>::value>(
1207
+ const_name("bool"),
1208
+ const_name<std::is_signed<T>::value>("numpy.int", "numpy.uint")
1209
+ + const_name<sizeof(T) * 8>());
1210
+ };
1211
+
1212
+ template <typename T>
1213
+ struct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> {
1214
+ static constexpr auto name = const_name < std::is_same<T, float>::value
1215
+ || std::is_same<T, const float>::value
1216
+ || std::is_same<T, double>::value
1217
+ || std::is_same<T, const double>::value
1218
+ > (const_name("numpy.float") + const_name<sizeof(T) * 8>(),
1219
+ const_name("numpy.longdouble"));
1220
+ };
1221
+
1222
+ template <typename T>
1223
+ struct npy_format_descriptor_name<T, enable_if_t<is_complex<T>::value>> {
1224
+ static constexpr auto name = const_name < std::is_same<typename T::value_type, float>::value
1225
+ || std::is_same<typename T::value_type, const float>::value
1226
+ || std::is_same<typename T::value_type, double>::value
1227
+ || std::is_same<typename T::value_type, const double>::value
1228
+ > (const_name("numpy.complex")
1229
+ + const_name<sizeof(typename T::value_type) * 16>(),
1230
+ const_name("numpy.longcomplex"));
1231
+ };
1232
+
1233
+ template <typename T>
1234
+ struct npy_format_descriptor<
1235
+ T,
1236
+ enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>>
1237
+ : npy_format_descriptor_name<T> {
1238
+ private:
1239
+ // NB: the order here must match the one in common.h
1240
+ constexpr static const int values[15] = {npy_api::NPY_BOOL_,
1241
+ npy_api::NPY_BYTE_,
1242
+ npy_api::NPY_UBYTE_,
1243
+ npy_api::NPY_INT16_,
1244
+ npy_api::NPY_UINT16_,
1245
+ npy_api::NPY_INT32_,
1246
+ npy_api::NPY_UINT32_,
1247
+ npy_api::NPY_INT64_,
1248
+ npy_api::NPY_UINT64_,
1249
+ npy_api::NPY_FLOAT_,
1250
+ npy_api::NPY_DOUBLE_,
1251
+ npy_api::NPY_LONGDOUBLE_,
1252
+ npy_api::NPY_CFLOAT_,
1253
+ npy_api::NPY_CDOUBLE_,
1254
+ npy_api::NPY_CLONGDOUBLE_};
1255
+
1256
+ public:
1257
+ static constexpr int value = values[detail::is_fmt_numeric<T>::index];
1258
+
1259
+ static pybind11::dtype dtype() {
1260
+ if (auto *ptr = npy_api::get().PyArray_DescrFromType_(value)) {
1261
+ return reinterpret_steal<pybind11::dtype>(ptr);
1262
+ }
1263
+ pybind11_fail("Unsupported buffer format!");
1264
+ }
1265
+ };
1266
+
1267
+ #define PYBIND11_DECL_CHAR_FMT \
1268
+ static constexpr auto name = const_name("S") + const_name<N>(); \
1269
+ static pybind11::dtype dtype() { \
1270
+ return pybind11::dtype(std::string("S") + std::to_string(N)); \
1271
+ }
1272
+ template <size_t N>
1273
+ struct npy_format_descriptor<char[N]> {
1274
+ PYBIND11_DECL_CHAR_FMT
1275
+ };
1276
+ template <size_t N>
1277
+ struct npy_format_descriptor<std::array<char, N>> {
1278
+ PYBIND11_DECL_CHAR_FMT
1279
+ };
1280
+ #undef PYBIND11_DECL_CHAR_FMT
1281
+
1282
+ template <typename T>
1283
+ struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> {
1284
+ private:
1285
+ using base_descr = npy_format_descriptor<typename array_info<T>::type>;
1286
+
1287
+ public:
1288
+ static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported");
1289
+
1290
+ static constexpr auto name
1291
+ = const_name("(") + array_info<T>::extents + const_name(")") + base_descr::name;
1292
+ static pybind11::dtype dtype() {
1293
+ list shape;
1294
+ array_info<T>::append_extents(shape);
1295
+ return pybind11::dtype::from_args(pybind11::make_tuple(base_descr::dtype(), shape));
1296
+ }
1297
+ };
1298
+
1299
+ template <typename T>
1300
+ struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> {
1301
+ private:
1302
+ using base_descr = npy_format_descriptor<typename std::underlying_type<T>::type>;
1303
+
1304
+ public:
1305
+ static constexpr auto name = base_descr::name;
1306
+ static pybind11::dtype dtype() { return base_descr::dtype(); }
1307
+ };
1308
+
1309
+ struct field_descriptor {
1310
+ const char *name;
1311
+ ssize_t offset;
1312
+ ssize_t size;
1313
+ std::string format;
1314
+ dtype descr;
1315
+ };
1316
+
1317
+ PYBIND11_NOINLINE void register_structured_dtype(any_container<field_descriptor> fields,
1318
+ const std::type_info &tinfo,
1319
+ ssize_t itemsize,
1320
+ bool (*direct_converter)(PyObject *, void *&)) {
1321
+
1322
+ auto &numpy_internals = get_numpy_internals();
1323
+ if (numpy_internals.get_type_info(tinfo, false)) {
1324
+ pybind11_fail("NumPy: dtype is already registered");
1325
+ }
1326
+
1327
+ // Use ordered fields because order matters as of NumPy 1.14:
1328
+ // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays
1329
+ std::vector<field_descriptor> ordered_fields(std::move(fields));
1330
+ std::sort(
1331
+ ordered_fields.begin(),
1332
+ ordered_fields.end(),
1333
+ [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
1334
+
1335
+ list names, formats, offsets;
1336
+ for (auto &field : ordered_fields) {
1337
+ if (!field.descr) {
1338
+ pybind11_fail(std::string("NumPy: unsupported field dtype: `") + field.name + "` @ "
1339
+ + tinfo.name());
1340
+ }
1341
+ names.append(PYBIND11_STR_TYPE(field.name));
1342
+ formats.append(field.descr);
1343
+ offsets.append(pybind11::int_(field.offset));
1344
+ }
1345
+ auto *dtype_ptr
1346
+ = pybind11::dtype(std::move(names), std::move(formats), std::move(offsets), itemsize)
1347
+ .release()
1348
+ .ptr();
1349
+
1350
+ // There is an existing bug in NumPy (as of v1.11): trailing bytes are
1351
+ // not encoded explicitly into the format string. This will supposedly
1352
+ // get fixed in v1.12; for further details, see these:
1353
+ // - https://github.com/numpy/numpy/issues/7797
1354
+ // - https://github.com/numpy/numpy/pull/7798
1355
+ // Because of this, we won't use numpy's logic to generate buffer format
1356
+ // strings and will just do it ourselves.
1357
+ ssize_t offset = 0;
1358
+ std::ostringstream oss;
1359
+ // mark the structure as unaligned with '^', because numpy and C++ don't
1360
+ // always agree about alignment (particularly for complex), and we're
1361
+ // explicitly listing all our padding. This depends on none of the fields
1362
+ // overriding the endianness. Putting the ^ in front of individual fields
1363
+ // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049
1364
+ oss << "^T{";
1365
+ for (auto &field : ordered_fields) {
1366
+ if (field.offset > offset) {
1367
+ oss << (field.offset - offset) << 'x';
1368
+ }
1369
+ oss << field.format << ':' << field.name << ':';
1370
+ offset = field.offset + field.size;
1371
+ }
1372
+ if (itemsize > offset) {
1373
+ oss << (itemsize - offset) << 'x';
1374
+ }
1375
+ oss << '}';
1376
+ auto format_str = oss.str();
1377
+
1378
+ // Sanity check: verify that NumPy properly parses our buffer format string
1379
+ auto &api = npy_api::get();
1380
+ auto arr = array(buffer_info(nullptr, itemsize, format_str, 1));
1381
+ if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr())) {
1382
+ pybind11_fail("NumPy: invalid buffer descriptor!");
1383
+ }
1384
+
1385
+ auto tindex = std::type_index(tinfo);
1386
+ numpy_internals.registered_dtypes[tindex] = {dtype_ptr, format_str};
1387
+ get_internals().direct_conversions[tindex].push_back(direct_converter);
1388
+ }
1389
+
1390
+ template <typename T, typename SFINAE>
1391
+ struct npy_format_descriptor {
1392
+ static_assert(is_pod_struct<T>::value,
1393
+ "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
1394
+
1395
+ static constexpr auto name = make_caster<T>::name;
1396
+
1397
+ static pybind11::dtype dtype() { return reinterpret_borrow<pybind11::dtype>(dtype_ptr()); }
1398
+
1399
+ static std::string format() {
1400
+ static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;
1401
+ return format_str;
1402
+ }
1403
+
1404
+ static void register_dtype(any_container<field_descriptor> fields) {
1405
+ register_structured_dtype(std::move(fields),
1406
+ typeid(typename std::remove_cv<T>::type),
1407
+ sizeof(T),
1408
+ &direct_converter);
1409
+ }
1410
+
1411
+ private:
1412
+ static PyObject *dtype_ptr() {
1413
+ static PyObject *ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
1414
+ return ptr;
1415
+ }
1416
+
1417
+ static bool direct_converter(PyObject *obj, void *&value) {
1418
+ auto &api = npy_api::get();
1419
+ if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_)) {
1420
+ return false;
1421
+ }
1422
+ if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {
1423
+ if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {
1424
+ value = ((PyVoidScalarObject_Proxy *) obj)->obval;
1425
+ return true;
1426
+ }
1427
+ }
1428
+ return false;
1429
+ }
1430
+ };
1431
+
1432
+ #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
1433
+ # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0)
1434
+ # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0)
1435
+ #else
1436
+
1437
+ # define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
1438
+ ::pybind11::detail::field_descriptor { \
1439
+ Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
1440
+ ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
1441
+ ::pybind11::detail::npy_format_descriptor< \
1442
+ decltype(std::declval<T>().Field)>::dtype() \
1443
+ }
1444
+
1445
+ // Extract name, offset and format descriptor for a struct field
1446
+ # define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, # Field)
1447
+
1448
+ // The main idea of this macro is borrowed from https://github.com/swansontec/map-macro
1449
+ // (C) William Swanson, Paul Fultz
1450
+ # define PYBIND11_EVAL0(...) __VA_ARGS__
1451
+ # define PYBIND11_EVAL1(...) PYBIND11_EVAL0(PYBIND11_EVAL0(PYBIND11_EVAL0(__VA_ARGS__)))
1452
+ # define PYBIND11_EVAL2(...) PYBIND11_EVAL1(PYBIND11_EVAL1(PYBIND11_EVAL1(__VA_ARGS__)))
1453
+ # define PYBIND11_EVAL3(...) PYBIND11_EVAL2(PYBIND11_EVAL2(PYBIND11_EVAL2(__VA_ARGS__)))
1454
+ # define PYBIND11_EVAL4(...) PYBIND11_EVAL3(PYBIND11_EVAL3(PYBIND11_EVAL3(__VA_ARGS__)))
1455
+ # define PYBIND11_EVAL(...) PYBIND11_EVAL4(PYBIND11_EVAL4(PYBIND11_EVAL4(__VA_ARGS__)))
1456
+ # define PYBIND11_MAP_END(...)
1457
+ # define PYBIND11_MAP_OUT
1458
+ # define PYBIND11_MAP_COMMA ,
1459
+ # define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
1460
+ # define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
1461
+ # define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0(test, next, 0)
1462
+ # define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1(PYBIND11_MAP_GET_END test, next)
1463
+ # if defined(_MSC_VER) \
1464
+ && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround
1465
+ # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1466
+ PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1467
+ # else
1468
+ # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1469
+ PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1470
+ # endif
1471
+ # define PYBIND11_MAP_LIST_NEXT(test, next) \
1472
+ PYBIND11_MAP_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1473
+ # define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
1474
+ f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST1)(f, t, peek, __VA_ARGS__)
1475
+ # define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
1476
+ f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST0)(f, t, peek, __VA_ARGS__)
1477
+ // PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...
1478
+ # define PYBIND11_MAP_LIST(f, t, ...) \
1479
+ PYBIND11_EVAL(PYBIND11_MAP_LIST1(f, t, __VA_ARGS__, (), 0))
1480
+
1481
+ # define PYBIND11_NUMPY_DTYPE(Type, ...) \
1482
+ ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1483
+ ::std::vector<::pybind11::detail::field_descriptor>{ \
1484
+ PYBIND11_MAP_LIST(PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
1485
+
1486
+ # if defined(_MSC_VER) && !defined(__clang__)
1487
+ # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1488
+ PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1489
+ # else
1490
+ # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1491
+ PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1492
+ # endif
1493
+ # define PYBIND11_MAP2_LIST_NEXT(test, next) \
1494
+ PYBIND11_MAP2_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1495
+ # define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
1496
+ f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST1)(f, t, peek, __VA_ARGS__)
1497
+ # define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
1498
+ f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST0)(f, t, peek, __VA_ARGS__)
1499
+ // PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...
1500
+ # define PYBIND11_MAP2_LIST(f, t, ...) \
1501
+ PYBIND11_EVAL(PYBIND11_MAP2_LIST1(f, t, __VA_ARGS__, (), 0))
1502
+
1503
+ # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
1504
+ ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1505
+ ::std::vector<::pybind11::detail::field_descriptor>{ \
1506
+ PYBIND11_MAP2_LIST(PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
1507
+
1508
+ #endif // __CLION_IDE__
1509
+
1510
+ class common_iterator {
1511
+ public:
1512
+ using container_type = std::vector<ssize_t>;
1513
+ using value_type = container_type::value_type;
1514
+ using size_type = container_type::size_type;
1515
+
1516
+ common_iterator() : m_strides() {}
1517
+
1518
+ common_iterator(void *ptr, const container_type &strides, const container_type &shape)
1519
+ : p_ptr(reinterpret_cast<char *>(ptr)), m_strides(strides.size()) {
1520
+ m_strides.back() = static_cast<value_type>(strides.back());
1521
+ for (size_type i = m_strides.size() - 1; i != 0; --i) {
1522
+ size_type j = i - 1;
1523
+ auto s = static_cast<value_type>(shape[i]);
1524
+ m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
1525
+ }
1526
+ }
1527
+
1528
+ void increment(size_type dim) { p_ptr += m_strides[dim]; }
1529
+
1530
+ void *data() const { return p_ptr; }
1531
+
1532
+ private:
1533
+ char *p_ptr{0};
1534
+ container_type m_strides;
1535
+ };
1536
+
1537
+ template <size_t N>
1538
+ class multi_array_iterator {
1539
+ public:
1540
+ using container_type = std::vector<ssize_t>;
1541
+
1542
+ multi_array_iterator(const std::array<buffer_info, N> &buffers, const container_type &shape)
1543
+ : m_shape(shape.size()), m_index(shape.size(), 0), m_common_iterator() {
1544
+
1545
+ // Manual copy to avoid conversion warning if using std::copy
1546
+ for (size_t i = 0; i < shape.size(); ++i) {
1547
+ m_shape[i] = shape[i];
1548
+ }
1549
+
1550
+ container_type strides(shape.size());
1551
+ for (size_t i = 0; i < N; ++i) {
1552
+ init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
1553
+ }
1554
+ }
1555
+
1556
+ multi_array_iterator &operator++() {
1557
+ for (size_t j = m_index.size(); j != 0; --j) {
1558
+ size_t i = j - 1;
1559
+ if (++m_index[i] != m_shape[i]) {
1560
+ increment_common_iterator(i);
1561
+ break;
1562
+ }
1563
+ m_index[i] = 0;
1564
+ }
1565
+ return *this;
1566
+ }
1567
+
1568
+ template <size_t K, class T = void>
1569
+ T *data() const {
1570
+ return reinterpret_cast<T *>(m_common_iterator[K].data());
1571
+ }
1572
+
1573
+ private:
1574
+ using common_iter = common_iterator;
1575
+
1576
+ void init_common_iterator(const buffer_info &buffer,
1577
+ const container_type &shape,
1578
+ common_iter &iterator,
1579
+ container_type &strides) {
1580
+ auto buffer_shape_iter = buffer.shape.rbegin();
1581
+ auto buffer_strides_iter = buffer.strides.rbegin();
1582
+ auto shape_iter = shape.rbegin();
1583
+ auto strides_iter = strides.rbegin();
1584
+
1585
+ while (buffer_shape_iter != buffer.shape.rend()) {
1586
+ if (*shape_iter == *buffer_shape_iter) {
1587
+ *strides_iter = *buffer_strides_iter;
1588
+ } else {
1589
+ *strides_iter = 0;
1590
+ }
1591
+
1592
+ ++buffer_shape_iter;
1593
+ ++buffer_strides_iter;
1594
+ ++shape_iter;
1595
+ ++strides_iter;
1596
+ }
1597
+
1598
+ std::fill(strides_iter, strides.rend(), 0);
1599
+ iterator = common_iter(buffer.ptr, strides, shape);
1600
+ }
1601
+
1602
+ void increment_common_iterator(size_t dim) {
1603
+ for (auto &iter : m_common_iterator) {
1604
+ iter.increment(dim);
1605
+ }
1606
+ }
1607
+
1608
+ container_type m_shape;
1609
+ container_type m_index;
1610
+ std::array<common_iter, N> m_common_iterator;
1611
+ };
1612
+
1613
+ enum class broadcast_trivial { non_trivial, c_trivial, f_trivial };
1614
+
1615
+ // Populates the shape and number of dimensions for the set of buffers. Returns a
1616
+ // broadcast_trivial enum value indicating whether the broadcast is "trivial"--that is, has each
1617
+ // buffer being either a singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous
1618
+ // (`f_trivial`) storage buffer; returns `non_trivial` otherwise.
1619
+ template <size_t N>
1620
+ broadcast_trivial
1621
+ broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
1622
+ ndim = std::accumulate(
1623
+ buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
1624
+ return std::max(res, buf.ndim);
1625
+ });
1626
+
1627
+ shape.clear();
1628
+ shape.resize((size_t) ndim, 1);
1629
+
1630
+ // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1
1631
+ // or the full size).
1632
+ for (size_t i = 0; i < N; ++i) {
1633
+ auto res_iter = shape.rbegin();
1634
+ auto end = buffers[i].shape.rend();
1635
+ for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end;
1636
+ ++shape_iter, ++res_iter) {
1637
+ const auto &dim_size_in = *shape_iter;
1638
+ auto &dim_size_out = *res_iter;
1639
+
1640
+ // Each input dimension can either be 1 or `n`, but `n` values must match across
1641
+ // buffers
1642
+ if (dim_size_out == 1) {
1643
+ dim_size_out = dim_size_in;
1644
+ } else if (dim_size_in != 1 && dim_size_in != dim_size_out) {
1645
+ pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
1646
+ }
1647
+ }
1648
+ }
1649
+
1650
+ bool trivial_broadcast_c = true;
1651
+ bool trivial_broadcast_f = true;
1652
+ for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {
1653
+ if (buffers[i].size == 1) {
1654
+ continue;
1655
+ }
1656
+
1657
+ // Require the same number of dimensions:
1658
+ if (buffers[i].ndim != ndim) {
1659
+ return broadcast_trivial::non_trivial;
1660
+ }
1661
+
1662
+ // Require all dimensions be full-size:
1663
+ if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin())) {
1664
+ return broadcast_trivial::non_trivial;
1665
+ }
1666
+
1667
+ // Check for C contiguity (but only if previous inputs were also C contiguous)
1668
+ if (trivial_broadcast_c) {
1669
+ ssize_t expect_stride = buffers[i].itemsize;
1670
+ auto end = buffers[i].shape.crend();
1671
+ for (auto shape_iter = buffers[i].shape.crbegin(),
1672
+ stride_iter = buffers[i].strides.crbegin();
1673
+ trivial_broadcast_c && shape_iter != end;
1674
+ ++shape_iter, ++stride_iter) {
1675
+ if (expect_stride == *stride_iter) {
1676
+ expect_stride *= *shape_iter;
1677
+ } else {
1678
+ trivial_broadcast_c = false;
1679
+ }
1680
+ }
1681
+ }
1682
+
1683
+ // Check for Fortran contiguity (if previous inputs were also F contiguous)
1684
+ if (trivial_broadcast_f) {
1685
+ ssize_t expect_stride = buffers[i].itemsize;
1686
+ auto end = buffers[i].shape.cend();
1687
+ for (auto shape_iter = buffers[i].shape.cbegin(),
1688
+ stride_iter = buffers[i].strides.cbegin();
1689
+ trivial_broadcast_f && shape_iter != end;
1690
+ ++shape_iter, ++stride_iter) {
1691
+ if (expect_stride == *stride_iter) {
1692
+ expect_stride *= *shape_iter;
1693
+ } else {
1694
+ trivial_broadcast_f = false;
1695
+ }
1696
+ }
1697
+ }
1698
+ }
1699
+
1700
+ return trivial_broadcast_c ? broadcast_trivial::c_trivial
1701
+ : trivial_broadcast_f ? broadcast_trivial::f_trivial
1702
+ : broadcast_trivial::non_trivial;
1703
+ }
1704
+
1705
+ template <typename T>
1706
+ struct vectorize_arg {
1707
+ static_assert(!std::is_rvalue_reference<T>::value,
1708
+ "Functions with rvalue reference arguments cannot be vectorized");
1709
+ // The wrapped function gets called with this type:
1710
+ using call_type = remove_reference_t<T>;
1711
+ // Is this a vectorized argument?
1712
+ static constexpr bool vectorize
1713
+ = satisfies_any_of<call_type, std::is_arithmetic, is_complex, is_pod>::value
1714
+ && satisfies_none_of<call_type,
1715
+ std::is_pointer,
1716
+ std::is_array,
1717
+ is_std_array,
1718
+ std::is_enum>::value
1719
+ && (!std::is_reference<T>::value
1720
+ || (std::is_lvalue_reference<T>::value && std::is_const<call_type>::value));
1721
+ // Accept this type: an array for vectorized types, otherwise the type as-is:
1722
+ using type = conditional_t<vectorize, array_t<remove_cv_t<call_type>, array::forcecast>, T>;
1723
+ };
1724
+
1725
+ // py::vectorize when a return type is present
1726
+ template <typename Func, typename Return, typename... Args>
1727
+ struct vectorize_returned_array {
1728
+ using Type = array_t<Return>;
1729
+
1730
+ static Type create(broadcast_trivial trivial, const std::vector<ssize_t> &shape) {
1731
+ if (trivial == broadcast_trivial::f_trivial) {
1732
+ return array_t<Return, array::f_style>(shape);
1733
+ }
1734
+ return array_t<Return>(shape);
1735
+ }
1736
+
1737
+ static Return *mutable_data(Type &array) { return array.mutable_data(); }
1738
+
1739
+ static Return call(Func &f, Args &...args) { return f(args...); }
1740
+
1741
+ static void call(Return *out, size_t i, Func &f, Args &...args) { out[i] = f(args...); }
1742
+ };
1743
+
1744
+ // py::vectorize when a return type is not present
1745
+ template <typename Func, typename... Args>
1746
+ struct vectorize_returned_array<Func, void, Args...> {
1747
+ using Type = none;
1748
+
1749
+ static Type create(broadcast_trivial, const std::vector<ssize_t> &) { return none(); }
1750
+
1751
+ static void *mutable_data(Type &) { return nullptr; }
1752
+
1753
+ static detail::void_type call(Func &f, Args &...args) {
1754
+ f(args...);
1755
+ return {};
1756
+ }
1757
+
1758
+ static void call(void *, size_t, Func &f, Args &...args) { f(args...); }
1759
+ };
1760
+
1761
+ template <typename Func, typename Return, typename... Args>
1762
+ struct vectorize_helper {
1763
+
1764
+ // NVCC for some reason breaks if NVectorized is private
1765
+ #ifdef __CUDACC__
1766
+ public:
1767
+ #else
1768
+ private:
1769
+ #endif
1770
+
1771
+ static constexpr size_t N = sizeof...(Args);
1772
+ static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);
1773
+ static_assert(
1774
+ NVectorized >= 1,
1775
+ "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
1776
+
1777
+ public:
1778
+ template <typename T,
1779
+ // SFINAE to prevent shadowing the copy constructor.
1780
+ typename = detail::enable_if_t<
1781
+ !std::is_same<vectorize_helper, typename std::decay<T>::type>::value>>
1782
+ explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) {}
1783
+
1784
+ object operator()(typename vectorize_arg<Args>::type... args) {
1785
+ return run(args...,
1786
+ make_index_sequence<N>(),
1787
+ select_indices<vectorize_arg<Args>::vectorize...>(),
1788
+ make_index_sequence<NVectorized>());
1789
+ }
1790
+
1791
+ private:
1792
+ remove_reference_t<Func> f;
1793
+
1794
+ // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling
1795
+ // with "/permissive-" flag when arg_call_types is manually inlined.
1796
+ using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>;
1797
+ template <size_t Index>
1798
+ using param_n_t = typename std::tuple_element<Index, arg_call_types>::type;
1799
+
1800
+ using returned_array = vectorize_returned_array<Func, Return, Args...>;
1801
+
1802
+ // Runs a vectorized function given arguments tuple and three index sequences:
1803
+ // - Index is the full set of 0 ... (N-1) argument indices;
1804
+ // - VIndex is the subset of argument indices with vectorized parameters, letting us access
1805
+ // vectorized arguments (anything not in this sequence is passed through)
1806
+ // - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that
1807
+ // we can store vectorized buffer_infos in an array (argument VIndex has its buffer at
1808
+ // index BIndex in the array).
1809
+ template <size_t... Index, size_t... VIndex, size_t... BIndex>
1810
+ object run(typename vectorize_arg<Args>::type &...args,
1811
+ index_sequence<Index...> i_seq,
1812
+ index_sequence<VIndex...> vi_seq,
1813
+ index_sequence<BIndex...> bi_seq) {
1814
+
1815
+ // Pointers to values the function was called with; the vectorized ones set here will start
1816
+ // out as array_t<T> pointers, but they will be changed them to T pointers before we make
1817
+ // call the wrapped function. Non-vectorized pointers are left as-is.
1818
+ std::array<void *, N> params{{&args...}};
1819
+
1820
+ // The array of `buffer_info`s of vectorized arguments:
1821
+ std::array<buffer_info, NVectorized> buffers{
1822
+ {reinterpret_cast<array *>(params[VIndex])->request()...}};
1823
+
1824
+ /* Determine dimensions parameters of output array */
1825
+ ssize_t nd = 0;
1826
+ std::vector<ssize_t> shape(0);
1827
+ auto trivial = broadcast(buffers, nd, shape);
1828
+ auto ndim = (size_t) nd;
1829
+
1830
+ size_t size
1831
+ = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
1832
+
1833
+ // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.
1834
+ // not wrapped in an array).
1835
+ if (size == 1 && ndim == 0) {
1836
+ PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);
1837
+ return cast(
1838
+ returned_array::call(f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...));
1839
+ }
1840
+
1841
+ auto result = returned_array::create(trivial, shape);
1842
+
1843
+ if (size == 0) {
1844
+ return std::move(result);
1845
+ }
1846
+
1847
+ /* Call the function */
1848
+ auto *mutable_data = returned_array::mutable_data(result);
1849
+ if (trivial == broadcast_trivial::non_trivial) {
1850
+ apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq);
1851
+ } else {
1852
+ apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq);
1853
+ }
1854
+
1855
+ return std::move(result);
1856
+ }
1857
+
1858
+ template <size_t... Index, size_t... VIndex, size_t... BIndex>
1859
+ void apply_trivial(std::array<buffer_info, NVectorized> &buffers,
1860
+ std::array<void *, N> &params,
1861
+ Return *out,
1862
+ size_t size,
1863
+ index_sequence<Index...>,
1864
+ index_sequence<VIndex...>,
1865
+ index_sequence<BIndex...>) {
1866
+
1867
+ // Initialize an array of mutable byte references and sizes with references set to the
1868
+ // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size
1869
+ // (except for singletons, which get an increment of 0).
1870
+ std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{
1871
+ {std::pair<unsigned char *&, const size_t>(
1872
+ reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
1873
+ buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>))...}};
1874
+
1875
+ for (size_t i = 0; i < size; ++i) {
1876
+ returned_array::call(
1877
+ out, i, f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...);
1878
+ for (auto &x : vecparams) {
1879
+ x.first += x.second;
1880
+ }
1881
+ }
1882
+ }
1883
+
1884
+ template <size_t... Index, size_t... VIndex, size_t... BIndex>
1885
+ void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,
1886
+ std::array<void *, N> &params,
1887
+ Return *out,
1888
+ size_t size,
1889
+ const std::vector<ssize_t> &output_shape,
1890
+ index_sequence<Index...>,
1891
+ index_sequence<VIndex...>,
1892
+ index_sequence<BIndex...>) {
1893
+
1894
+ multi_array_iterator<NVectorized> input_iter(buffers, output_shape);
1895
+
1896
+ for (size_t i = 0; i < size; ++i, ++input_iter) {
1897
+ PYBIND11_EXPAND_SIDE_EFFECTS((params[VIndex] = input_iter.template data<BIndex>()));
1898
+ returned_array::call(
1899
+ out, i, f, *reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
1900
+ }
1901
+ }
1902
+ };
1903
+
1904
+ template <typename Func, typename Return, typename... Args>
1905
+ vectorize_helper<Func, Return, Args...> vectorize_extractor(const Func &f, Return (*)(Args...)) {
1906
+ return detail::vectorize_helper<Func, Return, Args...>(f);
1907
+ }
1908
+
1909
+ template <typename T, int Flags>
1910
+ struct handle_type_name<array_t<T, Flags>> {
1911
+ static constexpr auto name
1912
+ = const_name("numpy.ndarray[") + npy_format_descriptor<T>::name + const_name("]");
1913
+ };
1914
+
1915
+ PYBIND11_NAMESPACE_END(detail)
1916
+
1917
+ // Vanilla pointer vectorizer:
1918
+ template <typename Return, typename... Args>
1919
+ detail::vectorize_helper<Return (*)(Args...), Return, Args...> vectorize(Return (*f)(Args...)) {
1920
+ return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);
1921
+ }
1922
+
1923
+ // lambda vectorizer:
1924
+ template <typename Func, detail::enable_if_t<detail::is_lambda<Func>::value, int> = 0>
1925
+ auto vectorize(Func &&f)
1926
+ -> decltype(detail::vectorize_extractor(std::forward<Func>(f),
1927
+ (detail::function_signature_t<Func> *) nullptr)) {
1928
+ return detail::vectorize_extractor(std::forward<Func>(f),
1929
+ (detail::function_signature_t<Func> *) nullptr);
1930
+ }
1931
+
1932
+ // Vectorize a class method (non-const):
1933
+ template <typename Return,
1934
+ typename Class,
1935
+ typename... Args,
1936
+ typename Helper = detail::vectorize_helper<
1937
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())),
1938
+ Return,
1939
+ Class *,
1940
+ Args...>>
1941
+ Helper vectorize(Return (Class::*f)(Args...)) {
1942
+ return Helper(std::mem_fn(f));
1943
+ }
1944
+
1945
+ // Vectorize a class method (const):
1946
+ template <typename Return,
1947
+ typename Class,
1948
+ typename... Args,
1949
+ typename Helper = detail::vectorize_helper<
1950
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())),
1951
+ Return,
1952
+ const Class *,
1953
+ Args...>>
1954
+ Helper vectorize(Return (Class::*f)(Args...) const) {
1955
+ return Helper(std::mem_fn(f));
1956
+ }
1957
+
1958
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/operators.h ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/operator.h: Metatemplates for operator overloading
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+ PYBIND11_NAMESPACE_BEGIN(detail)
16
+
17
+ /// Enumeration with all supported operator types
18
+ enum op_id : int {
19
+ op_add,
20
+ op_sub,
21
+ op_mul,
22
+ op_div,
23
+ op_mod,
24
+ op_divmod,
25
+ op_pow,
26
+ op_lshift,
27
+ op_rshift,
28
+ op_and,
29
+ op_xor,
30
+ op_or,
31
+ op_neg,
32
+ op_pos,
33
+ op_abs,
34
+ op_invert,
35
+ op_int,
36
+ op_long,
37
+ op_float,
38
+ op_str,
39
+ op_cmp,
40
+ op_gt,
41
+ op_ge,
42
+ op_lt,
43
+ op_le,
44
+ op_eq,
45
+ op_ne,
46
+ op_iadd,
47
+ op_isub,
48
+ op_imul,
49
+ op_idiv,
50
+ op_imod,
51
+ op_ilshift,
52
+ op_irshift,
53
+ op_iand,
54
+ op_ixor,
55
+ op_ior,
56
+ op_complex,
57
+ op_bool,
58
+ op_nonzero,
59
+ op_repr,
60
+ op_truediv,
61
+ op_itruediv,
62
+ op_hash
63
+ };
64
+
65
+ enum op_type : int {
66
+ op_l, /* base type on left */
67
+ op_r, /* base type on right */
68
+ op_u /* unary operator */
69
+ };
70
+
71
+ struct self_t {};
72
+ static const self_t self = self_t();
73
+
74
+ /// Type for an unused type slot
75
+ struct undefined_t {};
76
+
77
+ /// Don't warn about an unused variable
78
+ inline self_t __self() { return self; }
79
+
80
+ /// base template of operator implementations
81
+ template <op_id, op_type, typename B, typename L, typename R>
82
+ struct op_impl {};
83
+
84
+ /// Operator implementation generator
85
+ template <op_id id, op_type ot, typename L, typename R>
86
+ struct op_ {
87
+ template <typename Class, typename... Extra>
88
+ void execute(Class &cl, const Extra &...extra) const {
89
+ using Base = typename Class::type;
90
+ using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;
91
+ using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;
92
+ using op = op_impl<id, ot, Base, L_type, R_type>;
93
+ cl.def(op::name(), &op::execute, is_operator(), extra...);
94
+ #if PY_MAJOR_VERSION < 3
95
+ if (PYBIND11_SILENCE_MSVC_C4127(id == op_truediv)
96
+ || PYBIND11_SILENCE_MSVC_C4127(id == op_itruediv))
97
+ cl.def(id == op_itruediv ? "__idiv__"
98
+ : ot == op_l ? "__div__"
99
+ : "__rdiv__",
100
+ &op::execute,
101
+ is_operator(),
102
+ extra...);
103
+ #endif
104
+ }
105
+ template <typename Class, typename... Extra>
106
+ void execute_cast(Class &cl, const Extra &...extra) const {
107
+ using Base = typename Class::type;
108
+ using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;
109
+ using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;
110
+ using op = op_impl<id, ot, Base, L_type, R_type>;
111
+ cl.def(op::name(), &op::execute_cast, is_operator(), extra...);
112
+ #if PY_MAJOR_VERSION < 3
113
+ if (id == op_truediv || id == op_itruediv)
114
+ cl.def(id == op_itruediv ? "__idiv__"
115
+ : ot == op_l ? "__div__"
116
+ : "__rdiv__",
117
+ &op::execute,
118
+ is_operator(),
119
+ extra...);
120
+ #endif
121
+ }
122
+ };
123
+
124
+ #define PYBIND11_BINARY_OPERATOR(id, rid, op, expr) \
125
+ template <typename B, typename L, typename R> \
126
+ struct op_impl<op_##id, op_l, B, L, R> { \
127
+ static char const *name() { return "__" #id "__"; } \
128
+ static auto execute(const L &l, const R &r) -> decltype(expr) { return (expr); } \
129
+ static B execute_cast(const L &l, const R &r) { return B(expr); } \
130
+ }; \
131
+ template <typename B, typename L, typename R> \
132
+ struct op_impl<op_##id, op_r, B, L, R> { \
133
+ static char const *name() { return "__" #rid "__"; } \
134
+ static auto execute(const R &r, const L &l) -> decltype(expr) { return (expr); } \
135
+ static B execute_cast(const R &r, const L &l) { return B(expr); } \
136
+ }; \
137
+ inline op_<op_##id, op_l, self_t, self_t> op(const self_t &, const self_t &) { \
138
+ return op_<op_##id, op_l, self_t, self_t>(); \
139
+ } \
140
+ template <typename T> \
141
+ op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
142
+ return op_<op_##id, op_l, self_t, T>(); \
143
+ } \
144
+ template <typename T> \
145
+ op_<op_##id, op_r, T, self_t> op(const T &, const self_t &) { \
146
+ return op_<op_##id, op_r, T, self_t>(); \
147
+ }
148
+
149
+ #define PYBIND11_INPLACE_OPERATOR(id, op, expr) \
150
+ template <typename B, typename L, typename R> \
151
+ struct op_impl<op_##id, op_l, B, L, R> { \
152
+ static char const *name() { return "__" #id "__"; } \
153
+ static auto execute(L &l, const R &r) -> decltype(expr) { return expr; } \
154
+ static B execute_cast(L &l, const R &r) { return B(expr); } \
155
+ }; \
156
+ template <typename T> \
157
+ op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
158
+ return op_<op_##id, op_l, self_t, T>(); \
159
+ }
160
+
161
+ #define PYBIND11_UNARY_OPERATOR(id, op, expr) \
162
+ template <typename B, typename L> \
163
+ struct op_impl<op_##id, op_u, B, L, undefined_t> { \
164
+ static char const *name() { return "__" #id "__"; } \
165
+ static auto execute(const L &l) -> decltype(expr) { return expr; } \
166
+ static B execute_cast(const L &l) { return B(expr); } \
167
+ }; \
168
+ inline op_<op_##id, op_u, self_t, undefined_t> op(const self_t &) { \
169
+ return op_<op_##id, op_u, self_t, undefined_t>(); \
170
+ }
171
+
172
+ PYBIND11_BINARY_OPERATOR(sub, rsub, operator-, l - r)
173
+ PYBIND11_BINARY_OPERATOR(add, radd, operator+, l + r)
174
+ PYBIND11_BINARY_OPERATOR(mul, rmul, operator*, l *r)
175
+ PYBIND11_BINARY_OPERATOR(truediv, rtruediv, operator/, l / r)
176
+ PYBIND11_BINARY_OPERATOR(mod, rmod, operator%, l % r)
177
+ PYBIND11_BINARY_OPERATOR(lshift, rlshift, operator<<, l << r)
178
+ PYBIND11_BINARY_OPERATOR(rshift, rrshift, operator>>, l >> r)
179
+ PYBIND11_BINARY_OPERATOR(and, rand, operator&, l &r)
180
+ PYBIND11_BINARY_OPERATOR(xor, rxor, operator^, l ^ r)
181
+ PYBIND11_BINARY_OPERATOR(eq, eq, operator==, l == r)
182
+ PYBIND11_BINARY_OPERATOR(ne, ne, operator!=, l != r)
183
+ PYBIND11_BINARY_OPERATOR(or, ror, operator|, l | r)
184
+ PYBIND11_BINARY_OPERATOR(gt, lt, operator>, l > r)
185
+ PYBIND11_BINARY_OPERATOR(ge, le, operator>=, l >= r)
186
+ PYBIND11_BINARY_OPERATOR(lt, gt, operator<, l < r)
187
+ PYBIND11_BINARY_OPERATOR(le, ge, operator<=, l <= r)
188
+ // PYBIND11_BINARY_OPERATOR(pow, rpow, pow, std::pow(l, r))
189
+ PYBIND11_INPLACE_OPERATOR(iadd, operator+=, l += r)
190
+ PYBIND11_INPLACE_OPERATOR(isub, operator-=, l -= r)
191
+ PYBIND11_INPLACE_OPERATOR(imul, operator*=, l *= r)
192
+ PYBIND11_INPLACE_OPERATOR(itruediv, operator/=, l /= r)
193
+ PYBIND11_INPLACE_OPERATOR(imod, operator%=, l %= r)
194
+ PYBIND11_INPLACE_OPERATOR(ilshift, operator<<=, l <<= r)
195
+ PYBIND11_INPLACE_OPERATOR(irshift, operator>>=, l >>= r)
196
+ PYBIND11_INPLACE_OPERATOR(iand, operator&=, l &= r)
197
+ PYBIND11_INPLACE_OPERATOR(ixor, operator^=, l ^= r)
198
+ PYBIND11_INPLACE_OPERATOR(ior, operator|=, l |= r)
199
+ PYBIND11_UNARY_OPERATOR(neg, operator-, -l)
200
+ PYBIND11_UNARY_OPERATOR(pos, operator+, +l)
201
+ // WARNING: This usage of `abs` should only be done for existing STL overloads.
202
+ // Adding overloads directly in to the `std::` namespace is advised against:
203
+ // https://en.cppreference.com/w/cpp/language/extending_std
204
+ PYBIND11_UNARY_OPERATOR(abs, abs, std::abs(l))
205
+ PYBIND11_UNARY_OPERATOR(hash, hash, std::hash<L>()(l))
206
+ PYBIND11_UNARY_OPERATOR(invert, operator~, (~l))
207
+ PYBIND11_UNARY_OPERATOR(bool, operator!, !!l)
208
+ PYBIND11_UNARY_OPERATOR(int, int_, (int) l)
209
+ PYBIND11_UNARY_OPERATOR(float, float_, (double) l)
210
+
211
+ #undef PYBIND11_BINARY_OPERATOR
212
+ #undef PYBIND11_INPLACE_OPERATOR
213
+ #undef PYBIND11_UNARY_OPERATOR
214
+ PYBIND11_NAMESPACE_END(detail)
215
+
216
+ using detail::self;
217
+ // Add named operators so that they are accessible via `py::`.
218
+ using detail::hash;
219
+
220
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/options.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/options.h: global settings that are configurable at runtime.
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "detail/common.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+
16
+ class options {
17
+ public:
18
+ // Default RAII constructor, which leaves settings as they currently are.
19
+ options() : previous_state(global_state()) {}
20
+
21
+ // Class is non-copyable.
22
+ options(const options &) = delete;
23
+ options &operator=(const options &) = delete;
24
+
25
+ // Destructor, which restores settings that were in effect before.
26
+ ~options() { global_state() = previous_state; }
27
+
28
+ // Setter methods (affect the global state):
29
+
30
+ options &disable_user_defined_docstrings() & {
31
+ global_state().show_user_defined_docstrings = false;
32
+ return *this;
33
+ }
34
+
35
+ options &enable_user_defined_docstrings() & {
36
+ global_state().show_user_defined_docstrings = true;
37
+ return *this;
38
+ }
39
+
40
+ options &disable_function_signatures() & {
41
+ global_state().show_function_signatures = false;
42
+ return *this;
43
+ }
44
+
45
+ options &enable_function_signatures() & {
46
+ global_state().show_function_signatures = true;
47
+ return *this;
48
+ }
49
+
50
+ // Getter methods (return the global state):
51
+
52
+ static bool show_user_defined_docstrings() {
53
+ return global_state().show_user_defined_docstrings;
54
+ }
55
+
56
+ static bool show_function_signatures() { return global_state().show_function_signatures; }
57
+
58
+ // This type is not meant to be allocated on the heap.
59
+ void *operator new(size_t) = delete;
60
+
61
+ private:
62
+ struct state {
63
+ bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings.
64
+ bool show_function_signatures = true; //< Include auto-generated function signatures
65
+ // in docstrings.
66
+ };
67
+
68
+ static state &global_state() {
69
+ static state instance;
70
+ return instance;
71
+ }
72
+
73
+ state previous_state;
74
+ };
75
+
76
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/pybind11.h ADDED
The diff for this file is too large to render. See raw diff
 
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/pytypes.h ADDED
@@ -0,0 +1,2153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/pytypes.h: Convenience wrapper classes for basic Python types
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "detail/common.h"
13
+ #include "buffer_info.h"
14
+
15
+ #include <type_traits>
16
+ #include <utility>
17
+
18
+ #if defined(PYBIND11_HAS_OPTIONAL)
19
+ # include <optional>
20
+ #endif
21
+
22
+ #ifdef PYBIND11_HAS_STRING_VIEW
23
+ # include <string_view>
24
+ #endif
25
+
26
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
27
+
28
+ /* A few forward declarations */
29
+ class handle;
30
+ class object;
31
+ class str;
32
+ class iterator;
33
+ class type;
34
+ struct arg;
35
+ struct arg_v;
36
+
37
+ PYBIND11_NAMESPACE_BEGIN(detail)
38
+ class args_proxy;
39
+ bool isinstance_generic(handle obj, const std::type_info &tp);
40
+
41
+ // Accessor forward declarations
42
+ template <typename Policy>
43
+ class accessor;
44
+ namespace accessor_policies {
45
+ struct obj_attr;
46
+ struct str_attr;
47
+ struct generic_item;
48
+ struct sequence_item;
49
+ struct list_item;
50
+ struct tuple_item;
51
+ } // namespace accessor_policies
52
+ using obj_attr_accessor = accessor<accessor_policies::obj_attr>;
53
+ using str_attr_accessor = accessor<accessor_policies::str_attr>;
54
+ using item_accessor = accessor<accessor_policies::generic_item>;
55
+ using sequence_accessor = accessor<accessor_policies::sequence_item>;
56
+ using list_accessor = accessor<accessor_policies::list_item>;
57
+ using tuple_accessor = accessor<accessor_policies::tuple_item>;
58
+
59
+ /// Tag and check to identify a class which implements the Python object API
60
+ class pyobject_tag {};
61
+ template <typename T>
62
+ using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
63
+
64
+ /** \rst
65
+ A mixin class which adds common functions to `handle`, `object` and various accessors.
66
+ The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``.
67
+ \endrst */
68
+ template <typename Derived>
69
+ class object_api : public pyobject_tag {
70
+ const Derived &derived() const { return static_cast<const Derived &>(*this); }
71
+
72
+ public:
73
+ /** \rst
74
+ Return an iterator equivalent to calling ``iter()`` in Python. The object
75
+ must be a collection which supports the iteration protocol.
76
+ \endrst */
77
+ iterator begin() const;
78
+ /// Return a sentinel which ends iteration.
79
+ iterator end() const;
80
+
81
+ /** \rst
82
+ Return an internal functor to invoke the object's sequence protocol. Casting
83
+ the returned ``detail::item_accessor`` instance to a `handle` or `object`
84
+ subclass causes a corresponding call to ``__getitem__``. Assigning a `handle`
85
+ or `object` subclass causes a call to ``__setitem__``.
86
+ \endrst */
87
+ item_accessor operator[](handle key) const;
88
+ /// See above (the only difference is that they key is provided as a string literal)
89
+ item_accessor operator[](const char *key) const;
90
+
91
+ /** \rst
92
+ Return an internal functor to access the object's attributes. Casting the
93
+ returned ``detail::obj_attr_accessor`` instance to a `handle` or `object`
94
+ subclass causes a corresponding call to ``getattr``. Assigning a `handle`
95
+ or `object` subclass causes a call to ``setattr``.
96
+ \endrst */
97
+ obj_attr_accessor attr(handle key) const;
98
+ /// See above (the only difference is that they key is provided as a string literal)
99
+ str_attr_accessor attr(const char *key) const;
100
+
101
+ /** \rst
102
+ Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple``
103
+ or ``list`` for a function call. Applying another * to the result yields
104
+ ** unpacking, e.g. to unpack a dict as function keyword arguments.
105
+ See :ref:`calling_python_functions`.
106
+ \endrst */
107
+ args_proxy operator*() const;
108
+
109
+ /// Check if the given item is contained within this object, i.e. ``item in obj``.
110
+ template <typename T>
111
+ bool contains(T &&item) const;
112
+
113
+ /** \rst
114
+ Assuming the Python object is a function or implements the ``__call__``
115
+ protocol, ``operator()`` invokes the underlying function, passing an
116
+ arbitrary set of parameters. The result is returned as a `object` and
117
+ may need to be converted back into a Python object using `handle::cast()`.
118
+
119
+ When some of the arguments cannot be converted to Python objects, the
120
+ function will throw a `cast_error` exception. When the Python function
121
+ call fails, a `error_already_set` exception is thrown.
122
+ \endrst */
123
+ template <return_value_policy policy = return_value_policy::automatic_reference,
124
+ typename... Args>
125
+ object operator()(Args &&...args) const;
126
+ template <return_value_policy policy = return_value_policy::automatic_reference,
127
+ typename... Args>
128
+ PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
129
+ object call(Args &&...args) const;
130
+
131
+ /// Equivalent to ``obj is other`` in Python.
132
+ bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); }
133
+ /// Equivalent to ``obj is None`` in Python.
134
+ bool is_none() const { return derived().ptr() == Py_None; }
135
+ /// Equivalent to obj == other in Python
136
+ bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
137
+ bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
138
+ bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
139
+ bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
140
+ bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
141
+ bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
142
+
143
+ object operator-() const;
144
+ object operator~() const;
145
+ object operator+(object_api const &other) const;
146
+ object operator+=(object_api const &other) const;
147
+ object operator-(object_api const &other) const;
148
+ object operator-=(object_api const &other) const;
149
+ object operator*(object_api const &other) const;
150
+ object operator*=(object_api const &other) const;
151
+ object operator/(object_api const &other) const;
152
+ object operator/=(object_api const &other) const;
153
+ object operator|(object_api const &other) const;
154
+ object operator|=(object_api const &other) const;
155
+ object operator&(object_api const &other) const;
156
+ object operator&=(object_api const &other) const;
157
+ object operator^(object_api const &other) const;
158
+ object operator^=(object_api const &other) const;
159
+ object operator<<(object_api const &other) const;
160
+ object operator<<=(object_api const &other) const;
161
+ object operator>>(object_api const &other) const;
162
+ object operator>>=(object_api const &other) const;
163
+
164
+ PYBIND11_DEPRECATED("Use py::str(obj) instead")
165
+ pybind11::str str() const;
166
+
167
+ /// Get or set the object's docstring, i.e. ``obj.__doc__``.
168
+ str_attr_accessor doc() const;
169
+
170
+ /// Return the object's current reference count
171
+ int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); }
172
+
173
+ // TODO PYBIND11_DEPRECATED(
174
+ // "Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()")
175
+ handle get_type() const;
176
+
177
+ private:
178
+ bool rich_compare(object_api const &other, int value) const;
179
+ };
180
+
181
+ PYBIND11_NAMESPACE_END(detail)
182
+
183
+ /** \rst
184
+ Holds a reference to a Python object (no reference counting)
185
+
186
+ The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a
187
+ ``PyObject *`` in Python's C API). It does not perform any automatic reference
188
+ counting and merely provides a basic C++ interface to various Python API functions.
189
+
190
+ .. seealso::
191
+ The `object` class inherits from `handle` and adds automatic reference
192
+ counting features.
193
+ \endrst */
194
+ class handle : public detail::object_api<handle> {
195
+ public:
196
+ /// The default constructor creates a handle with a ``nullptr``-valued pointer
197
+ handle() = default;
198
+ /// Creates a ``handle`` from the given raw Python object pointer
199
+ // NOLINTNEXTLINE(google-explicit-constructor)
200
+ handle(PyObject *ptr) : m_ptr(ptr) {} // Allow implicit conversion from PyObject*
201
+
202
+ /// Return the underlying ``PyObject *`` pointer
203
+ PyObject *ptr() const { return m_ptr; }
204
+ PyObject *&ptr() { return m_ptr; }
205
+
206
+ /** \rst
207
+ Manually increase the reference count of the Python object. Usually, it is
208
+ preferable to use the `object` class which derives from `handle` and calls
209
+ this function automatically. Returns a reference to itself.
210
+ \endrst */
211
+ const handle &inc_ref() const & {
212
+ Py_XINCREF(m_ptr);
213
+ return *this;
214
+ }
215
+
216
+ /** \rst
217
+ Manually decrease the reference count of the Python object. Usually, it is
218
+ preferable to use the `object` class which derives from `handle` and calls
219
+ this function automatically. Returns a reference to itself.
220
+ \endrst */
221
+ const handle &dec_ref() const & {
222
+ Py_XDECREF(m_ptr);
223
+ return *this;
224
+ }
225
+
226
+ /** \rst
227
+ Attempt to cast the Python object into the given C++ type. A `cast_error`
228
+ will be throw upon failure.
229
+ \endrst */
230
+ template <typename T>
231
+ T cast() const;
232
+ /// Return ``true`` when the `handle` wraps a valid Python object
233
+ explicit operator bool() const { return m_ptr != nullptr; }
234
+ /** \rst
235
+ Deprecated: Check that the underlying pointers are the same.
236
+ Equivalent to ``obj1 is obj2`` in Python.
237
+ \endrst */
238
+ PYBIND11_DEPRECATED("Use obj1.is(obj2) instead")
239
+ bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }
240
+ PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead")
241
+ bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
242
+ PYBIND11_DEPRECATED("Use handle::operator bool() instead")
243
+ bool check() const { return m_ptr != nullptr; }
244
+
245
+ protected:
246
+ PyObject *m_ptr = nullptr;
247
+ };
248
+
249
+ /** \rst
250
+ Holds a reference to a Python object (with reference counting)
251
+
252
+ Like `handle`, the `object` class is a thin wrapper around an arbitrary Python
253
+ object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it
254
+ optionally increases the object's reference count upon construction, and it
255
+ *always* decreases the reference count when the `object` instance goes out of
256
+ scope and is destructed. When using `object` instances consistently, it is much
257
+ easier to get reference counting right at the first attempt.
258
+ \endrst */
259
+ class object : public handle {
260
+ public:
261
+ object() = default;
262
+ PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
263
+ object(handle h, bool is_borrowed) : handle(h) {
264
+ if (is_borrowed) {
265
+ inc_ref();
266
+ }
267
+ }
268
+ /// Copy constructor; always increases the reference count
269
+ object(const object &o) : handle(o) { inc_ref(); }
270
+ /// Move constructor; steals the object from ``other`` and preserves its reference count
271
+ object(object &&other) noexcept {
272
+ m_ptr = other.m_ptr;
273
+ other.m_ptr = nullptr;
274
+ }
275
+ /// Destructor; automatically calls `handle::dec_ref()`
276
+ ~object() { dec_ref(); }
277
+
278
+ /** \rst
279
+ Resets the internal pointer to ``nullptr`` without decreasing the
280
+ object's reference count. The function returns a raw handle to the original
281
+ Python object.
282
+ \endrst */
283
+ handle release() {
284
+ PyObject *tmp = m_ptr;
285
+ m_ptr = nullptr;
286
+ return handle(tmp);
287
+ }
288
+
289
+ object &operator=(const object &other) {
290
+ other.inc_ref();
291
+ // Use temporary variable to ensure `*this` remains valid while
292
+ // `Py_XDECREF` executes, in case `*this` is accessible from Python.
293
+ handle temp(m_ptr);
294
+ m_ptr = other.m_ptr;
295
+ temp.dec_ref();
296
+ return *this;
297
+ }
298
+
299
+ object &operator=(object &&other) noexcept {
300
+ if (this != &other) {
301
+ handle temp(m_ptr);
302
+ m_ptr = other.m_ptr;
303
+ other.m_ptr = nullptr;
304
+ temp.dec_ref();
305
+ }
306
+ return *this;
307
+ }
308
+
309
+ // Calling cast() on an object lvalue just copies (via handle::cast)
310
+ template <typename T>
311
+ T cast() const &;
312
+ // Calling on an object rvalue does a move, if needed and/or possible
313
+ template <typename T>
314
+ T cast() &&;
315
+
316
+ protected:
317
+ // Tags for choosing constructors from raw PyObject *
318
+ struct borrowed_t {};
319
+ struct stolen_t {};
320
+
321
+ /// @cond BROKEN
322
+ template <typename T>
323
+ friend T reinterpret_borrow(handle);
324
+ template <typename T>
325
+ friend T reinterpret_steal(handle);
326
+ /// @endcond
327
+
328
+ public:
329
+ // Only accessible from derived classes and the reinterpret_* functions
330
+ object(handle h, borrowed_t) : handle(h) { inc_ref(); }
331
+ object(handle h, stolen_t) : handle(h) {}
332
+ };
333
+
334
+ /** \rst
335
+ Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference.
336
+ The target type ``T`` must be `object` or one of its derived classes. The function
337
+ doesn't do any conversions or checks. It's up to the user to make sure that the
338
+ target type is correct.
339
+
340
+ .. code-block:: cpp
341
+
342
+ PyObject *p = PyList_GetItem(obj, index);
343
+ py::object o = reinterpret_borrow<py::object>(p);
344
+ // or
345
+ py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple`
346
+ \endrst */
347
+ template <typename T>
348
+ T reinterpret_borrow(handle h) {
349
+ return {h, object::borrowed_t{}};
350
+ }
351
+
352
+ /** \rst
353
+ Like `reinterpret_borrow`, but steals the reference.
354
+
355
+ .. code-block:: cpp
356
+
357
+ PyObject *p = PyObject_Str(obj);
358
+ py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str`
359
+ \endrst */
360
+ template <typename T>
361
+ T reinterpret_steal(handle h) {
362
+ return {h, object::stolen_t{}};
363
+ }
364
+
365
+ PYBIND11_NAMESPACE_BEGIN(detail)
366
+ std::string error_string();
367
+ PYBIND11_NAMESPACE_END(detail)
368
+
369
+ #if defined(_MSC_VER)
370
+ # pragma warning(push)
371
+ # pragma warning(disable : 4275 4251)
372
+ // warning C4275: An exported class was derived from a class that wasn't exported.
373
+ // Can be ignored when derived from a STL class.
374
+ #endif
375
+ /// Fetch and hold an error which was already set in Python. An instance of this is typically
376
+ /// thrown to propagate python-side errors back through C++ which can either be caught manually or
377
+ /// else falls back to the function dispatcher (which then raises the captured error back to
378
+ /// python).
379
+ class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::runtime_error {
380
+ public:
381
+ /// Constructs a new exception from the current Python error indicator, if any. The current
382
+ /// Python error indicator will be cleared.
383
+ error_already_set() : std::runtime_error(detail::error_string()) {
384
+ PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
385
+ }
386
+
387
+ error_already_set(const error_already_set &) = default;
388
+ error_already_set(error_already_set &&) = default;
389
+
390
+ inline ~error_already_set() override;
391
+
392
+ /// Give the currently-held error back to Python, if any. If there is currently a Python error
393
+ /// already set it is cleared first. After this call, the current object no longer stores the
394
+ /// error variables (but the `.what()` string is still available).
395
+ void restore() {
396
+ PyErr_Restore(m_type.release().ptr(), m_value.release().ptr(), m_trace.release().ptr());
397
+ }
398
+
399
+ /// If it is impossible to raise the currently-held error, such as in a destructor, we can
400
+ /// write it out using Python's unraisable hook (`sys.unraisablehook`). The error context
401
+ /// should be some object whose `repr()` helps identify the location of the error. Python
402
+ /// already knows the type and value of the error, so there is no need to repeat that. After
403
+ /// this call, the current object no longer stores the error variables, and neither does
404
+ /// Python.
405
+ void discard_as_unraisable(object err_context) {
406
+ restore();
407
+ PyErr_WriteUnraisable(err_context.ptr());
408
+ }
409
+ /// An alternate version of `discard_as_unraisable()`, where a string provides information on
410
+ /// the location of the error. For example, `__func__` could be helpful.
411
+ void discard_as_unraisable(const char *err_context) {
412
+ discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));
413
+ }
414
+
415
+ // Does nothing; provided for backwards compatibility.
416
+ PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
417
+ void clear() {}
418
+
419
+ /// Check if the currently trapped error type matches the given Python exception class (or a
420
+ /// subclass thereof). May also be passed a tuple to search for any exception class matches in
421
+ /// the given tuple.
422
+ bool matches(handle exc) const {
423
+ return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0);
424
+ }
425
+
426
+ const object &type() const { return m_type; }
427
+ const object &value() const { return m_value; }
428
+ const object &trace() const { return m_trace; }
429
+
430
+ private:
431
+ object m_type, m_value, m_trace;
432
+ };
433
+ #if defined(_MSC_VER)
434
+ # pragma warning(pop)
435
+ #endif
436
+
437
+ #if PY_VERSION_HEX >= 0x03030000
438
+
439
+ /// Replaces the current Python error indicator with the chosen error, performing a
440
+ /// 'raise from' to indicate that the chosen error was caused by the original error.
441
+ inline void raise_from(PyObject *type, const char *message) {
442
+ // Based on _PyErr_FormatVFromCause:
443
+ // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405
444
+ // See https://github.com/pybind/pybind11/pull/2112 for details.
445
+ PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr;
446
+
447
+ assert(PyErr_Occurred());
448
+ PyErr_Fetch(&exc, &val, &tb);
449
+ PyErr_NormalizeException(&exc, &val, &tb);
450
+ if (tb != nullptr) {
451
+ PyException_SetTraceback(val, tb);
452
+ Py_DECREF(tb);
453
+ }
454
+ Py_DECREF(exc);
455
+ assert(!PyErr_Occurred());
456
+
457
+ PyErr_SetString(type, message);
458
+
459
+ PyErr_Fetch(&exc, &val2, &tb);
460
+ PyErr_NormalizeException(&exc, &val2, &tb);
461
+ Py_INCREF(val);
462
+ PyException_SetCause(val2, val);
463
+ PyException_SetContext(val2, val);
464
+ PyErr_Restore(exc, val2, tb);
465
+ }
466
+
467
+ /// Sets the current Python error indicator with the chosen error, performing a 'raise from'
468
+ /// from the error contained in error_already_set to indicate that the chosen error was
469
+ /// caused by the original error. After this function is called error_already_set will
470
+ /// no longer contain an error.
471
+ inline void raise_from(error_already_set &err, PyObject *type, const char *message) {
472
+ err.restore();
473
+ raise_from(type, message);
474
+ }
475
+
476
+ #endif
477
+
478
+ /** \defgroup python_builtins const_name
479
+ Unless stated otherwise, the following C++ functions behave the same
480
+ as their Python counterparts.
481
+ */
482
+
483
+ /** \ingroup python_builtins
484
+ \rst
485
+ Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of
486
+ `object` or a class which was exposed to Python as ``py::class_<T>``.
487
+ \endrst */
488
+ template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0>
489
+ bool isinstance(handle obj) {
490
+ return T::check_(obj);
491
+ }
492
+
493
+ template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0>
494
+ bool isinstance(handle obj) {
495
+ return detail::isinstance_generic(obj, typeid(T));
496
+ }
497
+
498
+ template <>
499
+ inline bool isinstance<handle>(handle) = delete;
500
+ template <>
501
+ inline bool isinstance<object>(handle obj) {
502
+ return obj.ptr() != nullptr;
503
+ }
504
+
505
+ /// \ingroup python_builtins
506
+ /// Return true if ``obj`` is an instance of the ``type``.
507
+ inline bool isinstance(handle obj, handle type) {
508
+ const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
509
+ if (result == -1) {
510
+ throw error_already_set();
511
+ }
512
+ return result != 0;
513
+ }
514
+
515
+ /// \addtogroup python_builtins
516
+ /// @{
517
+ inline bool hasattr(handle obj, handle name) {
518
+ return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
519
+ }
520
+
521
+ inline bool hasattr(handle obj, const char *name) {
522
+ return PyObject_HasAttrString(obj.ptr(), name) == 1;
523
+ }
524
+
525
+ inline void delattr(handle obj, handle name) {
526
+ if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) {
527
+ throw error_already_set();
528
+ }
529
+ }
530
+
531
+ inline void delattr(handle obj, const char *name) {
532
+ if (PyObject_DelAttrString(obj.ptr(), name) != 0) {
533
+ throw error_already_set();
534
+ }
535
+ }
536
+
537
+ inline object getattr(handle obj, handle name) {
538
+ PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
539
+ if (!result) {
540
+ throw error_already_set();
541
+ }
542
+ return reinterpret_steal<object>(result);
543
+ }
544
+
545
+ inline object getattr(handle obj, const char *name) {
546
+ PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
547
+ if (!result) {
548
+ throw error_already_set();
549
+ }
550
+ return reinterpret_steal<object>(result);
551
+ }
552
+
553
+ inline object getattr(handle obj, handle name, handle default_) {
554
+ if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
555
+ return reinterpret_steal<object>(result);
556
+ }
557
+ PyErr_Clear();
558
+ return reinterpret_borrow<object>(default_);
559
+ }
560
+
561
+ inline object getattr(handle obj, const char *name, handle default_) {
562
+ if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
563
+ return reinterpret_steal<object>(result);
564
+ }
565
+ PyErr_Clear();
566
+ return reinterpret_borrow<object>(default_);
567
+ }
568
+
569
+ inline void setattr(handle obj, handle name, handle value) {
570
+ if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) {
571
+ throw error_already_set();
572
+ }
573
+ }
574
+
575
+ inline void setattr(handle obj, const char *name, handle value) {
576
+ if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) {
577
+ throw error_already_set();
578
+ }
579
+ }
580
+
581
+ inline ssize_t hash(handle obj) {
582
+ auto h = PyObject_Hash(obj.ptr());
583
+ if (h == -1) {
584
+ throw error_already_set();
585
+ }
586
+ return h;
587
+ }
588
+
589
+ /// @} python_builtins
590
+
591
+ PYBIND11_NAMESPACE_BEGIN(detail)
592
+ inline handle get_function(handle value) {
593
+ if (value) {
594
+ #if PY_MAJOR_VERSION >= 3
595
+ if (PyInstanceMethod_Check(value.ptr())) {
596
+ value = PyInstanceMethod_GET_FUNCTION(value.ptr());
597
+ } else
598
+ #endif
599
+ if (PyMethod_Check(value.ptr())) {
600
+ value = PyMethod_GET_FUNCTION(value.ptr());
601
+ }
602
+ }
603
+ return value;
604
+ }
605
+
606
+ // Reimplementation of python's dict helper functions to ensure that exceptions
607
+ // aren't swallowed (see #2862)
608
+
609
+ // copied from cpython _PyDict_GetItemStringWithError
610
+ inline PyObject *dict_getitemstring(PyObject *v, const char *key) {
611
+ #if PY_MAJOR_VERSION >= 3
612
+ PyObject *kv = nullptr, *rv = nullptr;
613
+ kv = PyUnicode_FromString(key);
614
+ if (kv == NULL) {
615
+ throw error_already_set();
616
+ }
617
+
618
+ rv = PyDict_GetItemWithError(v, kv);
619
+ Py_DECREF(kv);
620
+ if (rv == NULL && PyErr_Occurred()) {
621
+ throw error_already_set();
622
+ }
623
+ return rv;
624
+ #else
625
+ return PyDict_GetItemString(v, key);
626
+ #endif
627
+ }
628
+
629
+ inline PyObject *dict_getitem(PyObject *v, PyObject *key) {
630
+ #if PY_MAJOR_VERSION >= 3
631
+ PyObject *rv = PyDict_GetItemWithError(v, key);
632
+ if (rv == NULL && PyErr_Occurred()) {
633
+ throw error_already_set();
634
+ }
635
+ return rv;
636
+ #else
637
+ return PyDict_GetItem(v, key);
638
+ #endif
639
+ }
640
+
641
+ // Helper aliases/functions to support implicit casting of values given to python
642
+ // accessors/methods. When given a pyobject, this simply returns the pyobject as-is; for other C++
643
+ // type, the value goes through pybind11::cast(obj) to convert it to an `object`.
644
+ template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0>
645
+ auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) {
646
+ return std::forward<T>(o);
647
+ }
648
+ // The following casting version is implemented in cast.h:
649
+ template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0>
650
+ object object_or_cast(T &&o);
651
+ // Match a PyObject*, which we want to convert directly to handle via its converting constructor
652
+ inline handle object_or_cast(PyObject *ptr) { return ptr; }
653
+
654
+ #if defined(_MSC_VER) && _MSC_VER < 1920
655
+ # pragma warning(push)
656
+ # pragma warning(disable : 4522) // warning C4522: multiple assignment operators specified
657
+ #endif
658
+ template <typename Policy>
659
+ class accessor : public object_api<accessor<Policy>> {
660
+ using key_type = typename Policy::key_type;
661
+
662
+ public:
663
+ accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {}
664
+ accessor(const accessor &) = default;
665
+ accessor(accessor &&) noexcept = default;
666
+
667
+ // accessor overload required to override default assignment operator (templates are not
668
+ // allowed to replace default compiler-generated assignments).
669
+ void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
670
+ void operator=(const accessor &a) & { operator=(handle(a)); }
671
+
672
+ template <typename T>
673
+ void operator=(T &&value) && {
674
+ Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
675
+ }
676
+ template <typename T>
677
+ void operator=(T &&value) & {
678
+ get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value)));
679
+ }
680
+
681
+ template <typename T = Policy>
682
+ PYBIND11_DEPRECATED(
683
+ "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
684
+ explicit
685
+ operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value
686
+ || std::is_same<T, accessor_policies::obj_attr>::value,
687
+ bool>() const {
688
+ return hasattr(obj, key);
689
+ }
690
+ template <typename T = Policy>
691
+ PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
692
+ explicit
693
+ operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {
694
+ return obj.contains(key);
695
+ }
696
+
697
+ // NOLINTNEXTLINE(google-explicit-constructor)
698
+ operator object() const { return get_cache(); }
699
+ PyObject *ptr() const { return get_cache().ptr(); }
700
+ template <typename T>
701
+ T cast() const {
702
+ return get_cache().template cast<T>();
703
+ }
704
+
705
+ private:
706
+ object &get_cache() const {
707
+ if (!cache) {
708
+ cache = Policy::get(obj, key);
709
+ }
710
+ return cache;
711
+ }
712
+
713
+ private:
714
+ handle obj;
715
+ key_type key;
716
+ mutable object cache;
717
+ };
718
+ #if defined(_MSC_VER) && _MSC_VER < 1920
719
+ # pragma warning(pop)
720
+ #endif
721
+
722
+ PYBIND11_NAMESPACE_BEGIN(accessor_policies)
723
+ struct obj_attr {
724
+ using key_type = object;
725
+ static object get(handle obj, handle key) { return getattr(obj, key); }
726
+ static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }
727
+ };
728
+
729
+ struct str_attr {
730
+ using key_type = const char *;
731
+ static object get(handle obj, const char *key) { return getattr(obj, key); }
732
+ static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }
733
+ };
734
+
735
+ struct generic_item {
736
+ using key_type = object;
737
+
738
+ static object get(handle obj, handle key) {
739
+ PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
740
+ if (!result) {
741
+ throw error_already_set();
742
+ }
743
+ return reinterpret_steal<object>(result);
744
+ }
745
+
746
+ static void set(handle obj, handle key, handle val) {
747
+ if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) {
748
+ throw error_already_set();
749
+ }
750
+ }
751
+ };
752
+
753
+ struct sequence_item {
754
+ using key_type = size_t;
755
+
756
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
757
+ static object get(handle obj, const IdxType &index) {
758
+ PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index));
759
+ if (!result) {
760
+ throw error_already_set();
761
+ }
762
+ return reinterpret_steal<object>(result);
763
+ }
764
+
765
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
766
+ static void set(handle obj, const IdxType &index, handle val) {
767
+ // PySequence_SetItem does not steal a reference to 'val'
768
+ if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) {
769
+ throw error_already_set();
770
+ }
771
+ }
772
+ };
773
+
774
+ struct list_item {
775
+ using key_type = size_t;
776
+
777
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
778
+ static object get(handle obj, const IdxType &index) {
779
+ PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index));
780
+ if (!result) {
781
+ throw error_already_set();
782
+ }
783
+ return reinterpret_borrow<object>(result);
784
+ }
785
+
786
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
787
+ static void set(handle obj, const IdxType &index, handle val) {
788
+ // PyList_SetItem steals a reference to 'val'
789
+ if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
790
+ throw error_already_set();
791
+ }
792
+ }
793
+ };
794
+
795
+ struct tuple_item {
796
+ using key_type = size_t;
797
+
798
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
799
+ static object get(handle obj, const IdxType &index) {
800
+ PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index));
801
+ if (!result) {
802
+ throw error_already_set();
803
+ }
804
+ return reinterpret_borrow<object>(result);
805
+ }
806
+
807
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
808
+ static void set(handle obj, const IdxType &index, handle val) {
809
+ // PyTuple_SetItem steals a reference to 'val'
810
+ if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
811
+ throw error_already_set();
812
+ }
813
+ }
814
+ };
815
+ PYBIND11_NAMESPACE_END(accessor_policies)
816
+
817
+ /// STL iterator template used for tuple, list, sequence and dict
818
+ template <typename Policy>
819
+ class generic_iterator : public Policy {
820
+ using It = generic_iterator;
821
+
822
+ public:
823
+ using difference_type = ssize_t;
824
+ using iterator_category = typename Policy::iterator_category;
825
+ using value_type = typename Policy::value_type;
826
+ using reference = typename Policy::reference;
827
+ using pointer = typename Policy::pointer;
828
+
829
+ generic_iterator() = default;
830
+ generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {}
831
+
832
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
833
+ reference operator*() const { return Policy::dereference(); }
834
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
835
+ reference operator[](difference_type n) const { return *(*this + n); }
836
+ pointer operator->() const { return **this; }
837
+
838
+ It &operator++() {
839
+ Policy::increment();
840
+ return *this;
841
+ }
842
+ It operator++(int) {
843
+ auto copy = *this;
844
+ Policy::increment();
845
+ return copy;
846
+ }
847
+ It &operator--() {
848
+ Policy::decrement();
849
+ return *this;
850
+ }
851
+ It operator--(int) {
852
+ auto copy = *this;
853
+ Policy::decrement();
854
+ return copy;
855
+ }
856
+ It &operator+=(difference_type n) {
857
+ Policy::advance(n);
858
+ return *this;
859
+ }
860
+ It &operator-=(difference_type n) {
861
+ Policy::advance(-n);
862
+ return *this;
863
+ }
864
+
865
+ friend It operator+(const It &a, difference_type n) {
866
+ auto copy = a;
867
+ return copy += n;
868
+ }
869
+ friend It operator+(difference_type n, const It &b) { return b + n; }
870
+ friend It operator-(const It &a, difference_type n) {
871
+ auto copy = a;
872
+ return copy -= n;
873
+ }
874
+ friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
875
+
876
+ friend bool operator==(const It &a, const It &b) { return a.equal(b); }
877
+ friend bool operator!=(const It &a, const It &b) { return !(a == b); }
878
+ friend bool operator<(const It &a, const It &b) { return b - a > 0; }
879
+ friend bool operator>(const It &a, const It &b) { return b < a; }
880
+ friend bool operator>=(const It &a, const It &b) { return !(a < b); }
881
+ friend bool operator<=(const It &a, const It &b) { return !(a > b); }
882
+ };
883
+
884
+ PYBIND11_NAMESPACE_BEGIN(iterator_policies)
885
+ /// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers
886
+ template <typename T>
887
+ struct arrow_proxy {
888
+ T value;
889
+
890
+ // NOLINTNEXTLINE(google-explicit-constructor)
891
+ arrow_proxy(T &&value) noexcept : value(std::move(value)) {}
892
+ T *operator->() const { return &value; }
893
+ };
894
+
895
+ /// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS``
896
+ class sequence_fast_readonly {
897
+ protected:
898
+ using iterator_category = std::random_access_iterator_tag;
899
+ using value_type = handle;
900
+ using reference = const handle; // PR #3263
901
+ using pointer = arrow_proxy<const handle>;
902
+
903
+ sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {}
904
+
905
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
906
+ reference dereference() const { return *ptr; }
907
+ void increment() { ++ptr; }
908
+ void decrement() { --ptr; }
909
+ void advance(ssize_t n) { ptr += n; }
910
+ bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
911
+ ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }
912
+
913
+ private:
914
+ PyObject **ptr;
915
+ };
916
+
917
+ /// Full read and write access using the sequence protocol: see ``detail::sequence_accessor``
918
+ class sequence_slow_readwrite {
919
+ protected:
920
+ using iterator_category = std::random_access_iterator_tag;
921
+ using value_type = object;
922
+ using reference = sequence_accessor;
923
+ using pointer = arrow_proxy<const sequence_accessor>;
924
+
925
+ sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {}
926
+
927
+ reference dereference() const { return {obj, static_cast<size_t>(index)}; }
928
+ void increment() { ++index; }
929
+ void decrement() { --index; }
930
+ void advance(ssize_t n) { index += n; }
931
+ bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
932
+ ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }
933
+
934
+ private:
935
+ handle obj;
936
+ ssize_t index;
937
+ };
938
+
939
+ /// Python's dictionary protocol permits this to be a forward iterator
940
+ class dict_readonly {
941
+ protected:
942
+ using iterator_category = std::forward_iterator_tag;
943
+ using value_type = std::pair<handle, handle>;
944
+ using reference = const value_type; // PR #3263
945
+ using pointer = arrow_proxy<const value_type>;
946
+
947
+ dict_readonly() = default;
948
+ dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
949
+
950
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
951
+ reference dereference() const { return {key, value}; }
952
+ void increment() {
953
+ if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) {
954
+ pos = -1;
955
+ }
956
+ }
957
+ bool equal(const dict_readonly &b) const { return pos == b.pos; }
958
+
959
+ private:
960
+ handle obj;
961
+ PyObject *key = nullptr, *value = nullptr;
962
+ ssize_t pos = -1;
963
+ };
964
+ PYBIND11_NAMESPACE_END(iterator_policies)
965
+
966
+ #if !defined(PYPY_VERSION)
967
+ using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
968
+ using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
969
+ #else
970
+ using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
971
+ using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
972
+ #endif
973
+
974
+ using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
975
+ using dict_iterator = generic_iterator<iterator_policies::dict_readonly>;
976
+
977
+ inline bool PyIterable_Check(PyObject *obj) {
978
+ PyObject *iter = PyObject_GetIter(obj);
979
+ if (iter) {
980
+ Py_DECREF(iter);
981
+ return true;
982
+ }
983
+ PyErr_Clear();
984
+ return false;
985
+ }
986
+
987
+ inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
988
+ inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
989
+
990
+ #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
991
+ inline bool PyUnicode_Check_Permissive(PyObject *o) {
992
+ return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o);
993
+ }
994
+ # define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
995
+ #else
996
+ # define PYBIND11_STR_CHECK_FUN PyUnicode_Check
997
+ #endif
998
+
999
+ inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; }
1000
+
1001
+ class kwargs_proxy : public handle {
1002
+ public:
1003
+ explicit kwargs_proxy(handle h) : handle(h) {}
1004
+ };
1005
+
1006
+ class args_proxy : public handle {
1007
+ public:
1008
+ explicit args_proxy(handle h) : handle(h) {}
1009
+ kwargs_proxy operator*() const { return kwargs_proxy(*this); }
1010
+ };
1011
+
1012
+ /// Python argument categories (using PEP 448 terms)
1013
+ template <typename T>
1014
+ using is_keyword = std::is_base_of<arg, T>;
1015
+ template <typename T>
1016
+ using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
1017
+ template <typename T>
1018
+ using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
1019
+ template <typename T>
1020
+ using is_positional = satisfies_none_of<T, is_keyword, is_s_unpacking, is_ds_unpacking>;
1021
+ template <typename T>
1022
+ using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>;
1023
+
1024
+ // Call argument collector forward declarations
1025
+ template <return_value_policy policy = return_value_policy::automatic_reference>
1026
+ class simple_collector;
1027
+ template <return_value_policy policy = return_value_policy::automatic_reference>
1028
+ class unpacking_collector;
1029
+
1030
+ PYBIND11_NAMESPACE_END(detail)
1031
+
1032
+ // TODO: After the deprecated constructors are removed, this macro can be simplified by
1033
+ // inheriting ctors: `using Parent::Parent`. It's not an option right now because
1034
+ // the `using` statement triggers the parent deprecation warning even if the ctor
1035
+ // isn't even used.
1036
+ #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1037
+ public: \
1038
+ PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \
1039
+ Name(handle h, bool is_borrowed) \
1040
+ : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \
1041
+ Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \
1042
+ Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \
1043
+ PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
1044
+ bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \
1045
+ static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
1046
+ template <typename Policy_> /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1047
+ Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {}
1048
+
1049
+ #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1050
+ PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1051
+ /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
1052
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1053
+ Name(const object &o) \
1054
+ : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1055
+ if (!m_ptr) \
1056
+ throw error_already_set(); \
1057
+ } \
1058
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1059
+ Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1060
+ if (!m_ptr) \
1061
+ throw error_already_set(); \
1062
+ }
1063
+
1064
+ #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \
1065
+ PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1066
+ Name() : Parent() {}
1067
+
1068
+ #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \
1069
+ ::pybind11::type_error("Object of type '" \
1070
+ + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \
1071
+ + "' is not an instance of '" #Name "'")
1072
+
1073
+ #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
1074
+ PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1075
+ /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
1076
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1077
+ Name(const object &o) : Parent(o) { \
1078
+ if (m_ptr && !check_(m_ptr)) \
1079
+ throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1080
+ } \
1081
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1082
+ Name(object &&o) : Parent(std::move(o)) { \
1083
+ if (m_ptr && !check_(m_ptr)) \
1084
+ throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1085
+ }
1086
+
1087
+ #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
1088
+ PYBIND11_OBJECT(Name, Parent, CheckFun) \
1089
+ Name() : Parent() {}
1090
+
1091
+ /// \addtogroup pytypes
1092
+ /// @{
1093
+
1094
+ /** \rst
1095
+ Wraps a Python iterator so that it can also be used as a C++ input iterator
1096
+
1097
+ Caveat: copying an iterator does not (and cannot) clone the internal
1098
+ state of the Python iterable. This also applies to the post-increment
1099
+ operator. This iterator should only be used to retrieve the current
1100
+ value using ``operator*()``.
1101
+ \endrst */
1102
+ class iterator : public object {
1103
+ public:
1104
+ using iterator_category = std::input_iterator_tag;
1105
+ using difference_type = ssize_t;
1106
+ using value_type = handle;
1107
+ using reference = const handle; // PR #3263
1108
+ using pointer = const handle *;
1109
+
1110
+ PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
1111
+
1112
+ iterator &operator++() {
1113
+ advance();
1114
+ return *this;
1115
+ }
1116
+
1117
+ iterator operator++(int) {
1118
+ auto rv = *this;
1119
+ advance();
1120
+ return rv;
1121
+ }
1122
+
1123
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1124
+ reference operator*() const {
1125
+ if (m_ptr && !value.ptr()) {
1126
+ auto &self = const_cast<iterator &>(*this);
1127
+ self.advance();
1128
+ }
1129
+ return value;
1130
+ }
1131
+
1132
+ pointer operator->() const {
1133
+ operator*();
1134
+ return &value;
1135
+ }
1136
+
1137
+ /** \rst
1138
+ The value which marks the end of the iteration. ``it == iterator::sentinel()``
1139
+ is equivalent to catching ``StopIteration`` in Python.
1140
+
1141
+ .. code-block:: cpp
1142
+
1143
+ void foo(py::iterator it) {
1144
+ while (it != py::iterator::sentinel()) {
1145
+ // use `*it`
1146
+ ++it;
1147
+ }
1148
+ }
1149
+ \endrst */
1150
+ static iterator sentinel() { return {}; }
1151
+
1152
+ friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }
1153
+ friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }
1154
+
1155
+ private:
1156
+ void advance() {
1157
+ value = reinterpret_steal<object>(PyIter_Next(m_ptr));
1158
+ if (PyErr_Occurred()) {
1159
+ throw error_already_set();
1160
+ }
1161
+ }
1162
+
1163
+ private:
1164
+ object value = {};
1165
+ };
1166
+
1167
+ class type : public object {
1168
+ public:
1169
+ PYBIND11_OBJECT(type, object, PyType_Check)
1170
+
1171
+ /// Return a type handle from a handle or an object
1172
+ static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); }
1173
+
1174
+ /// Return a type object from a handle or an object
1175
+ static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }
1176
+
1177
+ // Defined in pybind11/cast.h
1178
+ /// Convert C++ type to handle if previously registered. Does not convert
1179
+ /// standard types, like int, float. etc. yet.
1180
+ /// See https://github.com/pybind/pybind11/issues/2486
1181
+ template <typename T>
1182
+ static handle handle_of();
1183
+
1184
+ /// Convert C++ type to type if previously registered. Does not convert
1185
+ /// standard types, like int, float. etc. yet.
1186
+ /// See https://github.com/pybind/pybind11/issues/2486
1187
+ template <typename T>
1188
+ static type of() {
1189
+ return type(type::handle_of<T>(), borrowed_t{});
1190
+ }
1191
+ };
1192
+
1193
+ class iterable : public object {
1194
+ public:
1195
+ PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)
1196
+ };
1197
+
1198
+ class bytes;
1199
+
1200
+ class str : public object {
1201
+ public:
1202
+ PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str)
1203
+
1204
+ template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1205
+ str(const char *c, const SzType &n)
1206
+ : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1207
+ if (!m_ptr) {
1208
+ pybind11_fail("Could not allocate string object!");
1209
+ }
1210
+ }
1211
+
1212
+ // 'explicit' is explicitly omitted from the following constructors to allow implicit
1213
+ // conversion to py::str from C++ string-like objects
1214
+ // NOLINTNEXTLINE(google-explicit-constructor)
1215
+ str(const char *c = "") : object(PyUnicode_FromString(c), stolen_t{}) {
1216
+ if (!m_ptr) {
1217
+ pybind11_fail("Could not allocate string object!");
1218
+ }
1219
+ }
1220
+
1221
+ // NOLINTNEXTLINE(google-explicit-constructor)
1222
+ str(const std::string &s) : str(s.data(), s.size()) {}
1223
+
1224
+ #ifdef PYBIND11_HAS_STRING_VIEW
1225
+ // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1226
+ template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
1227
+ // NOLINTNEXTLINE(google-explicit-constructor)
1228
+ str(T s) : str(s.data(), s.size()) {}
1229
+
1230
+ # ifdef PYBIND11_HAS_U8STRING
1231
+ // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char)
1232
+ // NOLINTNEXTLINE(google-explicit-constructor)
1233
+ str(std::u8string_view s) : str(reinterpret_cast<const char *>(s.data()), s.size()) {}
1234
+ # endif
1235
+
1236
+ #endif
1237
+
1238
+ explicit str(const bytes &b);
1239
+
1240
+ /** \rst
1241
+ Return a string representation of the object. This is analogous to
1242
+ the ``str()`` function in Python.
1243
+ \endrst */
1244
+ explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) {
1245
+ if (!m_ptr) {
1246
+ throw error_already_set();
1247
+ }
1248
+ }
1249
+
1250
+ // NOLINTNEXTLINE(google-explicit-constructor)
1251
+ operator std::string() const {
1252
+ object temp = *this;
1253
+ if (PyUnicode_Check(m_ptr)) {
1254
+ temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
1255
+ if (!temp) {
1256
+ throw error_already_set();
1257
+ }
1258
+ }
1259
+ char *buffer = nullptr;
1260
+ ssize_t length = 0;
1261
+ if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) {
1262
+ pybind11_fail("Unable to extract string contents! (invalid type)");
1263
+ }
1264
+ return std::string(buffer, (size_t) length);
1265
+ }
1266
+
1267
+ template <typename... Args>
1268
+ str format(Args &&...args) const {
1269
+ return attr("format")(std::forward<Args>(args)...);
1270
+ }
1271
+
1272
+ private:
1273
+ /// Return string representation -- always returns a new reference, even if already a str
1274
+ static PyObject *raw_str(PyObject *op) {
1275
+ PyObject *str_value = PyObject_Str(op);
1276
+ #if PY_MAJOR_VERSION < 3
1277
+ if (!str_value)
1278
+ throw error_already_set();
1279
+ PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
1280
+ Py_XDECREF(str_value);
1281
+ str_value = unicode;
1282
+ #endif
1283
+ return str_value;
1284
+ }
1285
+ };
1286
+ /// @} pytypes
1287
+
1288
+ inline namespace literals {
1289
+ /** \rst
1290
+ String literal version of `str`
1291
+ \endrst */
1292
+ inline str operator"" _s(const char *s, size_t size) { return {s, size}; }
1293
+ } // namespace literals
1294
+
1295
+ /// \addtogroup pytypes
1296
+ /// @{
1297
+ class bytes : public object {
1298
+ public:
1299
+ PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK)
1300
+
1301
+ // Allow implicit conversion:
1302
+ // NOLINTNEXTLINE(google-explicit-constructor)
1303
+ bytes(const char *c = "") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
1304
+ if (!m_ptr) {
1305
+ pybind11_fail("Could not allocate bytes object!");
1306
+ }
1307
+ }
1308
+
1309
+ template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1310
+ bytes(const char *c, const SzType &n)
1311
+ : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) {
1312
+ if (!m_ptr) {
1313
+ pybind11_fail("Could not allocate bytes object!");
1314
+ }
1315
+ }
1316
+
1317
+ // Allow implicit conversion:
1318
+ // NOLINTNEXTLINE(google-explicit-constructor)
1319
+ bytes(const std::string &s) : bytes(s.data(), s.size()) {}
1320
+
1321
+ explicit bytes(const pybind11::str &s);
1322
+
1323
+ // NOLINTNEXTLINE(google-explicit-constructor)
1324
+ operator std::string() const {
1325
+ char *buffer = nullptr;
1326
+ ssize_t length = 0;
1327
+ if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length)) {
1328
+ pybind11_fail("Unable to extract bytes contents!");
1329
+ }
1330
+ return std::string(buffer, (size_t) length);
1331
+ }
1332
+
1333
+ #ifdef PYBIND11_HAS_STRING_VIEW
1334
+ // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1335
+ template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
1336
+ // NOLINTNEXTLINE(google-explicit-constructor)
1337
+ bytes(T s) : bytes(s.data(), s.size()) {}
1338
+
1339
+ // Obtain a string view that views the current `bytes` buffer value. Note that this is only
1340
+ // valid so long as the `bytes` instance remains alive and so generally should not outlive the
1341
+ // lifetime of the `bytes` instance.
1342
+ // NOLINTNEXTLINE(google-explicit-constructor)
1343
+ operator std::string_view() const {
1344
+ char *buffer = nullptr;
1345
+ ssize_t length = 0;
1346
+ if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length)) {
1347
+ pybind11_fail("Unable to extract bytes contents!");
1348
+ }
1349
+ return {buffer, static_cast<size_t>(length)};
1350
+ }
1351
+ #endif
1352
+ };
1353
+ // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1354
+ // are included in the doxygen group; close here and reopen after as a workaround
1355
+ /// @} pytypes
1356
+
1357
+ inline bytes::bytes(const pybind11::str &s) {
1358
+ object temp = s;
1359
+ if (PyUnicode_Check(s.ptr())) {
1360
+ temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
1361
+ if (!temp) {
1362
+ pybind11_fail("Unable to extract string contents! (encoding issue)");
1363
+ }
1364
+ }
1365
+ char *buffer = nullptr;
1366
+ ssize_t length = 0;
1367
+ if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) {
1368
+ pybind11_fail("Unable to extract string contents! (invalid type)");
1369
+ }
1370
+ auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
1371
+ if (!obj) {
1372
+ pybind11_fail("Could not allocate bytes object!");
1373
+ }
1374
+ m_ptr = obj.release().ptr();
1375
+ }
1376
+
1377
+ inline str::str(const bytes &b) {
1378
+ char *buffer = nullptr;
1379
+ ssize_t length = 0;
1380
+ if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length)) {
1381
+ pybind11_fail("Unable to extract bytes contents!");
1382
+ }
1383
+ auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length));
1384
+ if (!obj) {
1385
+ pybind11_fail("Could not allocate string object!");
1386
+ }
1387
+ m_ptr = obj.release().ptr();
1388
+ }
1389
+
1390
+ /// \addtogroup pytypes
1391
+ /// @{
1392
+ class bytearray : public object {
1393
+ public:
1394
+ PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject)
1395
+
1396
+ template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1397
+ bytearray(const char *c, const SzType &n)
1398
+ : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1399
+ if (!m_ptr) {
1400
+ pybind11_fail("Could not allocate bytearray object!");
1401
+ }
1402
+ }
1403
+
1404
+ bytearray() : bytearray("", 0) {}
1405
+
1406
+ explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {}
1407
+
1408
+ size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
1409
+
1410
+ explicit operator std::string() const {
1411
+ char *buffer = PyByteArray_AS_STRING(m_ptr);
1412
+ ssize_t size = PyByteArray_GET_SIZE(m_ptr);
1413
+ return std::string(buffer, static_cast<size_t>(size));
1414
+ }
1415
+ };
1416
+ // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1417
+ // are included in the doxygen group; close here and reopen after as a workaround
1418
+ /// @} pytypes
1419
+
1420
+ /// \addtogroup pytypes
1421
+ /// @{
1422
+ class none : public object {
1423
+ public:
1424
+ PYBIND11_OBJECT(none, object, detail::PyNone_Check)
1425
+ none() : object(Py_None, borrowed_t{}) {}
1426
+ };
1427
+
1428
+ class ellipsis : public object {
1429
+ public:
1430
+ PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)
1431
+ ellipsis() : object(Py_Ellipsis, borrowed_t{}) {}
1432
+ };
1433
+
1434
+ class bool_ : public object {
1435
+ public:
1436
+ PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
1437
+ bool_() : object(Py_False, borrowed_t{}) {}
1438
+ // Allow implicit conversion from and to `bool`:
1439
+ // NOLINTNEXTLINE(google-explicit-constructor)
1440
+ bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {}
1441
+ // NOLINTNEXTLINE(google-explicit-constructor)
1442
+ operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; }
1443
+
1444
+ private:
1445
+ /// Return the truth value of an object -- always returns a new reference
1446
+ static PyObject *raw_bool(PyObject *op) {
1447
+ const auto value = PyObject_IsTrue(op);
1448
+ if (value == -1) {
1449
+ return nullptr;
1450
+ }
1451
+ return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr();
1452
+ }
1453
+ };
1454
+
1455
+ PYBIND11_NAMESPACE_BEGIN(detail)
1456
+ // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1;
1457
+ // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).
1458
+ // (The distinction is critically important when casting a returned -1 error value to some other
1459
+ // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).
1460
+ template <typename Unsigned>
1461
+ Unsigned as_unsigned(PyObject *o) {
1462
+ if (PYBIND11_SILENCE_MSVC_C4127(sizeof(Unsigned) <= sizeof(unsigned long))
1463
+ #if PY_VERSION_HEX < 0x03000000
1464
+ || PyInt_Check(o)
1465
+ #endif
1466
+ ) {
1467
+ unsigned long v = PyLong_AsUnsignedLong(o);
1468
+ return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1469
+ }
1470
+ unsigned long long v = PyLong_AsUnsignedLongLong(o);
1471
+ return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1472
+ }
1473
+ PYBIND11_NAMESPACE_END(detail)
1474
+
1475
+ class int_ : public object {
1476
+ public:
1477
+ PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)
1478
+ int_() : object(PyLong_FromLong(0), stolen_t{}) {}
1479
+ // Allow implicit conversion from C++ integral types:
1480
+ template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1481
+ // NOLINTNEXTLINE(google-explicit-constructor)
1482
+ int_(T value) {
1483
+ if (PYBIND11_SILENCE_MSVC_C4127(sizeof(T) <= sizeof(long))) {
1484
+ if (std::is_signed<T>::value) {
1485
+ m_ptr = PyLong_FromLong((long) value);
1486
+ } else {
1487
+ m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
1488
+ }
1489
+ } else {
1490
+ if (std::is_signed<T>::value) {
1491
+ m_ptr = PyLong_FromLongLong((long long) value);
1492
+ } else {
1493
+ m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
1494
+ }
1495
+ }
1496
+ if (!m_ptr) {
1497
+ pybind11_fail("Could not allocate int object!");
1498
+ }
1499
+ }
1500
+
1501
+ template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1502
+ // NOLINTNEXTLINE(google-explicit-constructor)
1503
+ operator T() const {
1504
+ return std::is_unsigned<T>::value ? detail::as_unsigned<T>(m_ptr)
1505
+ : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr)
1506
+ : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
1507
+ }
1508
+ };
1509
+
1510
+ class float_ : public object {
1511
+ public:
1512
+ PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
1513
+ // Allow implicit conversion from float/double:
1514
+ // NOLINTNEXTLINE(google-explicit-constructor)
1515
+ float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1516
+ if (!m_ptr) {
1517
+ pybind11_fail("Could not allocate float object!");
1518
+ }
1519
+ }
1520
+ // NOLINTNEXTLINE(google-explicit-constructor)
1521
+ float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1522
+ if (!m_ptr) {
1523
+ pybind11_fail("Could not allocate float object!");
1524
+ }
1525
+ }
1526
+ // NOLINTNEXTLINE(google-explicit-constructor)
1527
+ operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
1528
+ // NOLINTNEXTLINE(google-explicit-constructor)
1529
+ operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
1530
+ };
1531
+
1532
+ class weakref : public object {
1533
+ public:
1534
+ PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref)
1535
+ explicit weakref(handle obj, handle callback = {})
1536
+ : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
1537
+ if (!m_ptr) {
1538
+ pybind11_fail("Could not allocate weak reference!");
1539
+ }
1540
+ }
1541
+
1542
+ private:
1543
+ static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); }
1544
+ };
1545
+
1546
+ class slice : public object {
1547
+ public:
1548
+ PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check)
1549
+ slice(handle start, handle stop, handle step) {
1550
+ m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.ptr());
1551
+ if (!m_ptr) {
1552
+ pybind11_fail("Could not allocate slice object!");
1553
+ }
1554
+ }
1555
+
1556
+ #ifdef PYBIND11_HAS_OPTIONAL
1557
+ slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step)
1558
+ : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {}
1559
+ #else
1560
+ slice(ssize_t start_, ssize_t stop_, ssize_t step_)
1561
+ : slice(int_(start_), int_(stop_), int_(step_)) {}
1562
+ #endif
1563
+
1564
+ bool
1565
+ compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const {
1566
+ return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1567
+ (ssize_t) length,
1568
+ (ssize_t *) start,
1569
+ (ssize_t *) stop,
1570
+ (ssize_t *) step,
1571
+ (ssize_t *) slicelength)
1572
+ == 0;
1573
+ }
1574
+ bool compute(
1575
+ ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const {
1576
+ return PySlice_GetIndicesEx(
1577
+ (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength)
1578
+ == 0;
1579
+ }
1580
+
1581
+ private:
1582
+ template <typename T>
1583
+ static object index_to_object(T index) {
1584
+ return index ? object(int_(*index)) : object(none());
1585
+ }
1586
+ };
1587
+
1588
+ class capsule : public object {
1589
+ public:
1590
+ PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
1591
+ PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
1592
+ capsule(PyObject *ptr, bool is_borrowed)
1593
+ : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {}
1594
+
1595
+ explicit capsule(const void *value,
1596
+ const char *name = nullptr,
1597
+ void (*destructor)(PyObject *) = nullptr)
1598
+ : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
1599
+ if (!m_ptr) {
1600
+ pybind11_fail("Could not allocate capsule object!");
1601
+ }
1602
+ }
1603
+
1604
+ PYBIND11_DEPRECATED("Please pass a destructor that takes a void pointer as input")
1605
+ capsule(const void *value, void (*destruct)(PyObject *))
1606
+ : object(PyCapsule_New(const_cast<void *>(value), nullptr, destruct), stolen_t{}) {
1607
+ if (!m_ptr) {
1608
+ pybind11_fail("Could not allocate capsule object!");
1609
+ }
1610
+ }
1611
+
1612
+ capsule(const void *value, void (*destructor)(void *)) {
1613
+ m_ptr = PyCapsule_New(const_cast<void *>(value), nullptr, [](PyObject *o) {
1614
+ auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
1615
+ void *ptr = PyCapsule_GetPointer(o, nullptr);
1616
+ destructor(ptr);
1617
+ });
1618
+
1619
+ if (!m_ptr) {
1620
+ pybind11_fail("Could not allocate capsule object!");
1621
+ }
1622
+
1623
+ if (PyCapsule_SetContext(m_ptr, (void *) destructor) != 0) {
1624
+ pybind11_fail("Could not set capsule context!");
1625
+ }
1626
+ }
1627
+
1628
+ explicit capsule(void (*destructor)()) {
1629
+ m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {
1630
+ auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, nullptr));
1631
+ destructor();
1632
+ });
1633
+
1634
+ if (!m_ptr) {
1635
+ pybind11_fail("Could not allocate capsule object!");
1636
+ }
1637
+ }
1638
+
1639
+ template <typename T>
1640
+ operator T *() const { // NOLINT(google-explicit-constructor)
1641
+ return get_pointer<T>();
1642
+ }
1643
+
1644
+ /// Get the pointer the capsule holds.
1645
+ template <typename T = void>
1646
+ T *get_pointer() const {
1647
+ const auto *name = this->name();
1648
+ T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
1649
+ if (!result) {
1650
+ PyErr_Clear();
1651
+ pybind11_fail("Unable to extract capsule contents!");
1652
+ }
1653
+ return result;
1654
+ }
1655
+
1656
+ /// Replaces a capsule's pointer *without* calling the destructor on the existing one.
1657
+ void set_pointer(const void *value) {
1658
+ if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) {
1659
+ PyErr_Clear();
1660
+ pybind11_fail("Could not set capsule pointer");
1661
+ }
1662
+ }
1663
+
1664
+ const char *name() const { return PyCapsule_GetName(m_ptr); }
1665
+ };
1666
+
1667
+ class tuple : public object {
1668
+ public:
1669
+ PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
1670
+ template <typename SzType = ssize_t,
1671
+ detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1672
+ // Some compilers generate link errors when using `const SzType &` here:
1673
+ explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) {
1674
+ if (!m_ptr) {
1675
+ pybind11_fail("Could not allocate tuple object!");
1676
+ }
1677
+ }
1678
+ size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
1679
+ bool empty() const { return size() == 0; }
1680
+ detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
1681
+ detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1682
+ detail::tuple_iterator begin() const { return {*this, 0}; }
1683
+ detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
1684
+ };
1685
+
1686
+ // We need to put this into a separate function because the Intel compiler
1687
+ // fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below
1688
+ // (tested with ICC 2021.1 Beta 20200827).
1689
+ template <typename... Args>
1690
+ constexpr bool args_are_all_keyword_or_ds() {
1691
+ return detail::all_of<detail::is_keyword_or_ds<Args>...>::value;
1692
+ }
1693
+
1694
+ class dict : public object {
1695
+ public:
1696
+ PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
1697
+ dict() : object(PyDict_New(), stolen_t{}) {
1698
+ if (!m_ptr) {
1699
+ pybind11_fail("Could not allocate dict object!");
1700
+ }
1701
+ }
1702
+ template <typename... Args,
1703
+ typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>,
1704
+ // MSVC workaround: it can't compile an out-of-line definition, so defer the
1705
+ // collector
1706
+ typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
1707
+ explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) {}
1708
+
1709
+ size_t size() const { return (size_t) PyDict_Size(m_ptr); }
1710
+ bool empty() const { return size() == 0; }
1711
+ detail::dict_iterator begin() const { return {*this, 0}; }
1712
+ detail::dict_iterator end() const { return {}; }
1713
+ void clear() /* py-non-const */ { PyDict_Clear(ptr()); }
1714
+ template <typename T>
1715
+ bool contains(T &&key) const {
1716
+ return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1;
1717
+ }
1718
+
1719
+ private:
1720
+ /// Call the `dict` Python type -- always returns a new reference
1721
+ static PyObject *raw_dict(PyObject *op) {
1722
+ if (PyDict_Check(op)) {
1723
+ return handle(op).inc_ref().ptr();
1724
+ }
1725
+ return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
1726
+ }
1727
+ };
1728
+
1729
+ class sequence : public object {
1730
+ public:
1731
+ PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
1732
+ size_t size() const {
1733
+ ssize_t result = PySequence_Size(m_ptr);
1734
+ if (result == -1) {
1735
+ throw error_already_set();
1736
+ }
1737
+ return (size_t) result;
1738
+ }
1739
+ bool empty() const { return size() == 0; }
1740
+ detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
1741
+ detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1742
+ detail::sequence_iterator begin() const { return {*this, 0}; }
1743
+ detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
1744
+ };
1745
+
1746
+ class list : public object {
1747
+ public:
1748
+ PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
1749
+ template <typename SzType = ssize_t,
1750
+ detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1751
+ // Some compilers generate link errors when using `const SzType &` here:
1752
+ explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) {
1753
+ if (!m_ptr) {
1754
+ pybind11_fail("Could not allocate list object!");
1755
+ }
1756
+ }
1757
+ size_t size() const { return (size_t) PyList_Size(m_ptr); }
1758
+ bool empty() const { return size() == 0; }
1759
+ detail::list_accessor operator[](size_t index) const { return {*this, index}; }
1760
+ detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1761
+ detail::list_iterator begin() const { return {*this, 0}; }
1762
+ detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
1763
+ template <typename T>
1764
+ void append(T &&val) /* py-non-const */ {
1765
+ PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
1766
+ }
1767
+ template <typename IdxType,
1768
+ typename ValType,
1769
+ detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1770
+ void insert(const IdxType &index, ValType &&val) /* py-non-const */ {
1771
+ PyList_Insert(
1772
+ m_ptr, ssize_t_cast(index), detail::object_or_cast(std::forward<ValType>(val)).ptr());
1773
+ }
1774
+ };
1775
+
1776
+ class args : public tuple {
1777
+ PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check)
1778
+ };
1779
+ class kwargs : public dict {
1780
+ PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)
1781
+ };
1782
+
1783
+ class set : public object {
1784
+ public:
1785
+ PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New)
1786
+ set() : object(PySet_New(nullptr), stolen_t{}) {
1787
+ if (!m_ptr) {
1788
+ pybind11_fail("Could not allocate set object!");
1789
+ }
1790
+ }
1791
+ size_t size() const { return (size_t) PySet_Size(m_ptr); }
1792
+ bool empty() const { return size() == 0; }
1793
+ template <typename T>
1794
+ bool add(T &&val) /* py-non-const */ {
1795
+ return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
1796
+ }
1797
+ void clear() /* py-non-const */ { PySet_Clear(m_ptr); }
1798
+ template <typename T>
1799
+ bool contains(T &&val) const {
1800
+ return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
1801
+ }
1802
+ };
1803
+
1804
+ class function : public object {
1805
+ public:
1806
+ PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
1807
+ handle cpp_function() const {
1808
+ handle fun = detail::get_function(m_ptr);
1809
+ if (fun && PyCFunction_Check(fun.ptr())) {
1810
+ return fun;
1811
+ }
1812
+ return handle();
1813
+ }
1814
+ bool is_cpp_function() const { return (bool) cpp_function(); }
1815
+ };
1816
+
1817
+ class staticmethod : public object {
1818
+ public:
1819
+ PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
1820
+ };
1821
+
1822
+ class buffer : public object {
1823
+ public:
1824
+ PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
1825
+
1826
+ buffer_info request(bool writable = false) const {
1827
+ int flags = PyBUF_STRIDES | PyBUF_FORMAT;
1828
+ if (writable) {
1829
+ flags |= PyBUF_WRITABLE;
1830
+ }
1831
+ auto *view = new Py_buffer();
1832
+ if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
1833
+ delete view;
1834
+ throw error_already_set();
1835
+ }
1836
+ return buffer_info(view);
1837
+ }
1838
+ };
1839
+
1840
+ class memoryview : public object {
1841
+ public:
1842
+ PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
1843
+
1844
+ /** \rst
1845
+ Creates ``memoryview`` from ``buffer_info``.
1846
+
1847
+ ``buffer_info`` must be created from ``buffer::request()``. Otherwise
1848
+ throws an exception.
1849
+
1850
+ For creating a ``memoryview`` from objects that support buffer protocol,
1851
+ use ``memoryview(const object& obj)`` instead of this constructor.
1852
+ \endrst */
1853
+ explicit memoryview(const buffer_info &info) {
1854
+ if (!info.view()) {
1855
+ pybind11_fail("Prohibited to create memoryview without Py_buffer");
1856
+ }
1857
+ // Note: PyMemoryView_FromBuffer never increments obj reference.
1858
+ m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj)
1859
+ : PyMemoryView_FromBuffer(info.view());
1860
+ if (!m_ptr) {
1861
+ pybind11_fail("Unable to create memoryview from buffer descriptor");
1862
+ }
1863
+ }
1864
+
1865
+ /** \rst
1866
+ Creates ``memoryview`` from static buffer.
1867
+
1868
+ This method is meant for providing a ``memoryview`` for C/C++ buffer not
1869
+ managed by Python. The caller is responsible for managing the lifetime
1870
+ of ``ptr`` and ``format``, which MUST outlive the memoryview constructed
1871
+ here.
1872
+
1873
+ See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
1874
+
1875
+ .. _PyMemoryView_FromBuffer:
1876
+ https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer
1877
+
1878
+ :param ptr: Pointer to the buffer.
1879
+ :param itemsize: Byte size of an element.
1880
+ :param format: Pointer to the null-terminated format string. For
1881
+ homogeneous Buffers, this should be set to
1882
+ ``format_descriptor<T>::value``.
1883
+ :param shape: Shape of the tensor (1 entry per dimension).
1884
+ :param strides: Number of bytes between adjacent entries (for each
1885
+ per dimension).
1886
+ :param readonly: Flag to indicate if the underlying storage may be
1887
+ written to.
1888
+ \endrst */
1889
+ static memoryview from_buffer(void *ptr,
1890
+ ssize_t itemsize,
1891
+ const char *format,
1892
+ detail::any_container<ssize_t> shape,
1893
+ detail::any_container<ssize_t> strides,
1894
+ bool readonly = false);
1895
+
1896
+ static memoryview from_buffer(const void *ptr,
1897
+ ssize_t itemsize,
1898
+ const char *format,
1899
+ detail::any_container<ssize_t> shape,
1900
+ detail::any_container<ssize_t> strides) {
1901
+ return memoryview::from_buffer(
1902
+ const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true);
1903
+ }
1904
+
1905
+ template <typename T>
1906
+ static memoryview from_buffer(T *ptr,
1907
+ detail::any_container<ssize_t> shape,
1908
+ detail::any_container<ssize_t> strides,
1909
+ bool readonly = false) {
1910
+ return memoryview::from_buffer(reinterpret_cast<void *>(ptr),
1911
+ sizeof(T),
1912
+ format_descriptor<T>::value,
1913
+ shape,
1914
+ strides,
1915
+ readonly);
1916
+ }
1917
+
1918
+ template <typename T>
1919
+ static memoryview from_buffer(const T *ptr,
1920
+ detail::any_container<ssize_t> shape,
1921
+ detail::any_container<ssize_t> strides) {
1922
+ return memoryview::from_buffer(const_cast<T *>(ptr), shape, strides, true);
1923
+ }
1924
+
1925
+ #if PY_MAJOR_VERSION >= 3
1926
+ /** \rst
1927
+ Creates ``memoryview`` from static memory.
1928
+
1929
+ This method is meant for providing a ``memoryview`` for C/C++ buffer not
1930
+ managed by Python. The caller is responsible for managing the lifetime
1931
+ of ``mem``, which MUST outlive the memoryview constructed here.
1932
+
1933
+ This method is not available in Python 2.
1934
+
1935
+ See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
1936
+
1937
+ .. _PyMemoryView_FromMemory:
1938
+ https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory
1939
+ \endrst */
1940
+ static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {
1941
+ PyObject *ptr = PyMemoryView_FromMemory(
1942
+ reinterpret_cast<char *>(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE);
1943
+ if (!ptr) {
1944
+ pybind11_fail("Could not allocate memoryview object!");
1945
+ }
1946
+ return memoryview(object(ptr, stolen_t{}));
1947
+ }
1948
+
1949
+ static memoryview from_memory(const void *mem, ssize_t size) {
1950
+ return memoryview::from_memory(const_cast<void *>(mem), size, true);
1951
+ }
1952
+
1953
+ # ifdef PYBIND11_HAS_STRING_VIEW
1954
+ static memoryview from_memory(std::string_view mem) {
1955
+ return from_memory(const_cast<char *>(mem.data()), static_cast<ssize_t>(mem.size()), true);
1956
+ }
1957
+ # endif
1958
+
1959
+ #endif
1960
+ };
1961
+
1962
+ /// @cond DUPLICATE
1963
+ inline memoryview memoryview::from_buffer(void *ptr,
1964
+ ssize_t itemsize,
1965
+ const char *format,
1966
+ detail::any_container<ssize_t> shape,
1967
+ detail::any_container<ssize_t> strides,
1968
+ bool readonly) {
1969
+ size_t ndim = shape->size();
1970
+ if (ndim != strides->size()) {
1971
+ pybind11_fail("memoryview: shape length doesn't match strides length");
1972
+ }
1973
+ ssize_t size = ndim != 0u ? 1 : 0;
1974
+ for (size_t i = 0; i < ndim; ++i) {
1975
+ size *= (*shape)[i];
1976
+ }
1977
+ Py_buffer view;
1978
+ view.buf = ptr;
1979
+ view.obj = nullptr;
1980
+ view.len = size * itemsize;
1981
+ view.readonly = static_cast<int>(readonly);
1982
+ view.itemsize = itemsize;
1983
+ view.format = const_cast<char *>(format);
1984
+ view.ndim = static_cast<int>(ndim);
1985
+ view.shape = shape->data();
1986
+ view.strides = strides->data();
1987
+ view.suboffsets = nullptr;
1988
+ view.internal = nullptr;
1989
+ PyObject *obj = PyMemoryView_FromBuffer(&view);
1990
+ if (!obj) {
1991
+ throw error_already_set();
1992
+ }
1993
+ return memoryview(object(obj, stolen_t{}));
1994
+ }
1995
+ /// @endcond
1996
+ /// @} pytypes
1997
+
1998
+ /// \addtogroup python_builtins
1999
+ /// @{
2000
+
2001
+ /// Get the length of a Python object.
2002
+ inline size_t len(handle h) {
2003
+ ssize_t result = PyObject_Length(h.ptr());
2004
+ if (result < 0) {
2005
+ throw error_already_set();
2006
+ }
2007
+ return (size_t) result;
2008
+ }
2009
+
2010
+ /// Get the length hint of a Python object.
2011
+ /// Returns 0 when this cannot be determined.
2012
+ inline size_t len_hint(handle h) {
2013
+ #if PY_VERSION_HEX >= 0x03040000
2014
+ ssize_t result = PyObject_LengthHint(h.ptr(), 0);
2015
+ #else
2016
+ ssize_t result = PyObject_Length(h.ptr());
2017
+ #endif
2018
+ if (result < 0) {
2019
+ // Sometimes a length can't be determined at all (eg generators)
2020
+ // In which case simply return 0
2021
+ PyErr_Clear();
2022
+ return 0;
2023
+ }
2024
+ return (size_t) result;
2025
+ }
2026
+
2027
+ inline str repr(handle h) {
2028
+ PyObject *str_value = PyObject_Repr(h.ptr());
2029
+ if (!str_value) {
2030
+ throw error_already_set();
2031
+ }
2032
+ #if PY_MAJOR_VERSION < 3
2033
+ PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
2034
+ Py_XDECREF(str_value);
2035
+ str_value = unicode;
2036
+ if (!str_value)
2037
+ throw error_already_set();
2038
+ #endif
2039
+ return reinterpret_steal<str>(str_value);
2040
+ }
2041
+
2042
+ inline iterator iter(handle obj) {
2043
+ PyObject *result = PyObject_GetIter(obj.ptr());
2044
+ if (!result) {
2045
+ throw error_already_set();
2046
+ }
2047
+ return reinterpret_steal<iterator>(result);
2048
+ }
2049
+ /// @} python_builtins
2050
+
2051
+ PYBIND11_NAMESPACE_BEGIN(detail)
2052
+ template <typename D>
2053
+ iterator object_api<D>::begin() const {
2054
+ return iter(derived());
2055
+ }
2056
+ template <typename D>
2057
+ iterator object_api<D>::end() const {
2058
+ return iterator::sentinel();
2059
+ }
2060
+ template <typename D>
2061
+ item_accessor object_api<D>::operator[](handle key) const {
2062
+ return {derived(), reinterpret_borrow<object>(key)};
2063
+ }
2064
+ template <typename D>
2065
+ item_accessor object_api<D>::operator[](const char *key) const {
2066
+ return {derived(), pybind11::str(key)};
2067
+ }
2068
+ template <typename D>
2069
+ obj_attr_accessor object_api<D>::attr(handle key) const {
2070
+ return {derived(), reinterpret_borrow<object>(key)};
2071
+ }
2072
+ template <typename D>
2073
+ str_attr_accessor object_api<D>::attr(const char *key) const {
2074
+ return {derived(), key};
2075
+ }
2076
+ template <typename D>
2077
+ args_proxy object_api<D>::operator*() const {
2078
+ return args_proxy(derived().ptr());
2079
+ }
2080
+ template <typename D>
2081
+ template <typename T>
2082
+ bool object_api<D>::contains(T &&item) const {
2083
+ return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
2084
+ }
2085
+
2086
+ template <typename D>
2087
+ pybind11::str object_api<D>::str() const {
2088
+ return pybind11::str(derived());
2089
+ }
2090
+
2091
+ template <typename D>
2092
+ str_attr_accessor object_api<D>::doc() const {
2093
+ return attr("__doc__");
2094
+ }
2095
+
2096
+ template <typename D>
2097
+ handle object_api<D>::get_type() const {
2098
+ return type::handle_of(derived());
2099
+ }
2100
+
2101
+ template <typename D>
2102
+ bool object_api<D>::rich_compare(object_api const &other, int value) const {
2103
+ int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
2104
+ if (rv == -1) {
2105
+ throw error_already_set();
2106
+ }
2107
+ return rv == 1;
2108
+ }
2109
+
2110
+ #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
2111
+ template <typename D> \
2112
+ object object_api<D>::op() const { \
2113
+ object result = reinterpret_steal<object>(fn(derived().ptr())); \
2114
+ if (!result.ptr()) \
2115
+ throw error_already_set(); \
2116
+ return result; \
2117
+ }
2118
+
2119
+ #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
2120
+ template <typename D> \
2121
+ object object_api<D>::op(object_api const &other) const { \
2122
+ object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2123
+ if (!result.ptr()) \
2124
+ throw error_already_set(); \
2125
+ return result; \
2126
+ }
2127
+
2128
+ PYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert)
2129
+ PYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative)
2130
+ PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
2131
+ PYBIND11_MATH_OPERATOR_BINARY(operator+=, PyNumber_InPlaceAdd)
2132
+ PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
2133
+ PYBIND11_MATH_OPERATOR_BINARY(operator-=, PyNumber_InPlaceSubtract)
2134
+ PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
2135
+ PYBIND11_MATH_OPERATOR_BINARY(operator*=, PyNumber_InPlaceMultiply)
2136
+ PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
2137
+ PYBIND11_MATH_OPERATOR_BINARY(operator/=, PyNumber_InPlaceTrueDivide)
2138
+ PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
2139
+ PYBIND11_MATH_OPERATOR_BINARY(operator|=, PyNumber_InPlaceOr)
2140
+ PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
2141
+ PYBIND11_MATH_OPERATOR_BINARY(operator&=, PyNumber_InPlaceAnd)
2142
+ PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
2143
+ PYBIND11_MATH_OPERATOR_BINARY(operator^=, PyNumber_InPlaceXor)
2144
+ PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
2145
+ PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift)
2146
+ PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
2147
+ PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift)
2148
+
2149
+ #undef PYBIND11_MATH_OPERATOR_UNARY
2150
+ #undef PYBIND11_MATH_OPERATOR_BINARY
2151
+
2152
+ PYBIND11_NAMESPACE_END(detail)
2153
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/stl.h ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/stl.h: Transparent conversion for STL data types
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+ #include "detail/common.h"
14
+
15
+ #include <deque>
16
+ #include <iostream>
17
+ #include <list>
18
+ #include <map>
19
+ #include <set>
20
+ #include <unordered_map>
21
+ #include <unordered_set>
22
+ #include <valarray>
23
+
24
+ // See `detail/common.h` for implementation of these guards.
25
+ #if defined(PYBIND11_HAS_OPTIONAL)
26
+ # include <optional>
27
+ #elif defined(PYBIND11_HAS_EXP_OPTIONAL)
28
+ # include <experimental/optional>
29
+ #endif
30
+
31
+ #if defined(PYBIND11_HAS_VARIANT)
32
+ # include <variant>
33
+ #endif
34
+
35
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
36
+ PYBIND11_NAMESPACE_BEGIN(detail)
37
+
38
+ /// Extracts an const lvalue reference or rvalue reference for U based on the type of T (e.g. for
39
+ /// forwarding a container element). Typically used indirect via forwarded_type(), below.
40
+ template <typename T, typename U>
41
+ using forwarded_type = conditional_t<std::is_lvalue_reference<T>::value,
42
+ remove_reference_t<U> &,
43
+ remove_reference_t<U> &&>;
44
+
45
+ /// Forwards a value U as rvalue or lvalue according to whether T is rvalue or lvalue; typically
46
+ /// used for forwarding a container's elements.
47
+ template <typename T, typename U>
48
+ forwarded_type<T, U> forward_like(U &&u) {
49
+ return std::forward<detail::forwarded_type<T, U>>(std::forward<U>(u));
50
+ }
51
+
52
+ template <typename Type, typename Key>
53
+ struct set_caster {
54
+ using type = Type;
55
+ using key_conv = make_caster<Key>;
56
+
57
+ bool load(handle src, bool convert) {
58
+ if (!isinstance<pybind11::set>(src)) {
59
+ return false;
60
+ }
61
+ auto s = reinterpret_borrow<pybind11::set>(src);
62
+ value.clear();
63
+ for (auto entry : s) {
64
+ key_conv conv;
65
+ if (!conv.load(entry, convert)) {
66
+ return false;
67
+ }
68
+ value.insert(cast_op<Key &&>(std::move(conv)));
69
+ }
70
+ return true;
71
+ }
72
+
73
+ template <typename T>
74
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
75
+ if (!std::is_lvalue_reference<T>::value) {
76
+ policy = return_value_policy_override<Key>::policy(policy);
77
+ }
78
+ pybind11::set s;
79
+ for (auto &&value : src) {
80
+ auto value_ = reinterpret_steal<object>(
81
+ key_conv::cast(forward_like<T>(value), policy, parent));
82
+ if (!value_ || !s.add(value_)) {
83
+ return handle();
84
+ }
85
+ }
86
+ return s.release();
87
+ }
88
+
89
+ PYBIND11_TYPE_CASTER(type, const_name("Set[") + key_conv::name + const_name("]"));
90
+ };
91
+
92
+ template <typename Type, typename Key, typename Value>
93
+ struct map_caster {
94
+ using key_conv = make_caster<Key>;
95
+ using value_conv = make_caster<Value>;
96
+
97
+ bool load(handle src, bool convert) {
98
+ if (!isinstance<dict>(src)) {
99
+ return false;
100
+ }
101
+ auto d = reinterpret_borrow<dict>(src);
102
+ value.clear();
103
+ for (auto it : d) {
104
+ key_conv kconv;
105
+ value_conv vconv;
106
+ if (!kconv.load(it.first.ptr(), convert) || !vconv.load(it.second.ptr(), convert)) {
107
+ return false;
108
+ }
109
+ value.emplace(cast_op<Key &&>(std::move(kconv)), cast_op<Value &&>(std::move(vconv)));
110
+ }
111
+ return true;
112
+ }
113
+
114
+ template <typename T>
115
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
116
+ dict d;
117
+ return_value_policy policy_key = policy;
118
+ return_value_policy policy_value = policy;
119
+ if (!std::is_lvalue_reference<T>::value) {
120
+ policy_key = return_value_policy_override<Key>::policy(policy_key);
121
+ policy_value = return_value_policy_override<Value>::policy(policy_value);
122
+ }
123
+ for (auto &&kv : src) {
124
+ auto key = reinterpret_steal<object>(
125
+ key_conv::cast(forward_like<T>(kv.first), policy_key, parent));
126
+ auto value = reinterpret_steal<object>(
127
+ value_conv::cast(forward_like<T>(kv.second), policy_value, parent));
128
+ if (!key || !value) {
129
+ return handle();
130
+ }
131
+ d[key] = value;
132
+ }
133
+ return d.release();
134
+ }
135
+
136
+ PYBIND11_TYPE_CASTER(Type,
137
+ const_name("Dict[") + key_conv::name + const_name(", ") + value_conv::name
138
+ + const_name("]"));
139
+ };
140
+
141
+ template <typename Type, typename Value>
142
+ struct list_caster {
143
+ using value_conv = make_caster<Value>;
144
+
145
+ bool load(handle src, bool convert) {
146
+ if (!isinstance<sequence>(src) || isinstance<bytes>(src) || isinstance<str>(src)) {
147
+ return false;
148
+ }
149
+ auto s = reinterpret_borrow<sequence>(src);
150
+ value.clear();
151
+ reserve_maybe(s, &value);
152
+ for (auto it : s) {
153
+ value_conv conv;
154
+ if (!conv.load(it, convert)) {
155
+ return false;
156
+ }
157
+ value.push_back(cast_op<Value &&>(std::move(conv)));
158
+ }
159
+ return true;
160
+ }
161
+
162
+ private:
163
+ template <
164
+ typename T = Type,
165
+ enable_if_t<std::is_same<decltype(std::declval<T>().reserve(0)), void>::value, int> = 0>
166
+ void reserve_maybe(const sequence &s, Type *) {
167
+ value.reserve(s.size());
168
+ }
169
+ void reserve_maybe(const sequence &, void *) {}
170
+
171
+ public:
172
+ template <typename T>
173
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
174
+ if (!std::is_lvalue_reference<T>::value) {
175
+ policy = return_value_policy_override<Value>::policy(policy);
176
+ }
177
+ list l(src.size());
178
+ ssize_t index = 0;
179
+ for (auto &&value : src) {
180
+ auto value_ = reinterpret_steal<object>(
181
+ value_conv::cast(forward_like<T>(value), policy, parent));
182
+ if (!value_) {
183
+ return handle();
184
+ }
185
+ PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference
186
+ }
187
+ return l.release();
188
+ }
189
+
190
+ PYBIND11_TYPE_CASTER(Type, const_name("List[") + value_conv::name + const_name("]"));
191
+ };
192
+
193
+ template <typename Type, typename Alloc>
194
+ struct type_caster<std::vector<Type, Alloc>> : list_caster<std::vector<Type, Alloc>, Type> {};
195
+
196
+ template <typename Type, typename Alloc>
197
+ struct type_caster<std::deque<Type, Alloc>> : list_caster<std::deque<Type, Alloc>, Type> {};
198
+
199
+ template <typename Type, typename Alloc>
200
+ struct type_caster<std::list<Type, Alloc>> : list_caster<std::list<Type, Alloc>, Type> {};
201
+
202
+ template <typename ArrayType, typename Value, bool Resizable, size_t Size = 0>
203
+ struct array_caster {
204
+ using value_conv = make_caster<Value>;
205
+
206
+ private:
207
+ template <bool R = Resizable>
208
+ bool require_size(enable_if_t<R, size_t> size) {
209
+ if (value.size() != size) {
210
+ value.resize(size);
211
+ }
212
+ return true;
213
+ }
214
+ template <bool R = Resizable>
215
+ bool require_size(enable_if_t<!R, size_t> size) {
216
+ return size == Size;
217
+ }
218
+
219
+ public:
220
+ bool load(handle src, bool convert) {
221
+ if (!isinstance<sequence>(src)) {
222
+ return false;
223
+ }
224
+ auto l = reinterpret_borrow<sequence>(src);
225
+ if (!require_size(l.size())) {
226
+ return false;
227
+ }
228
+ size_t ctr = 0;
229
+ for (auto it : l) {
230
+ value_conv conv;
231
+ if (!conv.load(it, convert)) {
232
+ return false;
233
+ }
234
+ value[ctr++] = cast_op<Value &&>(std::move(conv));
235
+ }
236
+ return true;
237
+ }
238
+
239
+ template <typename T>
240
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
241
+ list l(src.size());
242
+ ssize_t index = 0;
243
+ for (auto &&value : src) {
244
+ auto value_ = reinterpret_steal<object>(
245
+ value_conv::cast(forward_like<T>(value), policy, parent));
246
+ if (!value_) {
247
+ return handle();
248
+ }
249
+ PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference
250
+ }
251
+ return l.release();
252
+ }
253
+
254
+ PYBIND11_TYPE_CASTER(ArrayType,
255
+ const_name("List[") + value_conv::name
256
+ + const_name<Resizable>(const_name(""),
257
+ const_name("[") + const_name<Size>()
258
+ + const_name("]"))
259
+ + const_name("]"));
260
+ };
261
+
262
+ template <typename Type, size_t Size>
263
+ struct type_caster<std::array<Type, Size>>
264
+ : array_caster<std::array<Type, Size>, Type, false, Size> {};
265
+
266
+ template <typename Type>
267
+ struct type_caster<std::valarray<Type>> : array_caster<std::valarray<Type>, Type, true> {};
268
+
269
+ template <typename Key, typename Compare, typename Alloc>
270
+ struct type_caster<std::set<Key, Compare, Alloc>>
271
+ : set_caster<std::set<Key, Compare, Alloc>, Key> {};
272
+
273
+ template <typename Key, typename Hash, typename Equal, typename Alloc>
274
+ struct type_caster<std::unordered_set<Key, Hash, Equal, Alloc>>
275
+ : set_caster<std::unordered_set<Key, Hash, Equal, Alloc>, Key> {};
276
+
277
+ template <typename Key, typename Value, typename Compare, typename Alloc>
278
+ struct type_caster<std::map<Key, Value, Compare, Alloc>>
279
+ : map_caster<std::map<Key, Value, Compare, Alloc>, Key, Value> {};
280
+
281
+ template <typename Key, typename Value, typename Hash, typename Equal, typename Alloc>
282
+ struct type_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>>
283
+ : map_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>, Key, Value> {};
284
+
285
+ // This type caster is intended to be used for std::optional and std::experimental::optional
286
+ template <typename Type, typename Value = typename Type::value_type>
287
+ struct optional_caster {
288
+ using value_conv = make_caster<Value>;
289
+
290
+ template <typename T>
291
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
292
+ if (!src) {
293
+ return none().inc_ref();
294
+ }
295
+ if (!std::is_lvalue_reference<T>::value) {
296
+ policy = return_value_policy_override<Value>::policy(policy);
297
+ }
298
+ return value_conv::cast(*std::forward<T>(src), policy, parent);
299
+ }
300
+
301
+ bool load(handle src, bool convert) {
302
+ if (!src) {
303
+ return false;
304
+ }
305
+ if (src.is_none()) {
306
+ return true; // default-constructed value is already empty
307
+ }
308
+ value_conv inner_caster;
309
+ if (!inner_caster.load(src, convert)) {
310
+ return false;
311
+ }
312
+
313
+ value.emplace(cast_op<Value &&>(std::move(inner_caster)));
314
+ return true;
315
+ }
316
+
317
+ PYBIND11_TYPE_CASTER(Type, const_name("Optional[") + value_conv::name + const_name("]"));
318
+ };
319
+
320
+ #if defined(PYBIND11_HAS_OPTIONAL)
321
+ template <typename T>
322
+ struct type_caster<std::optional<T>> : public optional_caster<std::optional<T>> {};
323
+
324
+ template <>
325
+ struct type_caster<std::nullopt_t> : public void_caster<std::nullopt_t> {};
326
+ #endif
327
+
328
+ #if defined(PYBIND11_HAS_EXP_OPTIONAL)
329
+ template <typename T>
330
+ struct type_caster<std::experimental::optional<T>>
331
+ : public optional_caster<std::experimental::optional<T>> {};
332
+
333
+ template <>
334
+ struct type_caster<std::experimental::nullopt_t>
335
+ : public void_caster<std::experimental::nullopt_t> {};
336
+ #endif
337
+
338
+ /// Visit a variant and cast any found type to Python
339
+ struct variant_caster_visitor {
340
+ return_value_policy policy;
341
+ handle parent;
342
+
343
+ using result_type = handle; // required by boost::variant in C++11
344
+
345
+ template <typename T>
346
+ result_type operator()(T &&src) const {
347
+ return make_caster<T>::cast(std::forward<T>(src), policy, parent);
348
+ }
349
+ };
350
+
351
+ /// Helper class which abstracts away variant's `visit` function. `std::variant` and similar
352
+ /// `namespace::variant` types which provide a `namespace::visit()` function are handled here
353
+ /// automatically using argument-dependent lookup. Users can provide specializations for other
354
+ /// variant-like classes, e.g. `boost::variant` and `boost::apply_visitor`.
355
+ template <template <typename...> class Variant>
356
+ struct visit_helper {
357
+ template <typename... Args>
358
+ static auto call(Args &&...args) -> decltype(visit(std::forward<Args>(args)...)) {
359
+ return visit(std::forward<Args>(args)...);
360
+ }
361
+ };
362
+
363
+ /// Generic variant caster
364
+ template <typename Variant>
365
+ struct variant_caster;
366
+
367
+ template <template <typename...> class V, typename... Ts>
368
+ struct variant_caster<V<Ts...>> {
369
+ static_assert(sizeof...(Ts) > 0, "Variant must consist of at least one alternative.");
370
+
371
+ template <typename U, typename... Us>
372
+ bool load_alternative(handle src, bool convert, type_list<U, Us...>) {
373
+ auto caster = make_caster<U>();
374
+ if (caster.load(src, convert)) {
375
+ value = cast_op<U>(caster);
376
+ return true;
377
+ }
378
+ return load_alternative(src, convert, type_list<Us...>{});
379
+ }
380
+
381
+ bool load_alternative(handle, bool, type_list<>) { return false; }
382
+
383
+ bool load(handle src, bool convert) {
384
+ // Do a first pass without conversions to improve constructor resolution.
385
+ // E.g. `py::int_(1).cast<variant<double, int>>()` needs to fill the `int`
386
+ // slot of the variant. Without two-pass loading `double` would be filled
387
+ // because it appears first and a conversion is possible.
388
+ if (convert && load_alternative(src, false, type_list<Ts...>{})) {
389
+ return true;
390
+ }
391
+ return load_alternative(src, convert, type_list<Ts...>{});
392
+ }
393
+
394
+ template <typename Variant>
395
+ static handle cast(Variant &&src, return_value_policy policy, handle parent) {
396
+ return visit_helper<V>::call(variant_caster_visitor{policy, parent},
397
+ std::forward<Variant>(src));
398
+ }
399
+
400
+ using Type = V<Ts...>;
401
+ PYBIND11_TYPE_CASTER(Type,
402
+ const_name("Union[") + detail::concat(make_caster<Ts>::name...)
403
+ + const_name("]"));
404
+ };
405
+
406
+ #if defined(PYBIND11_HAS_VARIANT)
407
+ template <typename... Ts>
408
+ struct type_caster<std::variant<Ts...>> : variant_caster<std::variant<Ts...>> {};
409
+ #endif
410
+
411
+ PYBIND11_NAMESPACE_END(detail)
412
+
413
+ inline std::ostream &operator<<(std::ostream &os, const handle &obj) {
414
+ #ifdef PYBIND11_HAS_STRING_VIEW
415
+ os << str(obj).cast<std::string_view>();
416
+ #else
417
+ os << (std::string) str(obj);
418
+ #endif
419
+ return os;
420
+ }
421
+
422
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/DPRetrieval/pybind11/include/pybind11/stl/filesystem.h ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2021 The Pybind Development Team.
2
+ // All rights reserved. Use of this source code is governed by a
3
+ // BSD-style license that can be found in the LICENSE file.
4
+
5
+ #pragma once
6
+
7
+ #include "../pybind11.h"
8
+ #include "../detail/common.h"
9
+ #include "../detail/descr.h"
10
+ #include "../cast.h"
11
+ #include "../pytypes.h"
12
+
13
+ #include <string>
14
+
15
+ #ifdef __has_include
16
+ # if defined(PYBIND11_CPP17) && __has_include(<filesystem>) && \
17
+ PY_VERSION_HEX >= 0x03060000
18
+ # include <filesystem>
19
+ # define PYBIND11_HAS_FILESYSTEM 1
20
+ # endif
21
+ #endif
22
+
23
+ #if !defined(PYBIND11_HAS_FILESYSTEM) && !defined(PYBIND11_HAS_FILESYSTEM_IS_OPTIONAL)
24
+ # error \
25
+ "#include <filesystem> is not available. (Use -DPYBIND11_HAS_FILESYSTEM_IS_OPTIONAL to ignore.)"
26
+ #endif
27
+
28
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
29
+ PYBIND11_NAMESPACE_BEGIN(detail)
30
+
31
+ #if defined(PYBIND11_HAS_FILESYSTEM)
32
+ template <typename T>
33
+ struct path_caster {
34
+
35
+ private:
36
+ static PyObject *unicode_from_fs_native(const std::string &w) {
37
+ # if !defined(PYPY_VERSION)
38
+ return PyUnicode_DecodeFSDefaultAndSize(w.c_str(), ssize_t(w.size()));
39
+ # else
40
+ // PyPy mistakenly declares the first parameter as non-const.
41
+ return PyUnicode_DecodeFSDefaultAndSize(const_cast<char *>(w.c_str()), ssize_t(w.size()));
42
+ # endif
43
+ }
44
+
45
+ static PyObject *unicode_from_fs_native(const std::wstring &w) {
46
+ return PyUnicode_FromWideChar(w.c_str(), ssize_t(w.size()));
47
+ }
48
+
49
+ public:
50
+ static handle cast(const T &path, return_value_policy, handle) {
51
+ if (auto py_str = unicode_from_fs_native(path.native())) {
52
+ return module_::import("pathlib")
53
+ .attr("Path")(reinterpret_steal<object>(py_str))
54
+ .release();
55
+ }
56
+ return nullptr;
57
+ }
58
+
59
+ bool load(handle handle, bool) {
60
+ // PyUnicode_FSConverter and PyUnicode_FSDecoder normally take care of
61
+ // calling PyOS_FSPath themselves, but that's broken on PyPy (PyPy
62
+ // issue #3168) so we do it ourselves instead.
63
+ PyObject *buf = PyOS_FSPath(handle.ptr());
64
+ if (!buf) {
65
+ PyErr_Clear();
66
+ return false;
67
+ }
68
+ PyObject *native = nullptr;
69
+ if constexpr (std::is_same_v<typename T::value_type, char>) {
70
+ if (PyUnicode_FSConverter(buf, &native) != 0) {
71
+ if (auto *c_str = PyBytes_AsString(native)) {
72
+ // AsString returns a pointer to the internal buffer, which
73
+ // must not be free'd.
74
+ value = c_str;
75
+ }
76
+ }
77
+ } else if constexpr (std::is_same_v<typename T::value_type, wchar_t>) {
78
+ if (PyUnicode_FSDecoder(buf, &native) != 0) {
79
+ if (auto *c_str = PyUnicode_AsWideCharString(native, nullptr)) {
80
+ // AsWideCharString returns a new string that must be free'd.
81
+ value = c_str; // Copies the string.
82
+ PyMem_Free(c_str);
83
+ }
84
+ }
85
+ }
86
+ Py_XDECREF(native);
87
+ Py_DECREF(buf);
88
+ if (PyErr_Occurred()) {
89
+ PyErr_Clear();
90
+ return false;
91
+ }
92
+ return true;
93
+ }
94
+
95
+ PYBIND11_TYPE_CASTER(T, const_name("os.PathLike"));
96
+ };
97
+
98
+ template <>
99
+ struct type_caster<std::filesystem::path> : public path_caster<std::filesystem::path> {};
100
+ #endif // PYBIND11_HAS_FILESYSTEM
101
+
102
+ PYBIND11_NAMESPACE_END(detail)
103
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)