Spaces:
Sleeping
Sleeping
49cbfae41f9cea5afc5b75c9ec391b97de2480740809b5290efef61f9dd7a64d
Browse files- third-party/DPVO/DPViewer/pybind11/docs/Doxyfile +21 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/cast/index.rst +43 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/cast/overview.rst +170 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/cast/stl.rst +249 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/cast/strings.rst +292 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/classes.rst +1335 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/embedding.rst +262 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/exceptions.rst +398 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/functions.rst +614 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/misc.rst +337 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/pycpp/index.rst +13 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/pycpp/numpy.rst +455 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/pycpp/object.rst +286 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/pycpp/utilities.rst +155 -0
- third-party/DPVO/DPViewer/pybind11/docs/advanced/smart_ptrs.rst +174 -0
- third-party/DPVO/DPViewer/pybind11/docs/basics.rst +307 -0
- third-party/DPVO/DPViewer/pybind11/docs/benchmark.py +87 -0
- third-party/DPVO/DPViewer/pybind11/docs/benchmark.rst +95 -0
- third-party/DPVO/DPViewer/pybind11/docs/changelog.rst +0 -0
- third-party/DPVO/DPViewer/pybind11/docs/classes.rst +541 -0
- third-party/DPVO/DPViewer/pybind11/docs/cmake/index.rst +8 -0
- third-party/DPVO/DPViewer/pybind11/docs/compiling.rst +638 -0
- third-party/DPVO/DPViewer/pybind11/docs/conf.py +380 -0
- third-party/DPVO/DPViewer/pybind11/docs/faq.rst +307 -0
- third-party/DPVO/DPViewer/pybind11/docs/index.rst +48 -0
- third-party/DPVO/DPViewer/pybind11/docs/installing.rst +105 -0
- third-party/DPVO/DPViewer/pybind11/docs/limitations.rst +72 -0
- third-party/DPVO/DPViewer/pybind11/docs/pybind11-logo.png +0 -0
- third-party/DPVO/DPViewer/pybind11/docs/pybind11_vs_boost_python1.png +0 -0
- third-party/DPVO/DPViewer/pybind11/docs/pybind11_vs_boost_python1.svg +427 -0
- third-party/DPVO/DPViewer/pybind11/docs/pybind11_vs_boost_python2.png +0 -0
- third-party/DPVO/DPViewer/pybind11/docs/pybind11_vs_boost_python2.svg +427 -0
- third-party/DPVO/DPViewer/pybind11/docs/reference.rst +130 -0
- third-party/DPVO/DPViewer/pybind11/docs/release.rst +97 -0
- third-party/DPVO/DPViewer/pybind11/docs/requirements.txt +5 -0
- third-party/DPVO/DPViewer/pybind11/docs/upgrade.rst +552 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/attr.h +676 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/buffer_info.h +193 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/cast.h +1665 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/chrono.h +225 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/common.h +2 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/complex.h +74 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/detail/class.h +734 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/detail/common.h +1168 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/detail/descr.h +158 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/detail/init.h +428 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/detail/internals.h +562 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/detail/type_caster_base.h +1010 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/detail/typeid.h +59 -0
- third-party/DPVO/DPViewer/pybind11/include/pybind11/eigen.h +702 -0
third-party/DPVO/DPViewer/pybind11/docs/Doxyfile
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 = PYBIND11_NOINLINE
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/cast/index.rst
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.. _type-conversions:
|
2 |
+
|
3 |
+
Type conversions
|
4 |
+
################
|
5 |
+
|
6 |
+
Apart from enabling cross-language function calls, a fundamental problem
|
7 |
+
that a binding tool like pybind11 must address is to provide access to
|
8 |
+
native Python types in C++ and vice versa. There are three fundamentally
|
9 |
+
different ways to do this—which approach is preferable for a particular type
|
10 |
+
depends on the situation at hand.
|
11 |
+
|
12 |
+
1. Use a native C++ type everywhere. In this case, the type must be wrapped
|
13 |
+
using pybind11-generated bindings so that Python can interact with it.
|
14 |
+
|
15 |
+
2. Use a native Python type everywhere. It will need to be wrapped so that
|
16 |
+
C++ functions can interact with it.
|
17 |
+
|
18 |
+
3. Use a native C++ type on the C++ side and a native Python type on the
|
19 |
+
Python side. pybind11 refers to this as a *type conversion*.
|
20 |
+
|
21 |
+
Type conversions are the most "natural" option in the sense that native
|
22 |
+
(non-wrapped) types are used everywhere. The main downside is that a copy
|
23 |
+
of the data must be made on every Python ↔ C++ transition: this is
|
24 |
+
needed since the C++ and Python versions of the same type generally won't
|
25 |
+
have the same memory layout.
|
26 |
+
|
27 |
+
pybind11 can perform many kinds of conversions automatically. An overview
|
28 |
+
is provided in the table ":ref:`conversion_table`".
|
29 |
+
|
30 |
+
The following subsections discuss the differences between these options in more
|
31 |
+
detail. The main focus in this section is on type conversions, which represent
|
32 |
+
the last case of the above list.
|
33 |
+
|
34 |
+
.. toctree::
|
35 |
+
:maxdepth: 1
|
36 |
+
|
37 |
+
overview
|
38 |
+
strings
|
39 |
+
stl
|
40 |
+
functional
|
41 |
+
chrono
|
42 |
+
eigen
|
43 |
+
custom
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/cast/overview.rst
ADDED
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Overview
|
2 |
+
########
|
3 |
+
|
4 |
+
.. rubric:: 1. Native type in C++, wrapper in Python
|
5 |
+
|
6 |
+
Exposing a custom C++ type using :class:`py::class_` was covered in detail
|
7 |
+
in the :doc:`/classes` section. There, the underlying data structure is
|
8 |
+
always the original C++ class while the :class:`py::class_` wrapper provides
|
9 |
+
a Python interface. Internally, when an object like this is sent from C++ to
|
10 |
+
Python, pybind11 will just add the outer wrapper layer over the native C++
|
11 |
+
object. Getting it back from Python is just a matter of peeling off the
|
12 |
+
wrapper.
|
13 |
+
|
14 |
+
.. rubric:: 2. Wrapper in C++, native type in Python
|
15 |
+
|
16 |
+
This is the exact opposite situation. Now, we have a type which is native to
|
17 |
+
Python, like a ``tuple`` or a ``list``. One way to get this data into C++ is
|
18 |
+
with the :class:`py::object` family of wrappers. These are explained in more
|
19 |
+
detail in the :doc:`/advanced/pycpp/object` section. We'll just give a quick
|
20 |
+
example here:
|
21 |
+
|
22 |
+
.. code-block:: cpp
|
23 |
+
|
24 |
+
void print_list(py::list my_list) {
|
25 |
+
for (auto item : my_list)
|
26 |
+
std::cout << item << " ";
|
27 |
+
}
|
28 |
+
|
29 |
+
.. code-block:: pycon
|
30 |
+
|
31 |
+
>>> print_list([1, 2, 3])
|
32 |
+
1 2 3
|
33 |
+
|
34 |
+
The Python ``list`` is not converted in any way -- it's just wrapped in a C++
|
35 |
+
:class:`py::list` class. At its core it's still a Python object. Copying a
|
36 |
+
:class:`py::list` will do the usual reference-counting like in Python.
|
37 |
+
Returning the object to Python will just remove the thin wrapper.
|
38 |
+
|
39 |
+
.. rubric:: 3. Converting between native C++ and Python types
|
40 |
+
|
41 |
+
In the previous two cases we had a native type in one language and a wrapper in
|
42 |
+
the other. Now, we have native types on both sides and we convert between them.
|
43 |
+
|
44 |
+
.. code-block:: cpp
|
45 |
+
|
46 |
+
void print_vector(const std::vector<int> &v) {
|
47 |
+
for (auto item : v)
|
48 |
+
std::cout << item << "\n";
|
49 |
+
}
|
50 |
+
|
51 |
+
.. code-block:: pycon
|
52 |
+
|
53 |
+
>>> print_vector([1, 2, 3])
|
54 |
+
1 2 3
|
55 |
+
|
56 |
+
In this case, pybind11 will construct a new ``std::vector<int>`` and copy each
|
57 |
+
element from the Python ``list``. The newly constructed object will be passed
|
58 |
+
to ``print_vector``. The same thing happens in the other direction: a new
|
59 |
+
``list`` is made to match the value returned from C++.
|
60 |
+
|
61 |
+
Lots of these conversions are supported out of the box, as shown in the table
|
62 |
+
below. They are very convenient, but keep in mind that these conversions are
|
63 |
+
fundamentally based on copying data. This is perfectly fine for small immutable
|
64 |
+
types but it may become quite expensive for large data structures. This can be
|
65 |
+
avoided by overriding the automatic conversion with a custom wrapper (i.e. the
|
66 |
+
above-mentioned approach 1). This requires some manual effort and more details
|
67 |
+
are available in the :ref:`opaque` section.
|
68 |
+
|
69 |
+
.. _conversion_table:
|
70 |
+
|
71 |
+
List of all builtin conversions
|
72 |
+
-------------------------------
|
73 |
+
|
74 |
+
The following basic data types are supported out of the box (some may require
|
75 |
+
an additional extension header to be included). To pass other data structures
|
76 |
+
as arguments and return values, refer to the section on binding :ref:`classes`.
|
77 |
+
|
78 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
79 |
+
| Data type | Description | Header file |
|
80 |
+
+====================================+===========================+===================================+
|
81 |
+
| ``int8_t``, ``uint8_t`` | 8-bit integers | :file:`pybind11/pybind11.h` |
|
82 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
83 |
+
| ``int16_t``, ``uint16_t`` | 16-bit integers | :file:`pybind11/pybind11.h` |
|
84 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
85 |
+
| ``int32_t``, ``uint32_t`` | 32-bit integers | :file:`pybind11/pybind11.h` |
|
86 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
87 |
+
| ``int64_t``, ``uint64_t`` | 64-bit integers | :file:`pybind11/pybind11.h` |
|
88 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
89 |
+
| ``ssize_t``, ``size_t`` | Platform-dependent size | :file:`pybind11/pybind11.h` |
|
90 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
91 |
+
| ``float``, ``double`` | Floating point types | :file:`pybind11/pybind11.h` |
|
92 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
93 |
+
| ``bool`` | Two-state Boolean type | :file:`pybind11/pybind11.h` |
|
94 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
95 |
+
| ``char`` | Character literal | :file:`pybind11/pybind11.h` |
|
96 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
97 |
+
| ``char16_t`` | UTF-16 character literal | :file:`pybind11/pybind11.h` |
|
98 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
99 |
+
| ``char32_t`` | UTF-32 character literal | :file:`pybind11/pybind11.h` |
|
100 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
101 |
+
| ``wchar_t`` | Wide character literal | :file:`pybind11/pybind11.h` |
|
102 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
103 |
+
| ``const char *`` | UTF-8 string literal | :file:`pybind11/pybind11.h` |
|
104 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
105 |
+
| ``const char16_t *`` | UTF-16 string literal | :file:`pybind11/pybind11.h` |
|
106 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
107 |
+
| ``const char32_t *`` | UTF-32 string literal | :file:`pybind11/pybind11.h` |
|
108 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
109 |
+
| ``const wchar_t *`` | Wide string literal | :file:`pybind11/pybind11.h` |
|
110 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
111 |
+
| ``std::string`` | STL dynamic UTF-8 string | :file:`pybind11/pybind11.h` |
|
112 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
113 |
+
| ``std::u16string`` | STL dynamic UTF-16 string | :file:`pybind11/pybind11.h` |
|
114 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
115 |
+
| ``std::u32string`` | STL dynamic UTF-32 string | :file:`pybind11/pybind11.h` |
|
116 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
117 |
+
| ``std::wstring`` | STL dynamic wide string | :file:`pybind11/pybind11.h` |
|
118 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
119 |
+
| ``std::string_view``, | STL C++17 string views | :file:`pybind11/pybind11.h` |
|
120 |
+
| ``std::u16string_view``, etc. | | |
|
121 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
122 |
+
| ``std::pair<T1, T2>`` | Pair of two custom types | :file:`pybind11/pybind11.h` |
|
123 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
124 |
+
| ``std::tuple<...>`` | Arbitrary tuple of types | :file:`pybind11/pybind11.h` |
|
125 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
126 |
+
| ``std::reference_wrapper<...>`` | Reference type wrapper | :file:`pybind11/pybind11.h` |
|
127 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
128 |
+
| ``std::complex<T>`` | Complex numbers | :file:`pybind11/complex.h` |
|
129 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
130 |
+
| ``std::array<T, Size>`` | STL static array | :file:`pybind11/stl.h` |
|
131 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
132 |
+
| ``std::vector<T>`` | STL dynamic array | :file:`pybind11/stl.h` |
|
133 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
134 |
+
| ``std::deque<T>`` | STL double-ended queue | :file:`pybind11/stl.h` |
|
135 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
136 |
+
| ``std::valarray<T>`` | STL value array | :file:`pybind11/stl.h` |
|
137 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
138 |
+
| ``std::list<T>`` | STL linked list | :file:`pybind11/stl.h` |
|
139 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
140 |
+
| ``std::map<T1, T2>`` | STL ordered map | :file:`pybind11/stl.h` |
|
141 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
142 |
+
| ``std::unordered_map<T1, T2>`` | STL unordered map | :file:`pybind11/stl.h` |
|
143 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
144 |
+
| ``std::set<T>`` | STL ordered set | :file:`pybind11/stl.h` |
|
145 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
146 |
+
| ``std::unordered_set<T>`` | STL unordered set | :file:`pybind11/stl.h` |
|
147 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
148 |
+
| ``std::optional<T>`` | STL optional type (C++17) | :file:`pybind11/stl.h` |
|
149 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
150 |
+
| ``std::experimental::optional<T>`` | STL optional type (exp.) | :file:`pybind11/stl.h` |
|
151 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
152 |
+
| ``std::variant<...>`` | Type-safe union (C++17) | :file:`pybind11/stl.h` |
|
153 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
154 |
+
| ``std::filesystem::path<T>`` | STL path (C++17) [#]_ | :file:`pybind11/stl/filesystem.h` |
|
155 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
156 |
+
| ``std::function<...>`` | STL polymorphic function | :file:`pybind11/functional.h` |
|
157 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
158 |
+
| ``std::chrono::duration<...>`` | STL time duration | :file:`pybind11/chrono.h` |
|
159 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
160 |
+
| ``std::chrono::time_point<...>`` | STL date/time | :file:`pybind11/chrono.h` |
|
161 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
162 |
+
| ``Eigen::Matrix<...>`` | Eigen: dense matrix | :file:`pybind11/eigen.h` |
|
163 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
164 |
+
| ``Eigen::Map<...>`` | Eigen: mapped memory | :file:`pybind11/eigen.h` |
|
165 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
166 |
+
| ``Eigen::SparseMatrix<...>`` | Eigen: sparse matrix | :file:`pybind11/eigen.h` |
|
167 |
+
+------------------------------------+---------------------------+-----------------------------------+
|
168 |
+
|
169 |
+
.. [#] ``std::filesystem::path`` is converted to ``pathlib.Path`` and
|
170 |
+
``os.PathLike`` is converted to ``std::filesystem::path``.
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/cast/stl.rst
ADDED
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
STL containers
|
2 |
+
##############
|
3 |
+
|
4 |
+
Automatic conversion
|
5 |
+
====================
|
6 |
+
|
7 |
+
When including the additional header file :file:`pybind11/stl.h`, conversions
|
8 |
+
between ``std::vector<>``/``std::deque<>``/``std::list<>``/``std::array<>``/``std::valarray<>``,
|
9 |
+
``std::set<>``/``std::unordered_set<>``, and
|
10 |
+
``std::map<>``/``std::unordered_map<>`` and the Python ``list``, ``set`` and
|
11 |
+
``dict`` data structures are automatically enabled. The types ``std::pair<>``
|
12 |
+
and ``std::tuple<>`` are already supported out of the box with just the core
|
13 |
+
:file:`pybind11/pybind11.h` header.
|
14 |
+
|
15 |
+
The major downside of these implicit conversions is that containers must be
|
16 |
+
converted (i.e. copied) on every Python->C++ and C++->Python transition, which
|
17 |
+
can have implications on the program semantics and performance. Please read the
|
18 |
+
next sections for more details and alternative approaches that avoid this.
|
19 |
+
|
20 |
+
.. note::
|
21 |
+
|
22 |
+
Arbitrary nesting of any of these types is possible.
|
23 |
+
|
24 |
+
.. seealso::
|
25 |
+
|
26 |
+
The file :file:`tests/test_stl.cpp` contains a complete
|
27 |
+
example that demonstrates how to pass STL data types in more detail.
|
28 |
+
|
29 |
+
.. _cpp17_container_casters:
|
30 |
+
|
31 |
+
C++17 library containers
|
32 |
+
========================
|
33 |
+
|
34 |
+
The :file:`pybind11/stl.h` header also includes support for ``std::optional<>``
|
35 |
+
and ``std::variant<>``. These require a C++17 compiler and standard library.
|
36 |
+
In C++14 mode, ``std::experimental::optional<>`` is supported if available.
|
37 |
+
|
38 |
+
Various versions of these containers also exist for C++11 (e.g. in Boost).
|
39 |
+
pybind11 provides an easy way to specialize the ``type_caster`` for such
|
40 |
+
types:
|
41 |
+
|
42 |
+
.. code-block:: cpp
|
43 |
+
|
44 |
+
// `boost::optional` as an example -- can be any `std::optional`-like container
|
45 |
+
namespace pybind11 { namespace detail {
|
46 |
+
template <typename T>
|
47 |
+
struct type_caster<boost::optional<T>> : optional_caster<boost::optional<T>> {};
|
48 |
+
}}
|
49 |
+
|
50 |
+
The above should be placed in a header file and included in all translation units
|
51 |
+
where automatic conversion is needed. Similarly, a specialization can be provided
|
52 |
+
for custom variant types:
|
53 |
+
|
54 |
+
.. code-block:: cpp
|
55 |
+
|
56 |
+
// `boost::variant` as an example -- can be any `std::variant`-like container
|
57 |
+
namespace pybind11 { namespace detail {
|
58 |
+
template <typename... Ts>
|
59 |
+
struct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {};
|
60 |
+
|
61 |
+
// Specifies the function used to visit the variant -- `apply_visitor` instead of `visit`
|
62 |
+
template <>
|
63 |
+
struct visit_helper<boost::variant> {
|
64 |
+
template <typename... Args>
|
65 |
+
static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) {
|
66 |
+
return boost::apply_visitor(args...);
|
67 |
+
}
|
68 |
+
};
|
69 |
+
}} // namespace pybind11::detail
|
70 |
+
|
71 |
+
The ``visit_helper`` specialization is not required if your ``name::variant`` provides
|
72 |
+
a ``name::visit()`` function. For any other function name, the specialization must be
|
73 |
+
included to tell pybind11 how to visit the variant.
|
74 |
+
|
75 |
+
.. warning::
|
76 |
+
|
77 |
+
When converting a ``variant`` type, pybind11 follows the same rules as when
|
78 |
+
determining which function overload to call (:ref:`overload_resolution`), and
|
79 |
+
so the same caveats hold. In particular, the order in which the ``variant``'s
|
80 |
+
alternatives are listed is important, since pybind11 will try conversions in
|
81 |
+
this order. This means that, for example, when converting ``variant<int, bool>``,
|
82 |
+
the ``bool`` variant will never be selected, as any Python ``bool`` is already
|
83 |
+
an ``int`` and is convertible to a C++ ``int``. Changing the order of alternatives
|
84 |
+
(and using ``variant<bool, int>``, in this example) provides a solution.
|
85 |
+
|
86 |
+
.. note::
|
87 |
+
|
88 |
+
pybind11 only supports the modern implementation of ``boost::variant``
|
89 |
+
which makes use of variadic templates. This requires Boost 1.56 or newer.
|
90 |
+
|
91 |
+
.. _opaque:
|
92 |
+
|
93 |
+
Making opaque types
|
94 |
+
===================
|
95 |
+
|
96 |
+
pybind11 heavily relies on a template matching mechanism to convert parameters
|
97 |
+
and return values that are constructed from STL data types such as vectors,
|
98 |
+
linked lists, hash tables, etc. This even works in a recursive manner, for
|
99 |
+
instance to deal with lists of hash maps of pairs of elementary and custom
|
100 |
+
types, etc.
|
101 |
+
|
102 |
+
However, a fundamental limitation of this approach is that internal conversions
|
103 |
+
between Python and C++ types involve a copy operation that prevents
|
104 |
+
pass-by-reference semantics. What does this mean?
|
105 |
+
|
106 |
+
Suppose we bind the following function
|
107 |
+
|
108 |
+
.. code-block:: cpp
|
109 |
+
|
110 |
+
void append_1(std::vector<int> &v) {
|
111 |
+
v.push_back(1);
|
112 |
+
}
|
113 |
+
|
114 |
+
and call it from Python, the following happens:
|
115 |
+
|
116 |
+
.. code-block:: pycon
|
117 |
+
|
118 |
+
>>> v = [5, 6]
|
119 |
+
>>> append_1(v)
|
120 |
+
>>> print(v)
|
121 |
+
[5, 6]
|
122 |
+
|
123 |
+
As you can see, when passing STL data structures by reference, modifications
|
124 |
+
are not propagated back the Python side. A similar situation arises when
|
125 |
+
exposing STL data structures using the ``def_readwrite`` or ``def_readonly``
|
126 |
+
functions:
|
127 |
+
|
128 |
+
.. code-block:: cpp
|
129 |
+
|
130 |
+
/* ... definition ... */
|
131 |
+
|
132 |
+
class MyClass {
|
133 |
+
std::vector<int> contents;
|
134 |
+
};
|
135 |
+
|
136 |
+
/* ... binding code ... */
|
137 |
+
|
138 |
+
py::class_<MyClass>(m, "MyClass")
|
139 |
+
.def(py::init<>())
|
140 |
+
.def_readwrite("contents", &MyClass::contents);
|
141 |
+
|
142 |
+
In this case, properties can be read and written in their entirety. However, an
|
143 |
+
``append`` operation involving such a list type has no effect:
|
144 |
+
|
145 |
+
.. code-block:: pycon
|
146 |
+
|
147 |
+
>>> m = MyClass()
|
148 |
+
>>> m.contents = [5, 6]
|
149 |
+
>>> print(m.contents)
|
150 |
+
[5, 6]
|
151 |
+
>>> m.contents.append(7)
|
152 |
+
>>> print(m.contents)
|
153 |
+
[5, 6]
|
154 |
+
|
155 |
+
Finally, the involved copy operations can be costly when dealing with very
|
156 |
+
large lists. To deal with all of the above situations, pybind11 provides a
|
157 |
+
macro named ``PYBIND11_MAKE_OPAQUE(T)`` that disables the template-based
|
158 |
+
conversion machinery of types, thus rendering them *opaque*. The contents of
|
159 |
+
opaque objects are never inspected or extracted, hence they *can* be passed by
|
160 |
+
reference. For instance, to turn ``std::vector<int>`` into an opaque type, add
|
161 |
+
the declaration
|
162 |
+
|
163 |
+
.. code-block:: cpp
|
164 |
+
|
165 |
+
PYBIND11_MAKE_OPAQUE(std::vector<int>);
|
166 |
+
|
167 |
+
before any binding code (e.g. invocations to ``class_::def()``, etc.). This
|
168 |
+
macro must be specified at the top level (and outside of any namespaces), since
|
169 |
+
it adds a template instantiation of ``type_caster``. If your binding code consists of
|
170 |
+
multiple compilation units, it must be present in every file (typically via a
|
171 |
+
common header) preceding any usage of ``std::vector<int>``. Opaque types must
|
172 |
+
also have a corresponding ``class_`` declaration to associate them with a name
|
173 |
+
in Python, and to define a set of available operations, e.g.:
|
174 |
+
|
175 |
+
.. code-block:: cpp
|
176 |
+
|
177 |
+
py::class_<std::vector<int>>(m, "IntVector")
|
178 |
+
.def(py::init<>())
|
179 |
+
.def("clear", &std::vector<int>::clear)
|
180 |
+
.def("pop_back", &std::vector<int>::pop_back)
|
181 |
+
.def("__len__", [](const std::vector<int> &v) { return v.size(); })
|
182 |
+
.def("__iter__", [](std::vector<int> &v) {
|
183 |
+
return py::make_iterator(v.begin(), v.end());
|
184 |
+
}, py::keep_alive<0, 1>()) /* Keep vector alive while iterator is used */
|
185 |
+
// ....
|
186 |
+
|
187 |
+
.. seealso::
|
188 |
+
|
189 |
+
The file :file:`tests/test_opaque_types.cpp` contains a complete
|
190 |
+
example that demonstrates how to create and expose opaque types using
|
191 |
+
pybind11 in more detail.
|
192 |
+
|
193 |
+
.. _stl_bind:
|
194 |
+
|
195 |
+
Binding STL containers
|
196 |
+
======================
|
197 |
+
|
198 |
+
The ability to expose STL containers as native Python objects is a fairly
|
199 |
+
common request, hence pybind11 also provides an optional header file named
|
200 |
+
:file:`pybind11/stl_bind.h` that does exactly this. The mapped containers try
|
201 |
+
to match the behavior of their native Python counterparts as much as possible.
|
202 |
+
|
203 |
+
The following example showcases usage of :file:`pybind11/stl_bind.h`:
|
204 |
+
|
205 |
+
.. code-block:: cpp
|
206 |
+
|
207 |
+
// Don't forget this
|
208 |
+
#include <pybind11/stl_bind.h>
|
209 |
+
|
210 |
+
PYBIND11_MAKE_OPAQUE(std::vector<int>);
|
211 |
+
PYBIND11_MAKE_OPAQUE(std::map<std::string, double>);
|
212 |
+
|
213 |
+
// ...
|
214 |
+
|
215 |
+
// later in binding code:
|
216 |
+
py::bind_vector<std::vector<int>>(m, "VectorInt");
|
217 |
+
py::bind_map<std::map<std::string, double>>(m, "MapStringDouble");
|
218 |
+
|
219 |
+
When binding STL containers pybind11 considers the types of the container's
|
220 |
+
elements to decide whether the container should be confined to the local module
|
221 |
+
(via the :ref:`module_local` feature). If the container element types are
|
222 |
+
anything other than already-bound custom types bound without
|
223 |
+
``py::module_local()`` the container binding will have ``py::module_local()``
|
224 |
+
applied. This includes converting types such as numeric types, strings, Eigen
|
225 |
+
types; and types that have not yet been bound at the time of the stl container
|
226 |
+
binding. This module-local binding is designed to avoid potential conflicts
|
227 |
+
between module bindings (for example, from two separate modules each attempting
|
228 |
+
to bind ``std::vector<int>`` as a python type).
|
229 |
+
|
230 |
+
It is possible to override this behavior to force a definition to be either
|
231 |
+
module-local or global. To do so, you can pass the attributes
|
232 |
+
``py::module_local()`` (to make the binding module-local) or
|
233 |
+
``py::module_local(false)`` (to make the binding global) into the
|
234 |
+
``py::bind_vector`` or ``py::bind_map`` arguments:
|
235 |
+
|
236 |
+
.. code-block:: cpp
|
237 |
+
|
238 |
+
py::bind_vector<std::vector<int>>(m, "VectorInt", py::module_local(false));
|
239 |
+
|
240 |
+
Note, however, that such a global binding would make it impossible to load this
|
241 |
+
module at the same time as any other pybind module that also attempts to bind
|
242 |
+
the same container type (``std::vector<int>`` in the above example).
|
243 |
+
|
244 |
+
See :ref:`module_local` for more details on module-local bindings.
|
245 |
+
|
246 |
+
.. seealso::
|
247 |
+
|
248 |
+
The file :file:`tests/test_stl_binders.cpp` shows how to use the
|
249 |
+
convenience STL container wrappers.
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/cast/strings.rst
ADDED
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Strings, bytes and Unicode conversions
|
2 |
+
######################################
|
3 |
+
|
4 |
+
Passing Python strings to C++
|
5 |
+
=============================
|
6 |
+
|
7 |
+
When a Python ``str`` is passed from Python to a C++ function that accepts
|
8 |
+
``std::string`` or ``char *`` as arguments, pybind11 will encode the Python
|
9 |
+
string to UTF-8. All Python ``str`` can be encoded in UTF-8, so this operation
|
10 |
+
does not fail.
|
11 |
+
|
12 |
+
The C++ language is encoding agnostic. It is the responsibility of the
|
13 |
+
programmer to track encodings. It's often easiest to simply `use UTF-8
|
14 |
+
everywhere <http://utf8everywhere.org/>`_.
|
15 |
+
|
16 |
+
.. code-block:: c++
|
17 |
+
|
18 |
+
m.def("utf8_test",
|
19 |
+
[](const std::string &s) {
|
20 |
+
cout << "utf-8 is icing on the cake.\n";
|
21 |
+
cout << s;
|
22 |
+
}
|
23 |
+
);
|
24 |
+
m.def("utf8_charptr",
|
25 |
+
[](const char *s) {
|
26 |
+
cout << "My favorite food is\n";
|
27 |
+
cout << s;
|
28 |
+
}
|
29 |
+
);
|
30 |
+
|
31 |
+
.. code-block:: pycon
|
32 |
+
|
33 |
+
>>> utf8_test("🎂")
|
34 |
+
utf-8 is icing on the cake.
|
35 |
+
🎂
|
36 |
+
|
37 |
+
>>> utf8_charptr("🍕")
|
38 |
+
My favorite food is
|
39 |
+
🍕
|
40 |
+
|
41 |
+
.. note::
|
42 |
+
|
43 |
+
Some terminal emulators do not support UTF-8 or emoji fonts and may not
|
44 |
+
display the example above correctly.
|
45 |
+
|
46 |
+
The results are the same whether the C++ function accepts arguments by value or
|
47 |
+
reference, and whether or not ``const`` is used.
|
48 |
+
|
49 |
+
Passing bytes to C++
|
50 |
+
--------------------
|
51 |
+
|
52 |
+
A Python ``bytes`` object will be passed to C++ functions that accept
|
53 |
+
``std::string`` or ``char*`` *without* conversion. In order to make a function
|
54 |
+
*only* accept ``bytes`` (and not ``str``), declare it as taking a ``py::bytes``
|
55 |
+
argument.
|
56 |
+
|
57 |
+
|
58 |
+
Returning C++ strings to Python
|
59 |
+
===============================
|
60 |
+
|
61 |
+
When a C++ function returns a ``std::string`` or ``char*`` to a Python caller,
|
62 |
+
**pybind11 will assume that the string is valid UTF-8** and will decode it to a
|
63 |
+
native Python ``str``, using the same API as Python uses to perform
|
64 |
+
``bytes.decode('utf-8')``. If this implicit conversion fails, pybind11 will
|
65 |
+
raise a ``UnicodeDecodeError``.
|
66 |
+
|
67 |
+
.. code-block:: c++
|
68 |
+
|
69 |
+
m.def("std_string_return",
|
70 |
+
[]() {
|
71 |
+
return std::string("This string needs to be UTF-8 encoded");
|
72 |
+
}
|
73 |
+
);
|
74 |
+
|
75 |
+
.. code-block:: pycon
|
76 |
+
|
77 |
+
>>> isinstance(example.std_string_return(), str)
|
78 |
+
True
|
79 |
+
|
80 |
+
|
81 |
+
Because UTF-8 is inclusive of pure ASCII, there is never any issue with
|
82 |
+
returning a pure ASCII string to Python. If there is any possibility that the
|
83 |
+
string is not pure ASCII, it is necessary to ensure the encoding is valid
|
84 |
+
UTF-8.
|
85 |
+
|
86 |
+
.. warning::
|
87 |
+
|
88 |
+
Implicit conversion assumes that a returned ``char *`` is null-terminated.
|
89 |
+
If there is no null terminator a buffer overrun will occur.
|
90 |
+
|
91 |
+
Explicit conversions
|
92 |
+
--------------------
|
93 |
+
|
94 |
+
If some C++ code constructs a ``std::string`` that is not a UTF-8 string, one
|
95 |
+
can perform a explicit conversion and return a ``py::str`` object. Explicit
|
96 |
+
conversion has the same overhead as implicit conversion.
|
97 |
+
|
98 |
+
.. code-block:: c++
|
99 |
+
|
100 |
+
// This uses the Python C API to convert Latin-1 to Unicode
|
101 |
+
m.def("str_output",
|
102 |
+
[]() {
|
103 |
+
std::string s = "Send your r\xe9sum\xe9 to Alice in HR"; // Latin-1
|
104 |
+
py::str py_s = PyUnicode_DecodeLatin1(s.data(), s.length());
|
105 |
+
return py_s;
|
106 |
+
}
|
107 |
+
);
|
108 |
+
|
109 |
+
.. code-block:: pycon
|
110 |
+
|
111 |
+
>>> str_output()
|
112 |
+
'Send your résumé to Alice in HR'
|
113 |
+
|
114 |
+
The `Python C API
|
115 |
+
<https://docs.python.org/3/c-api/unicode.html#built-in-codecs>`_ provides
|
116 |
+
several built-in codecs.
|
117 |
+
|
118 |
+
|
119 |
+
One could also use a third party encoding library such as libiconv to transcode
|
120 |
+
to UTF-8.
|
121 |
+
|
122 |
+
Return C++ strings without conversion
|
123 |
+
-------------------------------------
|
124 |
+
|
125 |
+
If the data in a C++ ``std::string`` does not represent text and should be
|
126 |
+
returned to Python as ``bytes``, then one can return the data as a
|
127 |
+
``py::bytes`` object.
|
128 |
+
|
129 |
+
.. code-block:: c++
|
130 |
+
|
131 |
+
m.def("return_bytes",
|
132 |
+
[]() {
|
133 |
+
std::string s("\xba\xd0\xba\xd0"); // Not valid UTF-8
|
134 |
+
return py::bytes(s); // Return the data without transcoding
|
135 |
+
}
|
136 |
+
);
|
137 |
+
|
138 |
+
.. code-block:: pycon
|
139 |
+
|
140 |
+
>>> example.return_bytes()
|
141 |
+
b'\xba\xd0\xba\xd0'
|
142 |
+
|
143 |
+
|
144 |
+
Note the asymmetry: pybind11 will convert ``bytes`` to ``std::string`` without
|
145 |
+
encoding, but cannot convert ``std::string`` back to ``bytes`` implicitly.
|
146 |
+
|
147 |
+
.. code-block:: c++
|
148 |
+
|
149 |
+
m.def("asymmetry",
|
150 |
+
[](std::string s) { // Accepts str or bytes from Python
|
151 |
+
return s; // Looks harmless, but implicitly converts to str
|
152 |
+
}
|
153 |
+
);
|
154 |
+
|
155 |
+
.. code-block:: pycon
|
156 |
+
|
157 |
+
>>> isinstance(example.asymmetry(b"have some bytes"), str)
|
158 |
+
True
|
159 |
+
|
160 |
+
>>> example.asymmetry(b"\xba\xd0\xba\xd0") # invalid utf-8 as bytes
|
161 |
+
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 0: invalid start byte
|
162 |
+
|
163 |
+
|
164 |
+
Wide character strings
|
165 |
+
======================
|
166 |
+
|
167 |
+
When a Python ``str`` is passed to a C++ function expecting ``std::wstring``,
|
168 |
+
``wchar_t*``, ``std::u16string`` or ``std::u32string``, the ``str`` will be
|
169 |
+
encoded to UTF-16 or UTF-32 depending on how the C++ compiler implements each
|
170 |
+
type, in the platform's native endianness. When strings of these types are
|
171 |
+
returned, they are assumed to contain valid UTF-16 or UTF-32, and will be
|
172 |
+
decoded to Python ``str``.
|
173 |
+
|
174 |
+
.. code-block:: c++
|
175 |
+
|
176 |
+
#define UNICODE
|
177 |
+
#include <windows.h>
|
178 |
+
|
179 |
+
m.def("set_window_text",
|
180 |
+
[](HWND hwnd, std::wstring s) {
|
181 |
+
// Call SetWindowText with null-terminated UTF-16 string
|
182 |
+
::SetWindowText(hwnd, s.c_str());
|
183 |
+
}
|
184 |
+
);
|
185 |
+
m.def("get_window_text",
|
186 |
+
[](HWND hwnd) {
|
187 |
+
const int buffer_size = ::GetWindowTextLength(hwnd) + 1;
|
188 |
+
auto buffer = std::make_unique< wchar_t[] >(buffer_size);
|
189 |
+
|
190 |
+
::GetWindowText(hwnd, buffer.data(), buffer_size);
|
191 |
+
|
192 |
+
std::wstring text(buffer.get());
|
193 |
+
|
194 |
+
// wstring will be converted to Python str
|
195 |
+
return text;
|
196 |
+
}
|
197 |
+
);
|
198 |
+
|
199 |
+
Strings in multibyte encodings such as Shift-JIS must transcoded to a
|
200 |
+
UTF-8/16/32 before being returned to Python.
|
201 |
+
|
202 |
+
|
203 |
+
Character literals
|
204 |
+
==================
|
205 |
+
|
206 |
+
C++ functions that accept character literals as input will receive the first
|
207 |
+
character of a Python ``str`` as their input. If the string is longer than one
|
208 |
+
Unicode character, trailing characters will be ignored.
|
209 |
+
|
210 |
+
When a character literal is returned from C++ (such as a ``char`` or a
|
211 |
+
``wchar_t``), it will be converted to a ``str`` that represents the single
|
212 |
+
character.
|
213 |
+
|
214 |
+
.. code-block:: c++
|
215 |
+
|
216 |
+
m.def("pass_char", [](char c) { return c; });
|
217 |
+
m.def("pass_wchar", [](wchar_t w) { return w; });
|
218 |
+
|
219 |
+
.. code-block:: pycon
|
220 |
+
|
221 |
+
>>> example.pass_char("A")
|
222 |
+
'A'
|
223 |
+
|
224 |
+
While C++ will cast integers to character types (``char c = 0x65;``), pybind11
|
225 |
+
does not convert Python integers to characters implicitly. The Python function
|
226 |
+
``chr()`` can be used to convert integers to characters.
|
227 |
+
|
228 |
+
.. code-block:: pycon
|
229 |
+
|
230 |
+
>>> example.pass_char(0x65)
|
231 |
+
TypeError
|
232 |
+
|
233 |
+
>>> example.pass_char(chr(0x65))
|
234 |
+
'A'
|
235 |
+
|
236 |
+
If the desire is to work with an 8-bit integer, use ``int8_t`` or ``uint8_t``
|
237 |
+
as the argument type.
|
238 |
+
|
239 |
+
Grapheme clusters
|
240 |
+
-----------------
|
241 |
+
|
242 |
+
A single grapheme may be represented by two or more Unicode characters. For
|
243 |
+
example 'é' is usually represented as U+00E9 but can also be expressed as the
|
244 |
+
combining character sequence U+0065 U+0301 (that is, the letter 'e' followed by
|
245 |
+
a combining acute accent). The combining character will be lost if the
|
246 |
+
two-character sequence is passed as an argument, even though it renders as a
|
247 |
+
single grapheme.
|
248 |
+
|
249 |
+
.. code-block:: pycon
|
250 |
+
|
251 |
+
>>> example.pass_wchar("é")
|
252 |
+
'é'
|
253 |
+
|
254 |
+
>>> combining_e_acute = "e" + "\u0301"
|
255 |
+
|
256 |
+
>>> combining_e_acute
|
257 |
+
'é'
|
258 |
+
|
259 |
+
>>> combining_e_acute == "é"
|
260 |
+
False
|
261 |
+
|
262 |
+
>>> example.pass_wchar(combining_e_acute)
|
263 |
+
'e'
|
264 |
+
|
265 |
+
Normalizing combining characters before passing the character literal to C++
|
266 |
+
may resolve *some* of these issues:
|
267 |
+
|
268 |
+
.. code-block:: pycon
|
269 |
+
|
270 |
+
>>> example.pass_wchar(unicodedata.normalize("NFC", combining_e_acute))
|
271 |
+
'é'
|
272 |
+
|
273 |
+
In some languages (Thai for example), there are `graphemes that cannot be
|
274 |
+
expressed as a single Unicode code point
|
275 |
+
<http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries>`_, so there is
|
276 |
+
no way to capture them in a C++ character type.
|
277 |
+
|
278 |
+
|
279 |
+
C++17 string views
|
280 |
+
==================
|
281 |
+
|
282 |
+
C++17 string views are automatically supported when compiling in C++17 mode.
|
283 |
+
They follow the same rules for encoding and decoding as the corresponding STL
|
284 |
+
string type (for example, a ``std::u16string_view`` argument will be passed
|
285 |
+
UTF-16-encoded data, and a returned ``std::string_view`` will be decoded as
|
286 |
+
UTF-8).
|
287 |
+
|
288 |
+
References
|
289 |
+
==========
|
290 |
+
|
291 |
+
* `The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) <https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/>`_
|
292 |
+
* `C++ - Using STL Strings at Win32 API Boundaries <https://msdn.microsoft.com/en-ca/magazine/mt238407.aspx>`_
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/classes.rst
ADDED
@@ -0,0 +1,1335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Classes
|
2 |
+
#######
|
3 |
+
|
4 |
+
This section presents advanced binding code for classes and it is assumed
|
5 |
+
that you are already familiar with the basics from :doc:`/classes`.
|
6 |
+
|
7 |
+
.. _overriding_virtuals:
|
8 |
+
|
9 |
+
Overriding virtual functions in Python
|
10 |
+
======================================
|
11 |
+
|
12 |
+
Suppose that a C++ class or interface has a virtual function that we'd like
|
13 |
+
to override from within Python (we'll focus on the class ``Animal``; ``Dog`` is
|
14 |
+
given as a specific example of how one would do this with traditional C++
|
15 |
+
code).
|
16 |
+
|
17 |
+
.. code-block:: cpp
|
18 |
+
|
19 |
+
class Animal {
|
20 |
+
public:
|
21 |
+
virtual ~Animal() { }
|
22 |
+
virtual std::string go(int n_times) = 0;
|
23 |
+
};
|
24 |
+
|
25 |
+
class Dog : public Animal {
|
26 |
+
public:
|
27 |
+
std::string go(int n_times) override {
|
28 |
+
std::string result;
|
29 |
+
for (int i=0; i<n_times; ++i)
|
30 |
+
result += "woof! ";
|
31 |
+
return result;
|
32 |
+
}
|
33 |
+
};
|
34 |
+
|
35 |
+
Let's also suppose that we are given a plain function which calls the
|
36 |
+
function ``go()`` on an arbitrary ``Animal`` instance.
|
37 |
+
|
38 |
+
.. code-block:: cpp
|
39 |
+
|
40 |
+
std::string call_go(Animal *animal) {
|
41 |
+
return animal->go(3);
|
42 |
+
}
|
43 |
+
|
44 |
+
Normally, the binding code for these classes would look as follows:
|
45 |
+
|
46 |
+
.. code-block:: cpp
|
47 |
+
|
48 |
+
PYBIND11_MODULE(example, m) {
|
49 |
+
py::class_<Animal>(m, "Animal")
|
50 |
+
.def("go", &Animal::go);
|
51 |
+
|
52 |
+
py::class_<Dog, Animal>(m, "Dog")
|
53 |
+
.def(py::init<>());
|
54 |
+
|
55 |
+
m.def("call_go", &call_go);
|
56 |
+
}
|
57 |
+
|
58 |
+
However, these bindings are impossible to extend: ``Animal`` is not
|
59 |
+
constructible, and we clearly require some kind of "trampoline" that
|
60 |
+
redirects virtual calls back to Python.
|
61 |
+
|
62 |
+
Defining a new type of ``Animal`` from within Python is possible but requires a
|
63 |
+
helper class that is defined as follows:
|
64 |
+
|
65 |
+
.. code-block:: cpp
|
66 |
+
|
67 |
+
class PyAnimal : public Animal {
|
68 |
+
public:
|
69 |
+
/* Inherit the constructors */
|
70 |
+
using Animal::Animal;
|
71 |
+
|
72 |
+
/* Trampoline (need one for each virtual function) */
|
73 |
+
std::string go(int n_times) override {
|
74 |
+
PYBIND11_OVERRIDE_PURE(
|
75 |
+
std::string, /* Return type */
|
76 |
+
Animal, /* Parent class */
|
77 |
+
go, /* Name of function in C++ (must match Python name) */
|
78 |
+
n_times /* Argument(s) */
|
79 |
+
);
|
80 |
+
}
|
81 |
+
};
|
82 |
+
|
83 |
+
The macro :c:macro:`PYBIND11_OVERRIDE_PURE` should be used for pure virtual
|
84 |
+
functions, and :c:macro:`PYBIND11_OVERRIDE` should be used for functions which have
|
85 |
+
a default implementation. There are also two alternate macros
|
86 |
+
:c:macro:`PYBIND11_OVERRIDE_PURE_NAME` and :c:macro:`PYBIND11_OVERRIDE_NAME` which
|
87 |
+
take a string-valued name argument between the *Parent class* and *Name of the
|
88 |
+
function* slots, which defines the name of function in Python. This is required
|
89 |
+
when the C++ and Python versions of the
|
90 |
+
function have different names, e.g. ``operator()`` vs ``__call__``.
|
91 |
+
|
92 |
+
The binding code also needs a few minor adaptations (highlighted):
|
93 |
+
|
94 |
+
.. code-block:: cpp
|
95 |
+
:emphasize-lines: 2,3
|
96 |
+
|
97 |
+
PYBIND11_MODULE(example, m) {
|
98 |
+
py::class_<Animal, PyAnimal /* <--- trampoline*/>(m, "Animal")
|
99 |
+
.def(py::init<>())
|
100 |
+
.def("go", &Animal::go);
|
101 |
+
|
102 |
+
py::class_<Dog, Animal>(m, "Dog")
|
103 |
+
.def(py::init<>());
|
104 |
+
|
105 |
+
m.def("call_go", &call_go);
|
106 |
+
}
|
107 |
+
|
108 |
+
Importantly, pybind11 is made aware of the trampoline helper class by
|
109 |
+
specifying it as an extra template argument to :class:`class_`. (This can also
|
110 |
+
be combined with other template arguments such as a custom holder type; the
|
111 |
+
order of template types does not matter). Following this, we are able to
|
112 |
+
define a constructor as usual.
|
113 |
+
|
114 |
+
Bindings should be made against the actual class, not the trampoline helper class.
|
115 |
+
|
116 |
+
.. code-block:: cpp
|
117 |
+
:emphasize-lines: 3
|
118 |
+
|
119 |
+
py::class_<Animal, PyAnimal /* <--- trampoline*/>(m, "Animal");
|
120 |
+
.def(py::init<>())
|
121 |
+
.def("go", &PyAnimal::go); /* <--- THIS IS WRONG, use &Animal::go */
|
122 |
+
|
123 |
+
Note, however, that the above is sufficient for allowing python classes to
|
124 |
+
extend ``Animal``, but not ``Dog``: see :ref:`virtual_and_inheritance` for the
|
125 |
+
necessary steps required to providing proper overriding support for inherited
|
126 |
+
classes.
|
127 |
+
|
128 |
+
The Python session below shows how to override ``Animal::go`` and invoke it via
|
129 |
+
a virtual method call.
|
130 |
+
|
131 |
+
.. code-block:: pycon
|
132 |
+
|
133 |
+
>>> from example import *
|
134 |
+
>>> d = Dog()
|
135 |
+
>>> call_go(d)
|
136 |
+
'woof! woof! woof! '
|
137 |
+
>>> class Cat(Animal):
|
138 |
+
... def go(self, n_times):
|
139 |
+
... return "meow! " * n_times
|
140 |
+
...
|
141 |
+
>>> c = Cat()
|
142 |
+
>>> call_go(c)
|
143 |
+
'meow! meow! meow! '
|
144 |
+
|
145 |
+
If you are defining a custom constructor in a derived Python class, you *must*
|
146 |
+
ensure that you explicitly call the bound C++ constructor using ``__init__``,
|
147 |
+
*regardless* of whether it is a default constructor or not. Otherwise, the
|
148 |
+
memory for the C++ portion of the instance will be left uninitialized, which
|
149 |
+
will generally leave the C++ instance in an invalid state and cause undefined
|
150 |
+
behavior if the C++ instance is subsequently used.
|
151 |
+
|
152 |
+
.. versionchanged:: 2.6
|
153 |
+
The default pybind11 metaclass will throw a ``TypeError`` when it detects
|
154 |
+
that ``__init__`` was not called by a derived class.
|
155 |
+
|
156 |
+
Here is an example:
|
157 |
+
|
158 |
+
.. code-block:: python
|
159 |
+
|
160 |
+
class Dachshund(Dog):
|
161 |
+
def __init__(self, name):
|
162 |
+
Dog.__init__(self) # Without this, a TypeError is raised.
|
163 |
+
self.name = name
|
164 |
+
|
165 |
+
def bark(self):
|
166 |
+
return "yap!"
|
167 |
+
|
168 |
+
Note that a direct ``__init__`` constructor *should be called*, and ``super()``
|
169 |
+
should not be used. For simple cases of linear inheritance, ``super()``
|
170 |
+
may work, but once you begin mixing Python and C++ multiple inheritance,
|
171 |
+
things will fall apart due to differences between Python's MRO and C++'s
|
172 |
+
mechanisms.
|
173 |
+
|
174 |
+
Please take a look at the :ref:`macro_notes` before using this feature.
|
175 |
+
|
176 |
+
.. note::
|
177 |
+
|
178 |
+
When the overridden type returns a reference or pointer to a type that
|
179 |
+
pybind11 converts from Python (for example, numeric values, std::string,
|
180 |
+
and other built-in value-converting types), there are some limitations to
|
181 |
+
be aware of:
|
182 |
+
|
183 |
+
- because in these cases there is no C++ variable to reference (the value
|
184 |
+
is stored in the referenced Python variable), pybind11 provides one in
|
185 |
+
the PYBIND11_OVERRIDE macros (when needed) with static storage duration.
|
186 |
+
Note that this means that invoking the overridden method on *any*
|
187 |
+
instance will change the referenced value stored in *all* instances of
|
188 |
+
that type.
|
189 |
+
|
190 |
+
- Attempts to modify a non-const reference will not have the desired
|
191 |
+
effect: it will change only the static cache variable, but this change
|
192 |
+
will not propagate to underlying Python instance, and the change will be
|
193 |
+
replaced the next time the override is invoked.
|
194 |
+
|
195 |
+
.. warning::
|
196 |
+
|
197 |
+
The :c:macro:`PYBIND11_OVERRIDE` and accompanying macros used to be called
|
198 |
+
``PYBIND11_OVERLOAD`` up until pybind11 v2.5.0, and :func:`get_override`
|
199 |
+
used to be called ``get_overload``. This naming was corrected and the older
|
200 |
+
macro and function names may soon be deprecated, in order to reduce
|
201 |
+
confusion with overloaded functions and methods and ``py::overload_cast``
|
202 |
+
(see :ref:`classes`).
|
203 |
+
|
204 |
+
.. seealso::
|
205 |
+
|
206 |
+
The file :file:`tests/test_virtual_functions.cpp` contains a complete
|
207 |
+
example that demonstrates how to override virtual functions using pybind11
|
208 |
+
in more detail.
|
209 |
+
|
210 |
+
.. _virtual_and_inheritance:
|
211 |
+
|
212 |
+
Combining virtual functions and inheritance
|
213 |
+
===========================================
|
214 |
+
|
215 |
+
When combining virtual methods with inheritance, you need to be sure to provide
|
216 |
+
an override for each method for which you want to allow overrides from derived
|
217 |
+
python classes. For example, suppose we extend the above ``Animal``/``Dog``
|
218 |
+
example as follows:
|
219 |
+
|
220 |
+
.. code-block:: cpp
|
221 |
+
|
222 |
+
class Animal {
|
223 |
+
public:
|
224 |
+
virtual std::string go(int n_times) = 0;
|
225 |
+
virtual std::string name() { return "unknown"; }
|
226 |
+
};
|
227 |
+
class Dog : public Animal {
|
228 |
+
public:
|
229 |
+
std::string go(int n_times) override {
|
230 |
+
std::string result;
|
231 |
+
for (int i=0; i<n_times; ++i)
|
232 |
+
result += bark() + " ";
|
233 |
+
return result;
|
234 |
+
}
|
235 |
+
virtual std::string bark() { return "woof!"; }
|
236 |
+
};
|
237 |
+
|
238 |
+
then the trampoline class for ``Animal`` must, as described in the previous
|
239 |
+
section, override ``go()`` and ``name()``, but in order to allow python code to
|
240 |
+
inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that
|
241 |
+
overrides both the added ``bark()`` method *and* the ``go()`` and ``name()``
|
242 |
+
methods inherited from ``Animal`` (even though ``Dog`` doesn't directly
|
243 |
+
override the ``name()`` method):
|
244 |
+
|
245 |
+
.. code-block:: cpp
|
246 |
+
|
247 |
+
class PyAnimal : public Animal {
|
248 |
+
public:
|
249 |
+
using Animal::Animal; // Inherit constructors
|
250 |
+
std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Animal, go, n_times); }
|
251 |
+
std::string name() override { PYBIND11_OVERRIDE(std::string, Animal, name, ); }
|
252 |
+
};
|
253 |
+
class PyDog : public Dog {
|
254 |
+
public:
|
255 |
+
using Dog::Dog; // Inherit constructors
|
256 |
+
std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, Dog, go, n_times); }
|
257 |
+
std::string name() override { PYBIND11_OVERRIDE(std::string, Dog, name, ); }
|
258 |
+
std::string bark() override { PYBIND11_OVERRIDE(std::string, Dog, bark, ); }
|
259 |
+
};
|
260 |
+
|
261 |
+
.. note::
|
262 |
+
|
263 |
+
Note the trailing commas in the ``PYBIND11_OVERRIDE`` calls to ``name()``
|
264 |
+
and ``bark()``. These are needed to portably implement a trampoline for a
|
265 |
+
function that does not take any arguments. For functions that take
|
266 |
+
a nonzero number of arguments, the trailing comma must be omitted.
|
267 |
+
|
268 |
+
A registered class derived from a pybind11-registered class with virtual
|
269 |
+
methods requires a similar trampoline class, *even if* it doesn't explicitly
|
270 |
+
declare or override any virtual methods itself:
|
271 |
+
|
272 |
+
.. code-block:: cpp
|
273 |
+
|
274 |
+
class Husky : public Dog {};
|
275 |
+
class PyHusky : public Husky {
|
276 |
+
public:
|
277 |
+
using Husky::Husky; // Inherit constructors
|
278 |
+
std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Husky, go, n_times); }
|
279 |
+
std::string name() override { PYBIND11_OVERRIDE(std::string, Husky, name, ); }
|
280 |
+
std::string bark() override { PYBIND11_OVERRIDE(std::string, Husky, bark, ); }
|
281 |
+
};
|
282 |
+
|
283 |
+
There is, however, a technique that can be used to avoid this duplication
|
284 |
+
(which can be especially helpful for a base class with several virtual
|
285 |
+
methods). The technique involves using template trampoline classes, as
|
286 |
+
follows:
|
287 |
+
|
288 |
+
.. code-block:: cpp
|
289 |
+
|
290 |
+
template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
|
291 |
+
public:
|
292 |
+
using AnimalBase::AnimalBase; // Inherit constructors
|
293 |
+
std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, AnimalBase, go, n_times); }
|
294 |
+
std::string name() override { PYBIND11_OVERRIDE(std::string, AnimalBase, name, ); }
|
295 |
+
};
|
296 |
+
template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
|
297 |
+
public:
|
298 |
+
using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
|
299 |
+
// Override PyAnimal's pure virtual go() with a non-pure one:
|
300 |
+
std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, DogBase, go, n_times); }
|
301 |
+
std::string bark() override { PYBIND11_OVERRIDE(std::string, DogBase, bark, ); }
|
302 |
+
};
|
303 |
+
|
304 |
+
This technique has the advantage of requiring just one trampoline method to be
|
305 |
+
declared per virtual method and pure virtual method override. It does,
|
306 |
+
however, require the compiler to generate at least as many methods (and
|
307 |
+
possibly more, if both pure virtual and overridden pure virtual methods are
|
308 |
+
exposed, as above).
|
309 |
+
|
310 |
+
The classes are then registered with pybind11 using:
|
311 |
+
|
312 |
+
.. code-block:: cpp
|
313 |
+
|
314 |
+
py::class_<Animal, PyAnimal<>> animal(m, "Animal");
|
315 |
+
py::class_<Dog, Animal, PyDog<>> dog(m, "Dog");
|
316 |
+
py::class_<Husky, Dog, PyDog<Husky>> husky(m, "Husky");
|
317 |
+
// ... add animal, dog, husky definitions
|
318 |
+
|
319 |
+
Note that ``Husky`` did not require a dedicated trampoline template class at
|
320 |
+
all, since it neither declares any new virtual methods nor provides any pure
|
321 |
+
virtual method implementations.
|
322 |
+
|
323 |
+
With either the repeated-virtuals or templated trampoline methods in place, you
|
324 |
+
can now create a python class that inherits from ``Dog``:
|
325 |
+
|
326 |
+
.. code-block:: python
|
327 |
+
|
328 |
+
class ShihTzu(Dog):
|
329 |
+
def bark(self):
|
330 |
+
return "yip!"
|
331 |
+
|
332 |
+
.. seealso::
|
333 |
+
|
334 |
+
See the file :file:`tests/test_virtual_functions.cpp` for complete examples
|
335 |
+
using both the duplication and templated trampoline approaches.
|
336 |
+
|
337 |
+
.. _extended_aliases:
|
338 |
+
|
339 |
+
Extended trampoline class functionality
|
340 |
+
=======================================
|
341 |
+
|
342 |
+
.. _extended_class_functionality_forced_trampoline:
|
343 |
+
|
344 |
+
Forced trampoline class initialisation
|
345 |
+
--------------------------------------
|
346 |
+
The trampoline classes described in the previous sections are, by default, only
|
347 |
+
initialized when needed. More specifically, they are initialized when a python
|
348 |
+
class actually inherits from a registered type (instead of merely creating an
|
349 |
+
instance of the registered type), or when a registered constructor is only
|
350 |
+
valid for the trampoline class but not the registered class. This is primarily
|
351 |
+
for performance reasons: when the trampoline class is not needed for anything
|
352 |
+
except virtual method dispatching, not initializing the trampoline class
|
353 |
+
improves performance by avoiding needing to do a run-time check to see if the
|
354 |
+
inheriting python instance has an overridden method.
|
355 |
+
|
356 |
+
Sometimes, however, it is useful to always initialize a trampoline class as an
|
357 |
+
intermediate class that does more than just handle virtual method dispatching.
|
358 |
+
For example, such a class might perform extra class initialization, extra
|
359 |
+
destruction operations, and might define new members and methods to enable a
|
360 |
+
more python-like interface to a class.
|
361 |
+
|
362 |
+
In order to tell pybind11 that it should *always* initialize the trampoline
|
363 |
+
class when creating new instances of a type, the class constructors should be
|
364 |
+
declared using ``py::init_alias<Args, ...>()`` instead of the usual
|
365 |
+
``py::init<Args, ...>()``. This forces construction via the trampoline class,
|
366 |
+
ensuring member initialization and (eventual) destruction.
|
367 |
+
|
368 |
+
.. seealso::
|
369 |
+
|
370 |
+
See the file :file:`tests/test_virtual_functions.cpp` for complete examples
|
371 |
+
showing both normal and forced trampoline instantiation.
|
372 |
+
|
373 |
+
Different method signatures
|
374 |
+
---------------------------
|
375 |
+
The macro's introduced in :ref:`overriding_virtuals` cover most of the standard
|
376 |
+
use cases when exposing C++ classes to Python. Sometimes it is hard or unwieldy
|
377 |
+
to create a direct one-on-one mapping between the arguments and method return
|
378 |
+
type.
|
379 |
+
|
380 |
+
An example would be when the C++ signature contains output arguments using
|
381 |
+
references (See also :ref:`faq_reference_arguments`). Another way of solving
|
382 |
+
this is to use the method body of the trampoline class to do conversions to the
|
383 |
+
input and return of the Python method.
|
384 |
+
|
385 |
+
The main building block to do so is the :func:`get_override`, this function
|
386 |
+
allows retrieving a method implemented in Python from within the trampoline's
|
387 |
+
methods. Consider for example a C++ method which has the signature
|
388 |
+
``bool myMethod(int32_t& value)``, where the return indicates whether
|
389 |
+
something should be done with the ``value``. This can be made convenient on the
|
390 |
+
Python side by allowing the Python function to return ``None`` or an ``int``:
|
391 |
+
|
392 |
+
.. code-block:: cpp
|
393 |
+
|
394 |
+
bool MyClass::myMethod(int32_t& value)
|
395 |
+
{
|
396 |
+
pybind11::gil_scoped_acquire gil; // Acquire the GIL while in this scope.
|
397 |
+
// Try to look up the overridden method on the Python side.
|
398 |
+
pybind11::function override = pybind11::get_override(this, "myMethod");
|
399 |
+
if (override) { // method is found
|
400 |
+
auto obj = override(value); // Call the Python function.
|
401 |
+
if (py::isinstance<py::int_>(obj)) { // check if it returned a Python integer type
|
402 |
+
value = obj.cast<int32_t>(); // Cast it and assign it to the value.
|
403 |
+
return true; // Return true; value should be used.
|
404 |
+
} else {
|
405 |
+
return false; // Python returned none, return false.
|
406 |
+
}
|
407 |
+
}
|
408 |
+
return false; // Alternatively return MyClass::myMethod(value);
|
409 |
+
}
|
410 |
+
|
411 |
+
|
412 |
+
.. _custom_constructors:
|
413 |
+
|
414 |
+
Custom constructors
|
415 |
+
===================
|
416 |
+
|
417 |
+
The syntax for binding constructors was previously introduced, but it only
|
418 |
+
works when a constructor of the appropriate arguments actually exists on the
|
419 |
+
C++ side. To extend this to more general cases, pybind11 makes it possible
|
420 |
+
to bind factory functions as constructors. For example, suppose you have a
|
421 |
+
class like this:
|
422 |
+
|
423 |
+
.. code-block:: cpp
|
424 |
+
|
425 |
+
class Example {
|
426 |
+
private:
|
427 |
+
Example(int); // private constructor
|
428 |
+
public:
|
429 |
+
// Factory function:
|
430 |
+
static Example create(int a) { return Example(a); }
|
431 |
+
};
|
432 |
+
|
433 |
+
py::class_<Example>(m, "Example")
|
434 |
+
.def(py::init(&Example::create));
|
435 |
+
|
436 |
+
While it is possible to create a straightforward binding of the static
|
437 |
+
``create`` method, it may sometimes be preferable to expose it as a constructor
|
438 |
+
on the Python side. This can be accomplished by calling ``.def(py::init(...))``
|
439 |
+
with the function reference returning the new instance passed as an argument.
|
440 |
+
It is also possible to use this approach to bind a function returning a new
|
441 |
+
instance by raw pointer or by the holder (e.g. ``std::unique_ptr``).
|
442 |
+
|
443 |
+
The following example shows the different approaches:
|
444 |
+
|
445 |
+
.. code-block:: cpp
|
446 |
+
|
447 |
+
class Example {
|
448 |
+
private:
|
449 |
+
Example(int); // private constructor
|
450 |
+
public:
|
451 |
+
// Factory function - returned by value:
|
452 |
+
static Example create(int a) { return Example(a); }
|
453 |
+
|
454 |
+
// These constructors are publicly callable:
|
455 |
+
Example(double);
|
456 |
+
Example(int, int);
|
457 |
+
Example(std::string);
|
458 |
+
};
|
459 |
+
|
460 |
+
py::class_<Example>(m, "Example")
|
461 |
+
// Bind the factory function as a constructor:
|
462 |
+
.def(py::init(&Example::create))
|
463 |
+
// Bind a lambda function returning a pointer wrapped in a holder:
|
464 |
+
.def(py::init([](std::string arg) {
|
465 |
+
return std::unique_ptr<Example>(new Example(arg));
|
466 |
+
}))
|
467 |
+
// Return a raw pointer:
|
468 |
+
.def(py::init([](int a, int b) { return new Example(a, b); }))
|
469 |
+
// You can mix the above with regular C++ constructor bindings as well:
|
470 |
+
.def(py::init<double>())
|
471 |
+
;
|
472 |
+
|
473 |
+
When the constructor is invoked from Python, pybind11 will call the factory
|
474 |
+
function and store the resulting C++ instance in the Python instance.
|
475 |
+
|
476 |
+
When combining factory functions constructors with :ref:`virtual function
|
477 |
+
trampolines <overriding_virtuals>` there are two approaches. The first is to
|
478 |
+
add a constructor to the alias class that takes a base value by
|
479 |
+
rvalue-reference. If such a constructor is available, it will be used to
|
480 |
+
construct an alias instance from the value returned by the factory function.
|
481 |
+
The second option is to provide two factory functions to ``py::init()``: the
|
482 |
+
first will be invoked when no alias class is required (i.e. when the class is
|
483 |
+
being used but not inherited from in Python), and the second will be invoked
|
484 |
+
when an alias is required.
|
485 |
+
|
486 |
+
You can also specify a single factory function that always returns an alias
|
487 |
+
instance: this will result in behaviour similar to ``py::init_alias<...>()``,
|
488 |
+
as described in the :ref:`extended trampoline class documentation
|
489 |
+
<extended_aliases>`.
|
490 |
+
|
491 |
+
The following example shows the different factory approaches for a class with
|
492 |
+
an alias:
|
493 |
+
|
494 |
+
.. code-block:: cpp
|
495 |
+
|
496 |
+
#include <pybind11/factory.h>
|
497 |
+
class Example {
|
498 |
+
public:
|
499 |
+
// ...
|
500 |
+
virtual ~Example() = default;
|
501 |
+
};
|
502 |
+
class PyExample : public Example {
|
503 |
+
public:
|
504 |
+
using Example::Example;
|
505 |
+
PyExample(Example &&base) : Example(std::move(base)) {}
|
506 |
+
};
|
507 |
+
py::class_<Example, PyExample>(m, "Example")
|
508 |
+
// Returns an Example pointer. If a PyExample is needed, the Example
|
509 |
+
// instance will be moved via the extra constructor in PyExample, above.
|
510 |
+
.def(py::init([]() { return new Example(); }))
|
511 |
+
// Two callbacks:
|
512 |
+
.def(py::init([]() { return new Example(); } /* no alias needed */,
|
513 |
+
[]() { return new PyExample(); } /* alias needed */))
|
514 |
+
// *Always* returns an alias instance (like py::init_alias<>())
|
515 |
+
.def(py::init([]() { return new PyExample(); }))
|
516 |
+
;
|
517 |
+
|
518 |
+
Brace initialization
|
519 |
+
--------------------
|
520 |
+
|
521 |
+
``pybind11::init<>`` internally uses C++11 brace initialization to call the
|
522 |
+
constructor of the target class. This means that it can be used to bind
|
523 |
+
*implicit* constructors as well:
|
524 |
+
|
525 |
+
.. code-block:: cpp
|
526 |
+
|
527 |
+
struct Aggregate {
|
528 |
+
int a;
|
529 |
+
std::string b;
|
530 |
+
};
|
531 |
+
|
532 |
+
py::class_<Aggregate>(m, "Aggregate")
|
533 |
+
.def(py::init<int, const std::string &>());
|
534 |
+
|
535 |
+
.. note::
|
536 |
+
|
537 |
+
Note that brace initialization preferentially invokes constructor overloads
|
538 |
+
taking a ``std::initializer_list``. In the rare event that this causes an
|
539 |
+
issue, you can work around it by using ``py::init(...)`` with a lambda
|
540 |
+
function that constructs the new object as desired.
|
541 |
+
|
542 |
+
.. _classes_with_non_public_destructors:
|
543 |
+
|
544 |
+
Non-public destructors
|
545 |
+
======================
|
546 |
+
|
547 |
+
If a class has a private or protected destructor (as might e.g. be the case in
|
548 |
+
a singleton pattern), a compile error will occur when creating bindings via
|
549 |
+
pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
|
550 |
+
is responsible for managing the lifetime of instances will reference the
|
551 |
+
destructor even if no deallocations ever take place. In order to expose classes
|
552 |
+
with private or protected destructors, it is possible to override the holder
|
553 |
+
type via a holder type argument to ``class_``. Pybind11 provides a helper class
|
554 |
+
``py::nodelete`` that disables any destructor invocations. In this case, it is
|
555 |
+
crucial that instances are deallocated on the C++ side to avoid memory leaks.
|
556 |
+
|
557 |
+
.. code-block:: cpp
|
558 |
+
|
559 |
+
/* ... definition ... */
|
560 |
+
|
561 |
+
class MyClass {
|
562 |
+
private:
|
563 |
+
~MyClass() { }
|
564 |
+
};
|
565 |
+
|
566 |
+
/* ... binding code ... */
|
567 |
+
|
568 |
+
py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
|
569 |
+
.def(py::init<>())
|
570 |
+
|
571 |
+
.. _destructors_that_call_python:
|
572 |
+
|
573 |
+
Destructors that call Python
|
574 |
+
============================
|
575 |
+
|
576 |
+
If a Python function is invoked from a C++ destructor, an exception may be thrown
|
577 |
+
of type :class:`error_already_set`. If this error is thrown out of a class destructor,
|
578 |
+
``std::terminate()`` will be called, terminating the process. Class destructors
|
579 |
+
must catch all exceptions of type :class:`error_already_set` to discard the Python
|
580 |
+
exception using :func:`error_already_set::discard_as_unraisable`.
|
581 |
+
|
582 |
+
Every Python function should be treated as *possibly throwing*. When a Python generator
|
583 |
+
stops yielding items, Python will throw a ``StopIteration`` exception, which can pass
|
584 |
+
though C++ destructors if the generator's stack frame holds the last reference to C++
|
585 |
+
objects.
|
586 |
+
|
587 |
+
For more information, see :ref:`the documentation on exceptions <unraisable_exceptions>`.
|
588 |
+
|
589 |
+
.. code-block:: cpp
|
590 |
+
|
591 |
+
class MyClass {
|
592 |
+
public:
|
593 |
+
~MyClass() {
|
594 |
+
try {
|
595 |
+
py::print("Even printing is dangerous in a destructor");
|
596 |
+
py::exec("raise ValueError('This is an unraisable exception')");
|
597 |
+
} catch (py::error_already_set &e) {
|
598 |
+
// error_context should be information about where/why the occurred,
|
599 |
+
// e.g. use __func__ to get the name of the current function
|
600 |
+
e.discard_as_unraisable(__func__);
|
601 |
+
}
|
602 |
+
}
|
603 |
+
};
|
604 |
+
|
605 |
+
.. note::
|
606 |
+
|
607 |
+
pybind11 does not support C++ destructors marked ``noexcept(false)``.
|
608 |
+
|
609 |
+
.. versionadded:: 2.6
|
610 |
+
|
611 |
+
.. _implicit_conversions:
|
612 |
+
|
613 |
+
Implicit conversions
|
614 |
+
====================
|
615 |
+
|
616 |
+
Suppose that instances of two types ``A`` and ``B`` are used in a project, and
|
617 |
+
that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
|
618 |
+
could be a fixed and an arbitrary precision number type).
|
619 |
+
|
620 |
+
.. code-block:: cpp
|
621 |
+
|
622 |
+
py::class_<A>(m, "A")
|
623 |
+
/// ... members ...
|
624 |
+
|
625 |
+
py::class_<B>(m, "B")
|
626 |
+
.def(py::init<A>())
|
627 |
+
/// ... members ...
|
628 |
+
|
629 |
+
m.def("func",
|
630 |
+
[](const B &) { /* .... */ }
|
631 |
+
);
|
632 |
+
|
633 |
+
To invoke the function ``func`` using a variable ``a`` containing an ``A``
|
634 |
+
instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
|
635 |
+
will automatically apply an implicit type conversion, which makes it possible
|
636 |
+
to directly write ``func(a)``.
|
637 |
+
|
638 |
+
In this situation (i.e. where ``B`` has a constructor that converts from
|
639 |
+
``A``), the following statement enables similar implicit conversions on the
|
640 |
+
Python side:
|
641 |
+
|
642 |
+
.. code-block:: cpp
|
643 |
+
|
644 |
+
py::implicitly_convertible<A, B>();
|
645 |
+
|
646 |
+
.. note::
|
647 |
+
|
648 |
+
Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom
|
649 |
+
data type that is exposed to Python via pybind11.
|
650 |
+
|
651 |
+
To prevent runaway recursion, implicit conversions are non-reentrant: an
|
652 |
+
implicit conversion invoked as part of another implicit conversion of the
|
653 |
+
same type (i.e. from ``A`` to ``B``) will fail.
|
654 |
+
|
655 |
+
.. _static_properties:
|
656 |
+
|
657 |
+
Static properties
|
658 |
+
=================
|
659 |
+
|
660 |
+
The section on :ref:`properties` discussed the creation of instance properties
|
661 |
+
that are implemented in terms of C++ getters and setters.
|
662 |
+
|
663 |
+
Static properties can also be created in a similar way to expose getters and
|
664 |
+
setters of static class attributes. Note that the implicit ``self`` argument
|
665 |
+
also exists in this case and is used to pass the Python ``type`` subclass
|
666 |
+
instance. This parameter will often not be needed by the C++ side, and the
|
667 |
+
following example illustrates how to instantiate a lambda getter function
|
668 |
+
that ignores it:
|
669 |
+
|
670 |
+
.. code-block:: cpp
|
671 |
+
|
672 |
+
py::class_<Foo>(m, "Foo")
|
673 |
+
.def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
|
674 |
+
|
675 |
+
Operator overloading
|
676 |
+
====================
|
677 |
+
|
678 |
+
Suppose that we're given the following ``Vector2`` class with a vector addition
|
679 |
+
and scalar multiplication operation, all implemented using overloaded operators
|
680 |
+
in C++.
|
681 |
+
|
682 |
+
.. code-block:: cpp
|
683 |
+
|
684 |
+
class Vector2 {
|
685 |
+
public:
|
686 |
+
Vector2(float x, float y) : x(x), y(y) { }
|
687 |
+
|
688 |
+
Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
|
689 |
+
Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
|
690 |
+
Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
|
691 |
+
Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
|
692 |
+
|
693 |
+
friend Vector2 operator*(float f, const Vector2 &v) {
|
694 |
+
return Vector2(f * v.x, f * v.y);
|
695 |
+
}
|
696 |
+
|
697 |
+
std::string toString() const {
|
698 |
+
return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
|
699 |
+
}
|
700 |
+
private:
|
701 |
+
float x, y;
|
702 |
+
};
|
703 |
+
|
704 |
+
The following snippet shows how the above operators can be conveniently exposed
|
705 |
+
to Python.
|
706 |
+
|
707 |
+
.. code-block:: cpp
|
708 |
+
|
709 |
+
#include <pybind11/operators.h>
|
710 |
+
|
711 |
+
PYBIND11_MODULE(example, m) {
|
712 |
+
py::class_<Vector2>(m, "Vector2")
|
713 |
+
.def(py::init<float, float>())
|
714 |
+
.def(py::self + py::self)
|
715 |
+
.def(py::self += py::self)
|
716 |
+
.def(py::self *= float())
|
717 |
+
.def(float() * py::self)
|
718 |
+
.def(py::self * float())
|
719 |
+
.def(-py::self)
|
720 |
+
.def("__repr__", &Vector2::toString);
|
721 |
+
}
|
722 |
+
|
723 |
+
Note that a line like
|
724 |
+
|
725 |
+
.. code-block:: cpp
|
726 |
+
|
727 |
+
.def(py::self * float())
|
728 |
+
|
729 |
+
is really just short hand notation for
|
730 |
+
|
731 |
+
.. code-block:: cpp
|
732 |
+
|
733 |
+
.def("__mul__", [](const Vector2 &a, float b) {
|
734 |
+
return a * b;
|
735 |
+
}, py::is_operator())
|
736 |
+
|
737 |
+
This can be useful for exposing additional operators that don't exist on the
|
738 |
+
C++ side, or to perform other types of customization. The ``py::is_operator``
|
739 |
+
flag marker is needed to inform pybind11 that this is an operator, which
|
740 |
+
returns ``NotImplemented`` when invoked with incompatible arguments rather than
|
741 |
+
throwing a type error.
|
742 |
+
|
743 |
+
.. note::
|
744 |
+
|
745 |
+
To use the more convenient ``py::self`` notation, the additional
|
746 |
+
header file :file:`pybind11/operators.h` must be included.
|
747 |
+
|
748 |
+
.. seealso::
|
749 |
+
|
750 |
+
The file :file:`tests/test_operator_overloading.cpp` contains a
|
751 |
+
complete example that demonstrates how to work with overloaded operators in
|
752 |
+
more detail.
|
753 |
+
|
754 |
+
.. _pickling:
|
755 |
+
|
756 |
+
Pickling support
|
757 |
+
================
|
758 |
+
|
759 |
+
Python's ``pickle`` module provides a powerful facility to serialize and
|
760 |
+
de-serialize a Python object graph into a binary data stream. To pickle and
|
761 |
+
unpickle C++ classes using pybind11, a ``py::pickle()`` definition must be
|
762 |
+
provided. Suppose the class in question has the following signature:
|
763 |
+
|
764 |
+
.. code-block:: cpp
|
765 |
+
|
766 |
+
class Pickleable {
|
767 |
+
public:
|
768 |
+
Pickleable(const std::string &value) : m_value(value) { }
|
769 |
+
const std::string &value() const { return m_value; }
|
770 |
+
|
771 |
+
void setExtra(int extra) { m_extra = extra; }
|
772 |
+
int extra() const { return m_extra; }
|
773 |
+
private:
|
774 |
+
std::string m_value;
|
775 |
+
int m_extra = 0;
|
776 |
+
};
|
777 |
+
|
778 |
+
Pickling support in Python is enabled by defining the ``__setstate__`` and
|
779 |
+
``__getstate__`` methods [#f3]_. For pybind11 classes, use ``py::pickle()``
|
780 |
+
to bind these two functions:
|
781 |
+
|
782 |
+
.. code-block:: cpp
|
783 |
+
|
784 |
+
py::class_<Pickleable>(m, "Pickleable")
|
785 |
+
.def(py::init<std::string>())
|
786 |
+
.def("value", &Pickleable::value)
|
787 |
+
.def("extra", &Pickleable::extra)
|
788 |
+
.def("setExtra", &Pickleable::setExtra)
|
789 |
+
.def(py::pickle(
|
790 |
+
[](const Pickleable &p) { // __getstate__
|
791 |
+
/* Return a tuple that fully encodes the state of the object */
|
792 |
+
return py::make_tuple(p.value(), p.extra());
|
793 |
+
},
|
794 |
+
[](py::tuple t) { // __setstate__
|
795 |
+
if (t.size() != 2)
|
796 |
+
throw std::runtime_error("Invalid state!");
|
797 |
+
|
798 |
+
/* Create a new C++ instance */
|
799 |
+
Pickleable p(t[0].cast<std::string>());
|
800 |
+
|
801 |
+
/* Assign any additional state */
|
802 |
+
p.setExtra(t[1].cast<int>());
|
803 |
+
|
804 |
+
return p;
|
805 |
+
}
|
806 |
+
));
|
807 |
+
|
808 |
+
The ``__setstate__`` part of the ``py::pickle()`` definition follows the same
|
809 |
+
rules as the single-argument version of ``py::init()``. The return type can be
|
810 |
+
a value, pointer or holder type. See :ref:`custom_constructors` for details.
|
811 |
+
|
812 |
+
An instance can now be pickled as follows:
|
813 |
+
|
814 |
+
.. code-block:: python
|
815 |
+
|
816 |
+
import pickle
|
817 |
+
|
818 |
+
p = Pickleable("test_value")
|
819 |
+
p.setExtra(15)
|
820 |
+
data = pickle.dumps(p)
|
821 |
+
|
822 |
+
|
823 |
+
.. note::
|
824 |
+
If given, the second argument to ``dumps`` must be 2 or larger - 0 and 1 are
|
825 |
+
not supported. Newer versions are also fine; for instance, specify ``-1`` to
|
826 |
+
always use the latest available version. Beware: failure to follow these
|
827 |
+
instructions will cause important pybind11 memory allocation routines to be
|
828 |
+
skipped during unpickling, which will likely lead to memory corruption
|
829 |
+
and/or segmentation faults. Python defaults to version 3 (Python 3-3.7) and
|
830 |
+
version 4 for Python 3.8+.
|
831 |
+
|
832 |
+
.. seealso::
|
833 |
+
|
834 |
+
The file :file:`tests/test_pickling.cpp` contains a complete example
|
835 |
+
that demonstrates how to pickle and unpickle types using pybind11 in more
|
836 |
+
detail.
|
837 |
+
|
838 |
+
.. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
|
839 |
+
|
840 |
+
Deepcopy support
|
841 |
+
================
|
842 |
+
|
843 |
+
Python normally uses references in assignments. Sometimes a real copy is needed
|
844 |
+
to prevent changing all copies. The ``copy`` module [#f5]_ provides these
|
845 |
+
capabilities.
|
846 |
+
|
847 |
+
A class with pickle support is automatically also (deep)copy
|
848 |
+
compatible. However, performance can be improved by adding custom
|
849 |
+
``__copy__`` and ``__deepcopy__`` methods.
|
850 |
+
|
851 |
+
For simple classes (deep)copy can be enabled by using the copy constructor,
|
852 |
+
which should look as follows:
|
853 |
+
|
854 |
+
.. code-block:: cpp
|
855 |
+
|
856 |
+
py::class_<Copyable>(m, "Copyable")
|
857 |
+
.def("__copy__", [](const Copyable &self) {
|
858 |
+
return Copyable(self);
|
859 |
+
})
|
860 |
+
.def("__deepcopy__", [](const Copyable &self, py::dict) {
|
861 |
+
return Copyable(self);
|
862 |
+
}, "memo"_a);
|
863 |
+
|
864 |
+
.. note::
|
865 |
+
|
866 |
+
Dynamic attributes will not be copied in this example.
|
867 |
+
|
868 |
+
.. [#f5] https://docs.python.org/3/library/copy.html
|
869 |
+
|
870 |
+
Multiple Inheritance
|
871 |
+
====================
|
872 |
+
|
873 |
+
pybind11 can create bindings for types that derive from multiple base types
|
874 |
+
(aka. *multiple inheritance*). To do so, specify all bases in the template
|
875 |
+
arguments of the ``class_`` declaration:
|
876 |
+
|
877 |
+
.. code-block:: cpp
|
878 |
+
|
879 |
+
py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
|
880 |
+
...
|
881 |
+
|
882 |
+
The base types can be specified in arbitrary order, and they can even be
|
883 |
+
interspersed with alias types and holder types (discussed earlier in this
|
884 |
+
document)---pybind11 will automatically find out which is which. The only
|
885 |
+
requirement is that the first template argument is the type to be declared.
|
886 |
+
|
887 |
+
It is also permitted to inherit multiply from exported C++ classes in Python,
|
888 |
+
as well as inheriting from multiple Python and/or pybind11-exported classes.
|
889 |
+
|
890 |
+
There is one caveat regarding the implementation of this feature:
|
891 |
+
|
892 |
+
When only one base type is specified for a C++ type that actually has multiple
|
893 |
+
bases, pybind11 will assume that it does not participate in multiple
|
894 |
+
inheritance, which can lead to undefined behavior. In such cases, add the tag
|
895 |
+
``multiple_inheritance`` to the class constructor:
|
896 |
+
|
897 |
+
.. code-block:: cpp
|
898 |
+
|
899 |
+
py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
|
900 |
+
|
901 |
+
The tag is redundant and does not need to be specified when multiple base types
|
902 |
+
are listed.
|
903 |
+
|
904 |
+
.. _module_local:
|
905 |
+
|
906 |
+
Module-local class bindings
|
907 |
+
===========================
|
908 |
+
|
909 |
+
When creating a binding for a class, pybind11 by default makes that binding
|
910 |
+
"global" across modules. What this means is that a type defined in one module
|
911 |
+
can be returned from any module resulting in the same Python type. For
|
912 |
+
example, this allows the following:
|
913 |
+
|
914 |
+
.. code-block:: cpp
|
915 |
+
|
916 |
+
// In the module1.cpp binding code for module1:
|
917 |
+
py::class_<Pet>(m, "Pet")
|
918 |
+
.def(py::init<std::string>())
|
919 |
+
.def_readonly("name", &Pet::name);
|
920 |
+
|
921 |
+
.. code-block:: cpp
|
922 |
+
|
923 |
+
// In the module2.cpp binding code for module2:
|
924 |
+
m.def("create_pet", [](std::string name) { return new Pet(name); });
|
925 |
+
|
926 |
+
.. code-block:: pycon
|
927 |
+
|
928 |
+
>>> from module1 import Pet
|
929 |
+
>>> from module2 import create_pet
|
930 |
+
>>> pet1 = Pet("Kitty")
|
931 |
+
>>> pet2 = create_pet("Doggy")
|
932 |
+
>>> pet2.name()
|
933 |
+
'Doggy'
|
934 |
+
|
935 |
+
When writing binding code for a library, this is usually desirable: this
|
936 |
+
allows, for example, splitting up a complex library into multiple Python
|
937 |
+
modules.
|
938 |
+
|
939 |
+
In some cases, however, this can cause conflicts. For example, suppose two
|
940 |
+
unrelated modules make use of an external C++ library and each provide custom
|
941 |
+
bindings for one of that library's classes. This will result in an error when
|
942 |
+
a Python program attempts to import both modules (directly or indirectly)
|
943 |
+
because of conflicting definitions on the external type:
|
944 |
+
|
945 |
+
.. code-block:: cpp
|
946 |
+
|
947 |
+
// dogs.cpp
|
948 |
+
|
949 |
+
// Binding for external library class:
|
950 |
+
py::class<pets::Pet>(m, "Pet")
|
951 |
+
.def("name", &pets::Pet::name);
|
952 |
+
|
953 |
+
// Binding for local extension class:
|
954 |
+
py::class<Dog, pets::Pet>(m, "Dog")
|
955 |
+
.def(py::init<std::string>());
|
956 |
+
|
957 |
+
.. code-block:: cpp
|
958 |
+
|
959 |
+
// cats.cpp, in a completely separate project from the above dogs.cpp.
|
960 |
+
|
961 |
+
// Binding for external library class:
|
962 |
+
py::class<pets::Pet>(m, "Pet")
|
963 |
+
.def("get_name", &pets::Pet::name);
|
964 |
+
|
965 |
+
// Binding for local extending class:
|
966 |
+
py::class<Cat, pets::Pet>(m, "Cat")
|
967 |
+
.def(py::init<std::string>());
|
968 |
+
|
969 |
+
.. code-block:: pycon
|
970 |
+
|
971 |
+
>>> import cats
|
972 |
+
>>> import dogs
|
973 |
+
Traceback (most recent call last):
|
974 |
+
File "<stdin>", line 1, in <module>
|
975 |
+
ImportError: generic_type: type "Pet" is already registered!
|
976 |
+
|
977 |
+
To get around this, you can tell pybind11 to keep the external class binding
|
978 |
+
localized to the module by passing the ``py::module_local()`` attribute into
|
979 |
+
the ``py::class_`` constructor:
|
980 |
+
|
981 |
+
.. code-block:: cpp
|
982 |
+
|
983 |
+
// Pet binding in dogs.cpp:
|
984 |
+
py::class<pets::Pet>(m, "Pet", py::module_local())
|
985 |
+
.def("name", &pets::Pet::name);
|
986 |
+
|
987 |
+
.. code-block:: cpp
|
988 |
+
|
989 |
+
// Pet binding in cats.cpp:
|
990 |
+
py::class<pets::Pet>(m, "Pet", py::module_local())
|
991 |
+
.def("get_name", &pets::Pet::name);
|
992 |
+
|
993 |
+
This makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes,
|
994 |
+
avoiding the conflict and allowing both modules to be loaded. C++ code in the
|
995 |
+
``dogs`` module that casts or returns a ``Pet`` instance will result in a
|
996 |
+
``dogs.Pet`` Python instance, while C++ code in the ``cats`` module will result
|
997 |
+
in a ``cats.Pet`` Python instance.
|
998 |
+
|
999 |
+
This does come with two caveats, however: First, external modules cannot return
|
1000 |
+
or cast a ``Pet`` instance to Python (unless they also provide their own local
|
1001 |
+
bindings). Second, from the Python point of view they are two distinct classes.
|
1002 |
+
|
1003 |
+
Note that the locality only applies in the C++ -> Python direction. When
|
1004 |
+
passing such a ``py::module_local`` type into a C++ function, the module-local
|
1005 |
+
classes are still considered. This means that if the following function is
|
1006 |
+
added to any module (including but not limited to the ``cats`` and ``dogs``
|
1007 |
+
modules above) it will be callable with either a ``dogs.Pet`` or ``cats.Pet``
|
1008 |
+
argument:
|
1009 |
+
|
1010 |
+
.. code-block:: cpp
|
1011 |
+
|
1012 |
+
m.def("pet_name", [](const pets::Pet &pet) { return pet.name(); });
|
1013 |
+
|
1014 |
+
For example, suppose the above function is added to each of ``cats.cpp``,
|
1015 |
+
``dogs.cpp`` and ``frogs.cpp`` (where ``frogs.cpp`` is some other module that
|
1016 |
+
does *not* bind ``Pets`` at all).
|
1017 |
+
|
1018 |
+
.. code-block:: pycon
|
1019 |
+
|
1020 |
+
>>> import cats, dogs, frogs # No error because of the added py::module_local()
|
1021 |
+
>>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover")
|
1022 |
+
>>> (cats.pet_name(mycat), dogs.pet_name(mydog))
|
1023 |
+
('Fluffy', 'Rover')
|
1024 |
+
>>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat))
|
1025 |
+
('Rover', 'Fluffy', 'Fluffy')
|
1026 |
+
|
1027 |
+
It is possible to use ``py::module_local()`` registrations in one module even
|
1028 |
+
if another module registers the same type globally: within the module with the
|
1029 |
+
module-local definition, all C++ instances will be cast to the associated bound
|
1030 |
+
Python type. In other modules any such values are converted to the global
|
1031 |
+
Python type created elsewhere.
|
1032 |
+
|
1033 |
+
.. note::
|
1034 |
+
|
1035 |
+
STL bindings (as provided via the optional :file:`pybind11/stl_bind.h`
|
1036 |
+
header) apply ``py::module_local`` by default when the bound type might
|
1037 |
+
conflict with other modules; see :ref:`stl_bind` for details.
|
1038 |
+
|
1039 |
+
.. note::
|
1040 |
+
|
1041 |
+
The localization of the bound types is actually tied to the shared object
|
1042 |
+
or binary generated by the compiler/linker. For typical modules created
|
1043 |
+
with ``PYBIND11_MODULE()``, this distinction is not significant. It is
|
1044 |
+
possible, however, when :ref:`embedding` to embed multiple modules in the
|
1045 |
+
same binary (see :ref:`embedding_modules`). In such a case, the
|
1046 |
+
localization will apply across all embedded modules within the same binary.
|
1047 |
+
|
1048 |
+
.. seealso::
|
1049 |
+
|
1050 |
+
The file :file:`tests/test_local_bindings.cpp` contains additional examples
|
1051 |
+
that demonstrate how ``py::module_local()`` works.
|
1052 |
+
|
1053 |
+
Binding protected member functions
|
1054 |
+
==================================
|
1055 |
+
|
1056 |
+
It's normally not possible to expose ``protected`` member functions to Python:
|
1057 |
+
|
1058 |
+
.. code-block:: cpp
|
1059 |
+
|
1060 |
+
class A {
|
1061 |
+
protected:
|
1062 |
+
int foo() const { return 42; }
|
1063 |
+
};
|
1064 |
+
|
1065 |
+
py::class_<A>(m, "A")
|
1066 |
+
.def("foo", &A::foo); // error: 'foo' is a protected member of 'A'
|
1067 |
+
|
1068 |
+
On one hand, this is good because non-``public`` members aren't meant to be
|
1069 |
+
accessed from the outside. But we may want to make use of ``protected``
|
1070 |
+
functions in derived Python classes.
|
1071 |
+
|
1072 |
+
The following pattern makes this possible:
|
1073 |
+
|
1074 |
+
.. code-block:: cpp
|
1075 |
+
|
1076 |
+
class A {
|
1077 |
+
protected:
|
1078 |
+
int foo() const { return 42; }
|
1079 |
+
};
|
1080 |
+
|
1081 |
+
class Publicist : public A { // helper type for exposing protected functions
|
1082 |
+
public:
|
1083 |
+
using A::foo; // inherited with different access modifier
|
1084 |
+
};
|
1085 |
+
|
1086 |
+
py::class_<A>(m, "A") // bind the primary class
|
1087 |
+
.def("foo", &Publicist::foo); // expose protected methods via the publicist
|
1088 |
+
|
1089 |
+
This works because ``&Publicist::foo`` is exactly the same function as
|
1090 |
+
``&A::foo`` (same signature and address), just with a different access
|
1091 |
+
modifier. The only purpose of the ``Publicist`` helper class is to make
|
1092 |
+
the function name ``public``.
|
1093 |
+
|
1094 |
+
If the intent is to expose ``protected`` ``virtual`` functions which can be
|
1095 |
+
overridden in Python, the publicist pattern can be combined with the previously
|
1096 |
+
described trampoline:
|
1097 |
+
|
1098 |
+
.. code-block:: cpp
|
1099 |
+
|
1100 |
+
class A {
|
1101 |
+
public:
|
1102 |
+
virtual ~A() = default;
|
1103 |
+
|
1104 |
+
protected:
|
1105 |
+
virtual int foo() const { return 42; }
|
1106 |
+
};
|
1107 |
+
|
1108 |
+
class Trampoline : public A {
|
1109 |
+
public:
|
1110 |
+
int foo() const override { PYBIND11_OVERRIDE(int, A, foo, ); }
|
1111 |
+
};
|
1112 |
+
|
1113 |
+
class Publicist : public A {
|
1114 |
+
public:
|
1115 |
+
using A::foo;
|
1116 |
+
};
|
1117 |
+
|
1118 |
+
py::class_<A, Trampoline>(m, "A") // <-- `Trampoline` here
|
1119 |
+
.def("foo", &Publicist::foo); // <-- `Publicist` here, not `Trampoline`!
|
1120 |
+
|
1121 |
+
Binding final classes
|
1122 |
+
=====================
|
1123 |
+
|
1124 |
+
Some classes may not be appropriate to inherit from. In C++11, classes can
|
1125 |
+
use the ``final`` specifier to ensure that a class cannot be inherited from.
|
1126 |
+
The ``py::is_final`` attribute can be used to ensure that Python classes
|
1127 |
+
cannot inherit from a specified type. The underlying C++ type does not need
|
1128 |
+
to be declared final.
|
1129 |
+
|
1130 |
+
.. code-block:: cpp
|
1131 |
+
|
1132 |
+
class IsFinal final {};
|
1133 |
+
|
1134 |
+
py::class_<IsFinal>(m, "IsFinal", py::is_final());
|
1135 |
+
|
1136 |
+
When you try to inherit from such a class in Python, you will now get this
|
1137 |
+
error:
|
1138 |
+
|
1139 |
+
.. code-block:: pycon
|
1140 |
+
|
1141 |
+
>>> class PyFinalChild(IsFinal):
|
1142 |
+
... pass
|
1143 |
+
...
|
1144 |
+
TypeError: type 'IsFinal' is not an acceptable base type
|
1145 |
+
|
1146 |
+
.. note:: This attribute is currently ignored on PyPy
|
1147 |
+
|
1148 |
+
.. versionadded:: 2.6
|
1149 |
+
|
1150 |
+
Binding classes with template parameters
|
1151 |
+
========================================
|
1152 |
+
|
1153 |
+
pybind11 can also wrap classes that have template parameters. Consider these classes:
|
1154 |
+
|
1155 |
+
.. code-block:: cpp
|
1156 |
+
|
1157 |
+
struct Cat {};
|
1158 |
+
struct Dog {};
|
1159 |
+
|
1160 |
+
template <typename PetType>
|
1161 |
+
struct Cage {
|
1162 |
+
Cage(PetType& pet);
|
1163 |
+
PetType& get();
|
1164 |
+
};
|
1165 |
+
|
1166 |
+
C++ templates may only be instantiated at compile time, so pybind11 can only
|
1167 |
+
wrap instantiated templated classes. You cannot wrap a non-instantiated template:
|
1168 |
+
|
1169 |
+
.. code-block:: cpp
|
1170 |
+
|
1171 |
+
// BROKEN (this will not compile)
|
1172 |
+
py::class_<Cage>(m, "Cage");
|
1173 |
+
.def("get", &Cage::get);
|
1174 |
+
|
1175 |
+
You must explicitly specify each template/type combination that you want to
|
1176 |
+
wrap separately.
|
1177 |
+
|
1178 |
+
.. code-block:: cpp
|
1179 |
+
|
1180 |
+
// ok
|
1181 |
+
py::class_<Cage<Cat>>(m, "CatCage")
|
1182 |
+
.def("get", &Cage<Cat>::get);
|
1183 |
+
|
1184 |
+
// ok
|
1185 |
+
py::class_<Cage<Dog>>(m, "DogCage")
|
1186 |
+
.def("get", &Cage<Dog>::get);
|
1187 |
+
|
1188 |
+
If your class methods have template parameters you can wrap those as well,
|
1189 |
+
but once again each instantiation must be explicitly specified:
|
1190 |
+
|
1191 |
+
.. code-block:: cpp
|
1192 |
+
|
1193 |
+
typename <typename T>
|
1194 |
+
struct MyClass {
|
1195 |
+
template <typename V>
|
1196 |
+
T fn(V v);
|
1197 |
+
};
|
1198 |
+
|
1199 |
+
py::class<MyClass<int>>(m, "MyClassT")
|
1200 |
+
.def("fn", &MyClass<int>::fn<std::string>);
|
1201 |
+
|
1202 |
+
Custom automatic downcasters
|
1203 |
+
============================
|
1204 |
+
|
1205 |
+
As explained in :ref:`inheritance`, pybind11 comes with built-in
|
1206 |
+
understanding of the dynamic type of polymorphic objects in C++; that
|
1207 |
+
is, returning a Pet to Python produces a Python object that knows it's
|
1208 |
+
wrapping a Dog, if Pet has virtual methods and pybind11 knows about
|
1209 |
+
Dog and this Pet is in fact a Dog. Sometimes, you might want to
|
1210 |
+
provide this automatic downcasting behavior when creating bindings for
|
1211 |
+
a class hierarchy that does not use standard C++ polymorphism, such as
|
1212 |
+
LLVM [#f4]_. As long as there's some way to determine at runtime
|
1213 |
+
whether a downcast is safe, you can proceed by specializing the
|
1214 |
+
``pybind11::polymorphic_type_hook`` template:
|
1215 |
+
|
1216 |
+
.. code-block:: cpp
|
1217 |
+
|
1218 |
+
enum class PetKind { Cat, Dog, Zebra };
|
1219 |
+
struct Pet { // Not polymorphic: has no virtual methods
|
1220 |
+
const PetKind kind;
|
1221 |
+
int age = 0;
|
1222 |
+
protected:
|
1223 |
+
Pet(PetKind _kind) : kind(_kind) {}
|
1224 |
+
};
|
1225 |
+
struct Dog : Pet {
|
1226 |
+
Dog() : Pet(PetKind::Dog) {}
|
1227 |
+
std::string sound = "woof!";
|
1228 |
+
std::string bark() const { return sound; }
|
1229 |
+
};
|
1230 |
+
|
1231 |
+
namespace pybind11 {
|
1232 |
+
template<> struct polymorphic_type_hook<Pet> {
|
1233 |
+
static const void *get(const Pet *src, const std::type_info*& type) {
|
1234 |
+
// note that src may be nullptr
|
1235 |
+
if (src && src->kind == PetKind::Dog) {
|
1236 |
+
type = &typeid(Dog);
|
1237 |
+
return static_cast<const Dog*>(src);
|
1238 |
+
}
|
1239 |
+
return src;
|
1240 |
+
}
|
1241 |
+
};
|
1242 |
+
} // namespace pybind11
|
1243 |
+
|
1244 |
+
When pybind11 wants to convert a C++ pointer of type ``Base*`` to a
|
1245 |
+
Python object, it calls ``polymorphic_type_hook<Base>::get()`` to
|
1246 |
+
determine if a downcast is possible. The ``get()`` function should use
|
1247 |
+
whatever runtime information is available to determine if its ``src``
|
1248 |
+
parameter is in fact an instance of some class ``Derived`` that
|
1249 |
+
inherits from ``Base``. If it finds such a ``Derived``, it sets ``type
|
1250 |
+
= &typeid(Derived)`` and returns a pointer to the ``Derived`` object
|
1251 |
+
that contains ``src``. Otherwise, it just returns ``src``, leaving
|
1252 |
+
``type`` at its default value of nullptr. If you set ``type`` to a
|
1253 |
+
type that pybind11 doesn't know about, no downcasting will occur, and
|
1254 |
+
the original ``src`` pointer will be used with its static type
|
1255 |
+
``Base*``.
|
1256 |
+
|
1257 |
+
It is critical that the returned pointer and ``type`` argument of
|
1258 |
+
``get()`` agree with each other: if ``type`` is set to something
|
1259 |
+
non-null, the returned pointer must point to the start of an object
|
1260 |
+
whose type is ``type``. If the hierarchy being exposed uses only
|
1261 |
+
single inheritance, a simple ``return src;`` will achieve this just
|
1262 |
+
fine, but in the general case, you must cast ``src`` to the
|
1263 |
+
appropriate derived-class pointer (e.g. using
|
1264 |
+
``static_cast<Derived>(src)``) before allowing it to be returned as a
|
1265 |
+
``void*``.
|
1266 |
+
|
1267 |
+
.. [#f4] https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html
|
1268 |
+
|
1269 |
+
.. note::
|
1270 |
+
|
1271 |
+
pybind11's standard support for downcasting objects whose types
|
1272 |
+
have virtual methods is implemented using
|
1273 |
+
``polymorphic_type_hook`` too, using the standard C++ ability to
|
1274 |
+
determine the most-derived type of a polymorphic object using
|
1275 |
+
``typeid()`` and to cast a base pointer to that most-derived type
|
1276 |
+
(even if you don't know what it is) using ``dynamic_cast<void*>``.
|
1277 |
+
|
1278 |
+
.. seealso::
|
1279 |
+
|
1280 |
+
The file :file:`tests/test_tagbased_polymorphic.cpp` contains a
|
1281 |
+
more complete example, including a demonstration of how to provide
|
1282 |
+
automatic downcasting for an entire class hierarchy without
|
1283 |
+
writing one get() function for each class.
|
1284 |
+
|
1285 |
+
Accessing the type object
|
1286 |
+
=========================
|
1287 |
+
|
1288 |
+
You can get the type object from a C++ class that has already been registered using:
|
1289 |
+
|
1290 |
+
.. code-block:: cpp
|
1291 |
+
|
1292 |
+
py::type T_py = py::type::of<T>();
|
1293 |
+
|
1294 |
+
You can directly use ``py::type::of(ob)`` to get the type object from any python
|
1295 |
+
object, just like ``type(ob)`` in Python.
|
1296 |
+
|
1297 |
+
.. note::
|
1298 |
+
|
1299 |
+
Other types, like ``py::type::of<int>()``, do not work, see :ref:`type-conversions`.
|
1300 |
+
|
1301 |
+
.. versionadded:: 2.6
|
1302 |
+
|
1303 |
+
Custom type setup
|
1304 |
+
=================
|
1305 |
+
|
1306 |
+
For advanced use cases, such as enabling garbage collection support, you may
|
1307 |
+
wish to directly manipulate the ``PyHeapTypeObject`` corresponding to a
|
1308 |
+
``py::class_`` definition.
|
1309 |
+
|
1310 |
+
You can do that using ``py::custom_type_setup``:
|
1311 |
+
|
1312 |
+
.. code-block:: cpp
|
1313 |
+
|
1314 |
+
struct OwnsPythonObjects {
|
1315 |
+
py::object value = py::none();
|
1316 |
+
};
|
1317 |
+
py::class_<OwnsPythonObjects> cls(
|
1318 |
+
m, "OwnsPythonObjects", py::custom_type_setup([](PyHeapTypeObject *heap_type) {
|
1319 |
+
auto *type = &heap_type->ht_type;
|
1320 |
+
type->tp_flags |= Py_TPFLAGS_HAVE_GC;
|
1321 |
+
type->tp_traverse = [](PyObject *self_base, visitproc visit, void *arg) {
|
1322 |
+
auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
|
1323 |
+
Py_VISIT(self.value.ptr());
|
1324 |
+
return 0;
|
1325 |
+
};
|
1326 |
+
type->tp_clear = [](PyObject *self_base) {
|
1327 |
+
auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
|
1328 |
+
self.value = py::none();
|
1329 |
+
return 0;
|
1330 |
+
};
|
1331 |
+
}));
|
1332 |
+
cls.def(py::init<>());
|
1333 |
+
cls.def_readwrite("value", &OwnsPythonObjects::value);
|
1334 |
+
|
1335 |
+
.. versionadded:: 2.8
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/embedding.rst
ADDED
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.. _embedding:
|
2 |
+
|
3 |
+
Embedding the interpreter
|
4 |
+
#########################
|
5 |
+
|
6 |
+
While pybind11 is mainly focused on extending Python using C++, it's also
|
7 |
+
possible to do the reverse: embed the Python interpreter into a C++ program.
|
8 |
+
All of the other documentation pages still apply here, so refer to them for
|
9 |
+
general pybind11 usage. This section will cover a few extra things required
|
10 |
+
for embedding.
|
11 |
+
|
12 |
+
Getting started
|
13 |
+
===============
|
14 |
+
|
15 |
+
A basic executable with an embedded interpreter can be created with just a few
|
16 |
+
lines of CMake and the ``pybind11::embed`` target, as shown below. For more
|
17 |
+
information, see :doc:`/compiling`.
|
18 |
+
|
19 |
+
.. code-block:: cmake
|
20 |
+
|
21 |
+
cmake_minimum_required(VERSION 3.4)
|
22 |
+
project(example)
|
23 |
+
|
24 |
+
find_package(pybind11 REQUIRED) # or `add_subdirectory(pybind11)`
|
25 |
+
|
26 |
+
add_executable(example main.cpp)
|
27 |
+
target_link_libraries(example PRIVATE pybind11::embed)
|
28 |
+
|
29 |
+
The essential structure of the ``main.cpp`` file looks like this:
|
30 |
+
|
31 |
+
.. code-block:: cpp
|
32 |
+
|
33 |
+
#include <pybind11/embed.h> // everything needed for embedding
|
34 |
+
namespace py = pybind11;
|
35 |
+
|
36 |
+
int main() {
|
37 |
+
py::scoped_interpreter guard{}; // start the interpreter and keep it alive
|
38 |
+
|
39 |
+
py::print("Hello, World!"); // use the Python API
|
40 |
+
}
|
41 |
+
|
42 |
+
The interpreter must be initialized before using any Python API, which includes
|
43 |
+
all the functions and classes in pybind11. The RAII guard class ``scoped_interpreter``
|
44 |
+
takes care of the interpreter lifetime. After the guard is destroyed, the interpreter
|
45 |
+
shuts down and clears its memory. No Python functions can be called after this.
|
46 |
+
|
47 |
+
Executing Python code
|
48 |
+
=====================
|
49 |
+
|
50 |
+
There are a few different ways to run Python code. One option is to use ``eval``,
|
51 |
+
``exec`` or ``eval_file``, as explained in :ref:`eval`. Here is a quick example in
|
52 |
+
the context of an executable with an embedded interpreter:
|
53 |
+
|
54 |
+
.. code-block:: cpp
|
55 |
+
|
56 |
+
#include <pybind11/embed.h>
|
57 |
+
namespace py = pybind11;
|
58 |
+
|
59 |
+
int main() {
|
60 |
+
py::scoped_interpreter guard{};
|
61 |
+
|
62 |
+
py::exec(R"(
|
63 |
+
kwargs = dict(name="World", number=42)
|
64 |
+
message = "Hello, {name}! The answer is {number}".format(**kwargs)
|
65 |
+
print(message)
|
66 |
+
)");
|
67 |
+
}
|
68 |
+
|
69 |
+
Alternatively, similar results can be achieved using pybind11's API (see
|
70 |
+
:doc:`/advanced/pycpp/index` for more details).
|
71 |
+
|
72 |
+
.. code-block:: cpp
|
73 |
+
|
74 |
+
#include <pybind11/embed.h>
|
75 |
+
namespace py = pybind11;
|
76 |
+
using namespace py::literals;
|
77 |
+
|
78 |
+
int main() {
|
79 |
+
py::scoped_interpreter guard{};
|
80 |
+
|
81 |
+
auto kwargs = py::dict("name"_a="World", "number"_a=42);
|
82 |
+
auto message = "Hello, {name}! The answer is {number}"_s.format(**kwargs);
|
83 |
+
py::print(message);
|
84 |
+
}
|
85 |
+
|
86 |
+
The two approaches can also be combined:
|
87 |
+
|
88 |
+
.. code-block:: cpp
|
89 |
+
|
90 |
+
#include <pybind11/embed.h>
|
91 |
+
#include <iostream>
|
92 |
+
|
93 |
+
namespace py = pybind11;
|
94 |
+
using namespace py::literals;
|
95 |
+
|
96 |
+
int main() {
|
97 |
+
py::scoped_interpreter guard{};
|
98 |
+
|
99 |
+
auto locals = py::dict("name"_a="World", "number"_a=42);
|
100 |
+
py::exec(R"(
|
101 |
+
message = "Hello, {name}! The answer is {number}".format(**locals())
|
102 |
+
)", py::globals(), locals);
|
103 |
+
|
104 |
+
auto message = locals["message"].cast<std::string>();
|
105 |
+
std::cout << message;
|
106 |
+
}
|
107 |
+
|
108 |
+
Importing modules
|
109 |
+
=================
|
110 |
+
|
111 |
+
Python modules can be imported using ``module_::import()``:
|
112 |
+
|
113 |
+
.. code-block:: cpp
|
114 |
+
|
115 |
+
py::module_ sys = py::module_::import("sys");
|
116 |
+
py::print(sys.attr("path"));
|
117 |
+
|
118 |
+
For convenience, the current working directory is included in ``sys.path`` when
|
119 |
+
embedding the interpreter. This makes it easy to import local Python files:
|
120 |
+
|
121 |
+
.. code-block:: python
|
122 |
+
|
123 |
+
"""calc.py located in the working directory"""
|
124 |
+
|
125 |
+
|
126 |
+
def add(i, j):
|
127 |
+
return i + j
|
128 |
+
|
129 |
+
|
130 |
+
.. code-block:: cpp
|
131 |
+
|
132 |
+
py::module_ calc = py::module_::import("calc");
|
133 |
+
py::object result = calc.attr("add")(1, 2);
|
134 |
+
int n = result.cast<int>();
|
135 |
+
assert(n == 3);
|
136 |
+
|
137 |
+
Modules can be reloaded using ``module_::reload()`` if the source is modified e.g.
|
138 |
+
by an external process. This can be useful in scenarios where the application
|
139 |
+
imports a user defined data processing script which needs to be updated after
|
140 |
+
changes by the user. Note that this function does not reload modules recursively.
|
141 |
+
|
142 |
+
.. _embedding_modules:
|
143 |
+
|
144 |
+
Adding embedded modules
|
145 |
+
=======================
|
146 |
+
|
147 |
+
Embedded binary modules can be added using the ``PYBIND11_EMBEDDED_MODULE`` macro.
|
148 |
+
Note that the definition must be placed at global scope. They can be imported
|
149 |
+
like any other module.
|
150 |
+
|
151 |
+
.. code-block:: cpp
|
152 |
+
|
153 |
+
#include <pybind11/embed.h>
|
154 |
+
namespace py = pybind11;
|
155 |
+
|
156 |
+
PYBIND11_EMBEDDED_MODULE(fast_calc, m) {
|
157 |
+
// `m` is a `py::module_` which is used to bind functions and classes
|
158 |
+
m.def("add", [](int i, int j) {
|
159 |
+
return i + j;
|
160 |
+
});
|
161 |
+
}
|
162 |
+
|
163 |
+
int main() {
|
164 |
+
py::scoped_interpreter guard{};
|
165 |
+
|
166 |
+
auto fast_calc = py::module_::import("fast_calc");
|
167 |
+
auto result = fast_calc.attr("add")(1, 2).cast<int>();
|
168 |
+
assert(result == 3);
|
169 |
+
}
|
170 |
+
|
171 |
+
Unlike extension modules where only a single binary module can be created, on
|
172 |
+
the embedded side an unlimited number of modules can be added using multiple
|
173 |
+
``PYBIND11_EMBEDDED_MODULE`` definitions (as long as they have unique names).
|
174 |
+
|
175 |
+
These modules are added to Python's list of builtins, so they can also be
|
176 |
+
imported in pure Python files loaded by the interpreter. Everything interacts
|
177 |
+
naturally:
|
178 |
+
|
179 |
+
.. code-block:: python
|
180 |
+
|
181 |
+
"""py_module.py located in the working directory"""
|
182 |
+
import cpp_module
|
183 |
+
|
184 |
+
a = cpp_module.a
|
185 |
+
b = a + 1
|
186 |
+
|
187 |
+
|
188 |
+
.. code-block:: cpp
|
189 |
+
|
190 |
+
#include <pybind11/embed.h>
|
191 |
+
namespace py = pybind11;
|
192 |
+
|
193 |
+
PYBIND11_EMBEDDED_MODULE(cpp_module, m) {
|
194 |
+
m.attr("a") = 1;
|
195 |
+
}
|
196 |
+
|
197 |
+
int main() {
|
198 |
+
py::scoped_interpreter guard{};
|
199 |
+
|
200 |
+
auto py_module = py::module_::import("py_module");
|
201 |
+
|
202 |
+
auto locals = py::dict("fmt"_a="{} + {} = {}", **py_module.attr("__dict__"));
|
203 |
+
assert(locals["a"].cast<int>() == 1);
|
204 |
+
assert(locals["b"].cast<int>() == 2);
|
205 |
+
|
206 |
+
py::exec(R"(
|
207 |
+
c = a + b
|
208 |
+
message = fmt.format(a, b, c)
|
209 |
+
)", py::globals(), locals);
|
210 |
+
|
211 |
+
assert(locals["c"].cast<int>() == 3);
|
212 |
+
assert(locals["message"].cast<std::string>() == "1 + 2 = 3");
|
213 |
+
}
|
214 |
+
|
215 |
+
|
216 |
+
Interpreter lifetime
|
217 |
+
====================
|
218 |
+
|
219 |
+
The Python interpreter shuts down when ``scoped_interpreter`` is destroyed. After
|
220 |
+
this, creating a new instance will restart the interpreter. Alternatively, the
|
221 |
+
``initialize_interpreter`` / ``finalize_interpreter`` pair of functions can be used
|
222 |
+
to directly set the state at any time.
|
223 |
+
|
224 |
+
Modules created with pybind11 can be safely re-initialized after the interpreter
|
225 |
+
has been restarted. However, this may not apply to third-party extension modules.
|
226 |
+
The issue is that Python itself cannot completely unload extension modules and
|
227 |
+
there are several caveats with regard to interpreter restarting. In short, not
|
228 |
+
all memory may be freed, either due to Python reference cycles or user-created
|
229 |
+
global data. All the details can be found in the CPython documentation.
|
230 |
+
|
231 |
+
.. warning::
|
232 |
+
|
233 |
+
Creating two concurrent ``scoped_interpreter`` guards is a fatal error. So is
|
234 |
+
calling ``initialize_interpreter`` for a second time after the interpreter
|
235 |
+
has already been initialized.
|
236 |
+
|
237 |
+
Do not use the raw CPython API functions ``Py_Initialize`` and
|
238 |
+
``Py_Finalize`` as these do not properly handle the lifetime of
|
239 |
+
pybind11's internal data.
|
240 |
+
|
241 |
+
|
242 |
+
Sub-interpreter support
|
243 |
+
=======================
|
244 |
+
|
245 |
+
Creating multiple copies of ``scoped_interpreter`` is not possible because it
|
246 |
+
represents the main Python interpreter. Sub-interpreters are something different
|
247 |
+
and they do permit the existence of multiple interpreters. This is an advanced
|
248 |
+
feature of the CPython API and should be handled with care. pybind11 does not
|
249 |
+
currently offer a C++ interface for sub-interpreters, so refer to the CPython
|
250 |
+
documentation for all the details regarding this feature.
|
251 |
+
|
252 |
+
We'll just mention a couple of caveats the sub-interpreters support in pybind11:
|
253 |
+
|
254 |
+
1. Sub-interpreters will not receive independent copies of embedded modules.
|
255 |
+
Instead, these are shared and modifications in one interpreter may be
|
256 |
+
reflected in another.
|
257 |
+
|
258 |
+
2. Managing multiple threads, multiple interpreters and the GIL can be
|
259 |
+
challenging and there are several caveats here, even within the pure
|
260 |
+
CPython API (please refer to the Python docs for details). As for
|
261 |
+
pybind11, keep in mind that ``gil_scoped_release`` and ``gil_scoped_acquire``
|
262 |
+
do not take sub-interpreters into account.
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/exceptions.rst
ADDED
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Exceptions
|
2 |
+
##########
|
3 |
+
|
4 |
+
Built-in C++ to Python exception translation
|
5 |
+
============================================
|
6 |
+
|
7 |
+
When Python calls C++ code through pybind11, pybind11 provides a C++ exception handler
|
8 |
+
that will trap C++ exceptions, translate them to the corresponding Python exception,
|
9 |
+
and raise them so that Python code can handle them.
|
10 |
+
|
11 |
+
pybind11 defines translations for ``std::exception`` and its standard
|
12 |
+
subclasses, and several special exception classes that translate to specific
|
13 |
+
Python exceptions. Note that these are not actually Python exceptions, so they
|
14 |
+
cannot be examined using the Python C API. Instead, they are pure C++ objects
|
15 |
+
that pybind11 will translate the corresponding Python exception when they arrive
|
16 |
+
at its exception handler.
|
17 |
+
|
18 |
+
.. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
|
19 |
+
|
20 |
+
+--------------------------------------+--------------------------------------+
|
21 |
+
| Exception thrown by C++ | Translated to Python exception type |
|
22 |
+
+======================================+======================================+
|
23 |
+
| :class:`std::exception` | ``RuntimeError`` |
|
24 |
+
+--------------------------------------+--------------------------------------+
|
25 |
+
| :class:`std::bad_alloc` | ``MemoryError`` |
|
26 |
+
+--------------------------------------+--------------------------------------+
|
27 |
+
| :class:`std::domain_error` | ``ValueError`` |
|
28 |
+
+--------------------------------------+--------------------------------------+
|
29 |
+
| :class:`std::invalid_argument` | ``ValueError`` |
|
30 |
+
+--------------------------------------+--------------------------------------+
|
31 |
+
| :class:`std::length_error` | ``ValueError`` |
|
32 |
+
+--------------------------------------+--------------------------------------+
|
33 |
+
| :class:`std::out_of_range` | ``IndexError`` |
|
34 |
+
+--------------------------------------+--------------------------------------+
|
35 |
+
| :class:`std::range_error` | ``ValueError`` |
|
36 |
+
+--------------------------------------+--------------------------------------+
|
37 |
+
| :class:`std::overflow_error` | ``OverflowError`` |
|
38 |
+
+--------------------------------------+--------------------------------------+
|
39 |
+
| :class:`pybind11::stop_iteration` | ``StopIteration`` (used to implement |
|
40 |
+
| | custom iterators) |
|
41 |
+
+--------------------------------------+--------------------------------------+
|
42 |
+
| :class:`pybind11::index_error` | ``IndexError`` (used to indicate out |
|
43 |
+
| | of bounds access in ``__getitem__``, |
|
44 |
+
| | ``__setitem__``, etc.) |
|
45 |
+
+--------------------------------------+--------------------------------------+
|
46 |
+
| :class:`pybind11::key_error` | ``KeyError`` (used to indicate out |
|
47 |
+
| | of bounds access in ``__getitem__``, |
|
48 |
+
| | ``__setitem__`` in dict-like |
|
49 |
+
| | objects, etc.) |
|
50 |
+
+--------------------------------------+--------------------------------------+
|
51 |
+
| :class:`pybind11::value_error` | ``ValueError`` (used to indicate |
|
52 |
+
| | wrong value passed in |
|
53 |
+
| | ``container.remove(...)``) |
|
54 |
+
+--------------------------------------+--------------------------------------+
|
55 |
+
| :class:`pybind11::type_error` | ``TypeError`` |
|
56 |
+
+--------------------------------------+--------------------------------------+
|
57 |
+
| :class:`pybind11::buffer_error` | ``BufferError`` |
|
58 |
+
+--------------------------------------+--------------------------------------+
|
59 |
+
| :class:`pybind11::import_error` | ``ImportError`` |
|
60 |
+
+--------------------------------------+--------------------------------------+
|
61 |
+
| :class:`pybind11::attribute_error` | ``AttributeError`` |
|
62 |
+
+--------------------------------------+--------------------------------------+
|
63 |
+
| Any other exception | ``RuntimeError`` |
|
64 |
+
+--------------------------------------+--------------------------------------+
|
65 |
+
|
66 |
+
Exception translation is not bidirectional. That is, *catching* the C++
|
67 |
+
exceptions defined above will not trap exceptions that originate from
|
68 |
+
Python. For that, catch :class:`pybind11::error_already_set`. See :ref:`below
|
69 |
+
<handling_python_exceptions_cpp>` for further details.
|
70 |
+
|
71 |
+
There is also a special exception :class:`cast_error` that is thrown by
|
72 |
+
:func:`handle::call` when the input arguments cannot be converted to Python
|
73 |
+
objects.
|
74 |
+
|
75 |
+
Registering custom translators
|
76 |
+
==============================
|
77 |
+
|
78 |
+
If the default exception conversion policy described above is insufficient,
|
79 |
+
pybind11 also provides support for registering custom exception translators.
|
80 |
+
Similar to pybind11 classes, exception translators can be local to the module
|
81 |
+
they are defined in or global to the entire python session. To register a simple
|
82 |
+
exception conversion that translates a C++ exception into a new Python exception
|
83 |
+
using the C++ exception's ``what()`` method, a helper function is available:
|
84 |
+
|
85 |
+
.. code-block:: cpp
|
86 |
+
|
87 |
+
py::register_exception<CppExp>(module, "PyExp");
|
88 |
+
|
89 |
+
This call creates a Python exception class with the name ``PyExp`` in the given
|
90 |
+
module and automatically converts any encountered exceptions of type ``CppExp``
|
91 |
+
into Python exceptions of type ``PyExp``.
|
92 |
+
|
93 |
+
A matching function is available for registering a local exception translator:
|
94 |
+
|
95 |
+
.. code-block:: cpp
|
96 |
+
|
97 |
+
py::register_local_exception<CppExp>(module, "PyExp");
|
98 |
+
|
99 |
+
|
100 |
+
It is possible to specify base class for the exception using the third
|
101 |
+
parameter, a ``handle``:
|
102 |
+
|
103 |
+
.. code-block:: cpp
|
104 |
+
|
105 |
+
py::register_exception<CppExp>(module, "PyExp", PyExc_RuntimeError);
|
106 |
+
py::register_local_exception<CppExp>(module, "PyExp", PyExc_RuntimeError);
|
107 |
+
|
108 |
+
Then ``PyExp`` can be caught both as ``PyExp`` and ``RuntimeError``.
|
109 |
+
|
110 |
+
The class objects of the built-in Python exceptions are listed in the Python
|
111 |
+
documentation on `Standard Exceptions <https://docs.python.org/3/c-api/exceptions.html#standard-exceptions>`_.
|
112 |
+
The default base class is ``PyExc_Exception``.
|
113 |
+
|
114 |
+
When more advanced exception translation is needed, the functions
|
115 |
+
``py::register_exception_translator(translator)`` and
|
116 |
+
``py::register_local_exception_translator(translator)`` can be used to register
|
117 |
+
functions that can translate arbitrary exception types (and which may include
|
118 |
+
additional logic to do so). The functions takes a stateless callable (e.g. a
|
119 |
+
function pointer or a lambda function without captured variables) with the call
|
120 |
+
signature ``void(std::exception_ptr)``.
|
121 |
+
|
122 |
+
When a C++ exception is thrown, the registered exception translators are tried
|
123 |
+
in reverse order of registration (i.e. the last registered translator gets the
|
124 |
+
first shot at handling the exception). All local translators will be tried
|
125 |
+
before a global translator is tried.
|
126 |
+
|
127 |
+
Inside the translator, ``std::rethrow_exception`` should be used within
|
128 |
+
a try block to re-throw the exception. One or more catch clauses to catch
|
129 |
+
the appropriate exceptions should then be used with each clause using
|
130 |
+
``PyErr_SetString`` to set a Python exception or ``ex(string)`` to set
|
131 |
+
the python exception to a custom exception type (see below).
|
132 |
+
|
133 |
+
To declare a custom Python exception type, declare a ``py::exception`` variable
|
134 |
+
and use this in the associated exception translator (note: it is often useful
|
135 |
+
to make this a static declaration when using it inside a lambda expression
|
136 |
+
without requiring capturing).
|
137 |
+
|
138 |
+
The following example demonstrates this for a hypothetical exception classes
|
139 |
+
``MyCustomException`` and ``OtherException``: the first is translated to a
|
140 |
+
custom python exception ``MyCustomError``, while the second is translated to a
|
141 |
+
standard python RuntimeError:
|
142 |
+
|
143 |
+
.. code-block:: cpp
|
144 |
+
|
145 |
+
static py::exception<MyCustomException> exc(m, "MyCustomError");
|
146 |
+
py::register_exception_translator([](std::exception_ptr p) {
|
147 |
+
try {
|
148 |
+
if (p) std::rethrow_exception(p);
|
149 |
+
} catch (const MyCustomException &e) {
|
150 |
+
exc(e.what());
|
151 |
+
} catch (const OtherException &e) {
|
152 |
+
PyErr_SetString(PyExc_RuntimeError, e.what());
|
153 |
+
}
|
154 |
+
});
|
155 |
+
|
156 |
+
Multiple exceptions can be handled by a single translator, as shown in the
|
157 |
+
example above. If the exception is not caught by the current translator, the
|
158 |
+
previously registered one gets a chance.
|
159 |
+
|
160 |
+
If none of the registered exception translators is able to handle the
|
161 |
+
exception, it is handled by the default converter as described in the previous
|
162 |
+
section.
|
163 |
+
|
164 |
+
.. seealso::
|
165 |
+
|
166 |
+
The file :file:`tests/test_exceptions.cpp` contains examples
|
167 |
+
of various custom exception translators and custom exception types.
|
168 |
+
|
169 |
+
.. note::
|
170 |
+
|
171 |
+
Call either ``PyErr_SetString`` or a custom exception's call
|
172 |
+
operator (``exc(string)``) for every exception caught in a custom exception
|
173 |
+
translator. Failure to do so will cause Python to crash with ``SystemError:
|
174 |
+
error return without exception set``.
|
175 |
+
|
176 |
+
Exceptions that you do not plan to handle should simply not be caught, or
|
177 |
+
may be explicitly (re-)thrown to delegate it to the other,
|
178 |
+
previously-declared existing exception translators.
|
179 |
+
|
180 |
+
Note that ``libc++`` and ``libstdc++`` `behave differently <https://stackoverflow.com/questions/19496643/using-clang-fvisibility-hidden-and-typeinfo-and-type-erasure/28827430>`_
|
181 |
+
with ``-fvisibility=hidden``. Therefore exceptions that are used across ABI boundaries need to be explicitly exported, as exercised in ``tests/test_exceptions.h``.
|
182 |
+
See also: "Problems with C++ exceptions" under `GCC Wiki <https://gcc.gnu.org/wiki/Visibility>`_.
|
183 |
+
|
184 |
+
|
185 |
+
Local vs Global Exception Translators
|
186 |
+
=====================================
|
187 |
+
|
188 |
+
When a global exception translator is registered, it will be applied across all
|
189 |
+
modules in the reverse order of registration. This can create behavior where the
|
190 |
+
order of module import influences how exceptions are translated.
|
191 |
+
|
192 |
+
If module1 has the following translator:
|
193 |
+
|
194 |
+
.. code-block:: cpp
|
195 |
+
|
196 |
+
py::register_exception_translator([](std::exception_ptr p) {
|
197 |
+
try {
|
198 |
+
if (p) std::rethrow_exception(p);
|
199 |
+
} catch (const std::invalid_argument &e) {
|
200 |
+
PyErr_SetString("module1 handled this")
|
201 |
+
}
|
202 |
+
}
|
203 |
+
|
204 |
+
and module2 has the following similar translator:
|
205 |
+
|
206 |
+
.. code-block:: cpp
|
207 |
+
|
208 |
+
py::register_exception_translator([](std::exception_ptr p) {
|
209 |
+
try {
|
210 |
+
if (p) std::rethrow_exception(p);
|
211 |
+
} catch (const std::invalid_argument &e) {
|
212 |
+
PyErr_SetString("module2 handled this")
|
213 |
+
}
|
214 |
+
}
|
215 |
+
|
216 |
+
then which translator handles the invalid_argument will be determined by the
|
217 |
+
order that module1 and module2 are imported. Since exception translators are
|
218 |
+
applied in the reverse order of registration, which ever module was imported
|
219 |
+
last will "win" and that translator will be applied.
|
220 |
+
|
221 |
+
If there are multiple pybind11 modules that share exception types (either
|
222 |
+
standard built-in or custom) loaded into a single python instance and
|
223 |
+
consistent error handling behavior is needed, then local translators should be
|
224 |
+
used.
|
225 |
+
|
226 |
+
Changing the previous example to use ``register_local_exception_translator``
|
227 |
+
would mean that when invalid_argument is thrown in the module2 code, the
|
228 |
+
module2 translator will always handle it, while in module1, the module1
|
229 |
+
translator will do the same.
|
230 |
+
|
231 |
+
.. _handling_python_exceptions_cpp:
|
232 |
+
|
233 |
+
Handling exceptions from Python in C++
|
234 |
+
======================================
|
235 |
+
|
236 |
+
When C++ calls Python functions, such as in a callback function or when
|
237 |
+
manipulating Python objects, and Python raises an ``Exception``, pybind11
|
238 |
+
converts the Python exception into a C++ exception of type
|
239 |
+
:class:`pybind11::error_already_set` whose payload contains a C++ string textual
|
240 |
+
summary and the actual Python exception. ``error_already_set`` is used to
|
241 |
+
propagate Python exception back to Python (or possibly, handle them in C++).
|
242 |
+
|
243 |
+
.. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
|
244 |
+
|
245 |
+
+--------------------------------------+--------------------------------------+
|
246 |
+
| Exception raised in Python | Thrown as C++ exception type |
|
247 |
+
+======================================+======================================+
|
248 |
+
| Any Python ``Exception`` | :class:`pybind11::error_already_set` |
|
249 |
+
+--------------------------------------+--------------------------------------+
|
250 |
+
|
251 |
+
For example:
|
252 |
+
|
253 |
+
.. code-block:: cpp
|
254 |
+
|
255 |
+
try {
|
256 |
+
// open("missing.txt", "r")
|
257 |
+
auto file = py::module_::import("io").attr("open")("missing.txt", "r");
|
258 |
+
auto text = file.attr("read")();
|
259 |
+
file.attr("close")();
|
260 |
+
} catch (py::error_already_set &e) {
|
261 |
+
if (e.matches(PyExc_FileNotFoundError)) {
|
262 |
+
py::print("missing.txt not found");
|
263 |
+
} else if (e.matches(PyExc_PermissionError)) {
|
264 |
+
py::print("missing.txt found but not accessible");
|
265 |
+
} else {
|
266 |
+
throw;
|
267 |
+
}
|
268 |
+
}
|
269 |
+
|
270 |
+
Note that C++ to Python exception translation does not apply here, since that is
|
271 |
+
a method for translating C++ exceptions to Python, not vice versa. The error raised
|
272 |
+
from Python is always ``error_already_set``.
|
273 |
+
|
274 |
+
This example illustrates this behavior:
|
275 |
+
|
276 |
+
.. code-block:: cpp
|
277 |
+
|
278 |
+
try {
|
279 |
+
py::eval("raise ValueError('The Ring')");
|
280 |
+
} catch (py::value_error &boromir) {
|
281 |
+
// Boromir never gets the ring
|
282 |
+
assert(false);
|
283 |
+
} catch (py::error_already_set &frodo) {
|
284 |
+
// Frodo gets the ring
|
285 |
+
py::print("I will take the ring");
|
286 |
+
}
|
287 |
+
|
288 |
+
try {
|
289 |
+
// py::value_error is a request for pybind11 to raise a Python exception
|
290 |
+
throw py::value_error("The ball");
|
291 |
+
} catch (py::error_already_set &cat) {
|
292 |
+
// cat won't catch the ball since
|
293 |
+
// py::value_error is not a Python exception
|
294 |
+
assert(false);
|
295 |
+
} catch (py::value_error &dog) {
|
296 |
+
// dog will catch the ball
|
297 |
+
py::print("Run Spot run");
|
298 |
+
throw; // Throw it again (pybind11 will raise ValueError)
|
299 |
+
}
|
300 |
+
|
301 |
+
Handling errors from the Python C API
|
302 |
+
=====================================
|
303 |
+
|
304 |
+
Where possible, use :ref:`pybind11 wrappers <wrappers>` instead of calling
|
305 |
+
the Python C API directly. When calling the Python C API directly, in
|
306 |
+
addition to manually managing reference counts, one must follow the pybind11
|
307 |
+
error protocol, which is outlined here.
|
308 |
+
|
309 |
+
After calling the Python C API, if Python returns an error,
|
310 |
+
``throw py::error_already_set();``, which allows pybind11 to deal with the
|
311 |
+
exception and pass it back to the Python interpreter. This includes calls to
|
312 |
+
the error setting functions such as ``PyErr_SetString``.
|
313 |
+
|
314 |
+
.. code-block:: cpp
|
315 |
+
|
316 |
+
PyErr_SetString(PyExc_TypeError, "C API type error demo");
|
317 |
+
throw py::error_already_set();
|
318 |
+
|
319 |
+
// But it would be easier to simply...
|
320 |
+
throw py::type_error("pybind11 wrapper type error");
|
321 |
+
|
322 |
+
Alternately, to ignore the error, call `PyErr_Clear
|
323 |
+
<https://docs.python.org/3/c-api/exceptions.html#c.PyErr_Clear>`_.
|
324 |
+
|
325 |
+
Any Python error must be thrown or cleared, or Python/pybind11 will be left in
|
326 |
+
an invalid state.
|
327 |
+
|
328 |
+
Chaining exceptions ('raise from')
|
329 |
+
==================================
|
330 |
+
|
331 |
+
Python has a mechanism for indicating that exceptions were caused by other
|
332 |
+
exceptions:
|
333 |
+
|
334 |
+
.. code-block:: py
|
335 |
+
|
336 |
+
try:
|
337 |
+
print(1 / 0)
|
338 |
+
except Exception as exc:
|
339 |
+
raise RuntimeError("could not divide by zero") from exc
|
340 |
+
|
341 |
+
To do a similar thing in pybind11, you can use the ``py::raise_from`` function. It
|
342 |
+
sets the current python error indicator, so to continue propagating the exception
|
343 |
+
you should ``throw py::error_already_set()``.
|
344 |
+
|
345 |
+
.. code-block:: cpp
|
346 |
+
|
347 |
+
try {
|
348 |
+
py::eval("print(1 / 0"));
|
349 |
+
} catch (py::error_already_set &e) {
|
350 |
+
py::raise_from(e, PyExc_RuntimeError, "could not divide by zero");
|
351 |
+
throw py::error_already_set();
|
352 |
+
}
|
353 |
+
|
354 |
+
.. versionadded:: 2.8
|
355 |
+
|
356 |
+
.. _unraisable_exceptions:
|
357 |
+
|
358 |
+
Handling unraisable exceptions
|
359 |
+
==============================
|
360 |
+
|
361 |
+
If a Python function invoked from a C++ destructor or any function marked
|
362 |
+
``noexcept(true)`` (collectively, "noexcept functions") throws an exception, there
|
363 |
+
is no way to propagate the exception, as such functions may not throw.
|
364 |
+
Should they throw or fail to catch any exceptions in their call graph,
|
365 |
+
the C++ runtime calls ``std::terminate()`` to abort immediately.
|
366 |
+
|
367 |
+
Similarly, Python exceptions raised in a class's ``__del__`` method do not
|
368 |
+
propagate, but are logged by Python as an unraisable error. In Python 3.8+, a
|
369 |
+
`system hook is triggered
|
370 |
+
<https://docs.python.org/3/library/sys.html#sys.unraisablehook>`_
|
371 |
+
and an auditing event is logged.
|
372 |
+
|
373 |
+
Any noexcept function should have a try-catch block that traps
|
374 |
+
class:`error_already_set` (or any other exception that can occur). Note that
|
375 |
+
pybind11 wrappers around Python exceptions such as
|
376 |
+
:class:`pybind11::value_error` are *not* Python exceptions; they are C++
|
377 |
+
exceptions that pybind11 catches and converts to Python exceptions. Noexcept
|
378 |
+
functions cannot propagate these exceptions either. A useful approach is to
|
379 |
+
convert them to Python exceptions and then ``discard_as_unraisable`` as shown
|
380 |
+
below.
|
381 |
+
|
382 |
+
.. code-block:: cpp
|
383 |
+
|
384 |
+
void nonthrowing_func() noexcept(true) {
|
385 |
+
try {
|
386 |
+
// ...
|
387 |
+
} catch (py::error_already_set &eas) {
|
388 |
+
// Discard the Python error using Python APIs, using the C++ magic
|
389 |
+
// variable __func__. Python already knows the type and value and of the
|
390 |
+
// exception object.
|
391 |
+
eas.discard_as_unraisable(__func__);
|
392 |
+
} catch (const std::exception &e) {
|
393 |
+
// Log and discard C++ exceptions.
|
394 |
+
third_party::log(e);
|
395 |
+
}
|
396 |
+
}
|
397 |
+
|
398 |
+
.. versionadded:: 2.6
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/functions.rst
ADDED
@@ -0,0 +1,614 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Functions
|
2 |
+
#########
|
3 |
+
|
4 |
+
Before proceeding with this section, make sure that you are already familiar
|
5 |
+
with the basics of binding functions and classes, as explained in :doc:`/basics`
|
6 |
+
and :doc:`/classes`. The following guide is applicable to both free and member
|
7 |
+
functions, i.e. *methods* in Python.
|
8 |
+
|
9 |
+
.. _return_value_policies:
|
10 |
+
|
11 |
+
Return value policies
|
12 |
+
=====================
|
13 |
+
|
14 |
+
Python and C++ use fundamentally different ways of managing the memory and
|
15 |
+
lifetime of objects managed by them. This can lead to issues when creating
|
16 |
+
bindings for functions that return a non-trivial type. Just by looking at the
|
17 |
+
type information, it is not clear whether Python should take charge of the
|
18 |
+
returned value and eventually free its resources, or if this is handled on the
|
19 |
+
C++ side. For this reason, pybind11 provides a several *return value policy*
|
20 |
+
annotations that can be passed to the :func:`module_::def` and
|
21 |
+
:func:`class_::def` functions. The default policy is
|
22 |
+
:enum:`return_value_policy::automatic`.
|
23 |
+
|
24 |
+
Return value policies are tricky, and it's very important to get them right.
|
25 |
+
Just to illustrate what can go wrong, consider the following simple example:
|
26 |
+
|
27 |
+
.. code-block:: cpp
|
28 |
+
|
29 |
+
/* Function declaration */
|
30 |
+
Data *get_data() { return _data; /* (pointer to a static data structure) */ }
|
31 |
+
...
|
32 |
+
|
33 |
+
/* Binding code */
|
34 |
+
m.def("get_data", &get_data); // <-- KABOOM, will cause crash when called from Python
|
35 |
+
|
36 |
+
What's going on here? When ``get_data()`` is called from Python, the return
|
37 |
+
value (a native C++ type) must be wrapped to turn it into a usable Python type.
|
38 |
+
In this case, the default return value policy (:enum:`return_value_policy::automatic`)
|
39 |
+
causes pybind11 to assume ownership of the static ``_data`` instance.
|
40 |
+
|
41 |
+
When Python's garbage collector eventually deletes the Python
|
42 |
+
wrapper, pybind11 will also attempt to delete the C++ instance (via ``operator
|
43 |
+
delete()``) due to the implied ownership. At this point, the entire application
|
44 |
+
will come crashing down, though errors could also be more subtle and involve
|
45 |
+
silent data corruption.
|
46 |
+
|
47 |
+
In the above example, the policy :enum:`return_value_policy::reference` should have
|
48 |
+
been specified so that the global data instance is only *referenced* without any
|
49 |
+
implied transfer of ownership, i.e.:
|
50 |
+
|
51 |
+
.. code-block:: cpp
|
52 |
+
|
53 |
+
m.def("get_data", &get_data, py::return_value_policy::reference);
|
54 |
+
|
55 |
+
On the other hand, this is not the right policy for many other situations,
|
56 |
+
where ignoring ownership could lead to resource leaks.
|
57 |
+
As a developer using pybind11, it's important to be familiar with the different
|
58 |
+
return value policies, including which situation calls for which one of them.
|
59 |
+
The following table provides an overview of available policies:
|
60 |
+
|
61 |
+
.. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
|
62 |
+
|
63 |
+
+--------------------------------------------------+----------------------------------------------------------------------------+
|
64 |
+
| Return value policy | Description |
|
65 |
+
+==================================================+============================================================================+
|
66 |
+
| :enum:`return_value_policy::take_ownership` | Reference an existing object (i.e. do not create a new copy) and take |
|
67 |
+
| | ownership. Python will call the destructor and delete operator when the |
|
68 |
+
| | object's reference count reaches zero. Undefined behavior ensues when the |
|
69 |
+
| | C++ side does the same, or when the data was not dynamically allocated. |
|
70 |
+
+--------------------------------------------------+----------------------------------------------------------------------------+
|
71 |
+
| :enum:`return_value_policy::copy` | Create a new copy of the returned object, which will be owned by Python. |
|
72 |
+
| | This policy is comparably safe because the lifetimes of the two instances |
|
73 |
+
| | are decoupled. |
|
74 |
+
+--------------------------------------------------+----------------------------------------------------------------------------+
|
75 |
+
| :enum:`return_value_policy::move` | Use ``std::move`` to move the return value contents into a new instance |
|
76 |
+
| | that will be owned by Python. This policy is comparably safe because the |
|
77 |
+
| | lifetimes of the two instances (move source and destination) are decoupled.|
|
78 |
+
+--------------------------------------------------+----------------------------------------------------------------------------+
|
79 |
+
| :enum:`return_value_policy::reference` | Reference an existing object, but do not take ownership. The C++ side is |
|
80 |
+
| | responsible for managing the object's lifetime and deallocating it when |
|
81 |
+
| | it is no longer used. Warning: undefined behavior will ensue when the C++ |
|
82 |
+
| | side deletes an object that is still referenced and used by Python. |
|
83 |
+
+--------------------------------------------------+----------------------------------------------------------------------------+
|
84 |
+
| :enum:`return_value_policy::reference_internal` | Indicates that the lifetime of the return value is tied to the lifetime |
|
85 |
+
| | of a parent object, namely the implicit ``this``, or ``self`` argument of |
|
86 |
+
| | the called method or property. Internally, this policy works just like |
|
87 |
+
| | :enum:`return_value_policy::reference` but additionally applies a |
|
88 |
+
| | ``keep_alive<0, 1>`` *call policy* (described in the next section) that |
|
89 |
+
| | prevents the parent object from being garbage collected as long as the |
|
90 |
+
| | return value is referenced by Python. This is the default policy for |
|
91 |
+
| | property getters created via ``def_property``, ``def_readwrite``, etc. |
|
92 |
+
+--------------------------------------------------+----------------------------------------------------------------------------+
|
93 |
+
| :enum:`return_value_policy::automatic` | This policy falls back to the policy |
|
94 |
+
| | :enum:`return_value_policy::take_ownership` when the return value is a |
|
95 |
+
| | pointer. Otherwise, it uses :enum:`return_value_policy::move` or |
|
96 |
+
| | :enum:`return_value_policy::copy` for rvalue and lvalue references, |
|
97 |
+
| | respectively. See above for a description of what all of these different |
|
98 |
+
| | policies do. This is the default policy for ``py::class_``-wrapped types. |
|
99 |
+
+--------------------------------------------------+----------------------------------------------------------------------------+
|
100 |
+
| :enum:`return_value_policy::automatic_reference` | As above, but use policy :enum:`return_value_policy::reference` when the |
|
101 |
+
| | return value is a pointer. This is the default conversion policy for |
|
102 |
+
| | function arguments when calling Python functions manually from C++ code |
|
103 |
+
| | (i.e. via ``handle::operator()``) and the casters in ``pybind11/stl.h``. |
|
104 |
+
| | You probably won't need to use this explicitly. |
|
105 |
+
+--------------------------------------------------+----------------------------------------------------------------------------+
|
106 |
+
|
107 |
+
Return value policies can also be applied to properties:
|
108 |
+
|
109 |
+
.. code-block:: cpp
|
110 |
+
|
111 |
+
class_<MyClass>(m, "MyClass")
|
112 |
+
.def_property("data", &MyClass::getData, &MyClass::setData,
|
113 |
+
py::return_value_policy::copy);
|
114 |
+
|
115 |
+
Technically, the code above applies the policy to both the getter and the
|
116 |
+
setter function, however, the setter doesn't really care about *return*
|
117 |
+
value policies which makes this a convenient terse syntax. Alternatively,
|
118 |
+
targeted arguments can be passed through the :class:`cpp_function` constructor:
|
119 |
+
|
120 |
+
.. code-block:: cpp
|
121 |
+
|
122 |
+
class_<MyClass>(m, "MyClass")
|
123 |
+
.def_property("data",
|
124 |
+
py::cpp_function(&MyClass::getData, py::return_value_policy::copy),
|
125 |
+
py::cpp_function(&MyClass::setData)
|
126 |
+
);
|
127 |
+
|
128 |
+
.. warning::
|
129 |
+
|
130 |
+
Code with invalid return value policies might access uninitialized memory or
|
131 |
+
free data structures multiple times, which can lead to hard-to-debug
|
132 |
+
non-determinism and segmentation faults, hence it is worth spending the
|
133 |
+
time to understand all the different options in the table above.
|
134 |
+
|
135 |
+
.. note::
|
136 |
+
|
137 |
+
One important aspect of the above policies is that they only apply to
|
138 |
+
instances which pybind11 has *not* seen before, in which case the policy
|
139 |
+
clarifies essential questions about the return value's lifetime and
|
140 |
+
ownership. When pybind11 knows the instance already (as identified by its
|
141 |
+
type and address in memory), it will return the existing Python object
|
142 |
+
wrapper rather than creating a new copy.
|
143 |
+
|
144 |
+
.. note::
|
145 |
+
|
146 |
+
The next section on :ref:`call_policies` discusses *call policies* that can be
|
147 |
+
specified *in addition* to a return value policy from the list above. Call
|
148 |
+
policies indicate reference relationships that can involve both return values
|
149 |
+
and parameters of functions.
|
150 |
+
|
151 |
+
.. note::
|
152 |
+
|
153 |
+
As an alternative to elaborate call policies and lifetime management logic,
|
154 |
+
consider using smart pointers (see the section on :ref:`smart_pointers` for
|
155 |
+
details). Smart pointers can tell whether an object is still referenced from
|
156 |
+
C++ or Python, which generally eliminates the kinds of inconsistencies that
|
157 |
+
can lead to crashes or undefined behavior. For functions returning smart
|
158 |
+
pointers, it is not necessary to specify a return value policy.
|
159 |
+
|
160 |
+
.. _call_policies:
|
161 |
+
|
162 |
+
Additional call policies
|
163 |
+
========================
|
164 |
+
|
165 |
+
In addition to the above return value policies, further *call policies* can be
|
166 |
+
specified to indicate dependencies between parameters or ensure a certain state
|
167 |
+
for the function call.
|
168 |
+
|
169 |
+
Keep alive
|
170 |
+
----------
|
171 |
+
|
172 |
+
In general, this policy is required when the C++ object is any kind of container
|
173 |
+
and another object is being added to the container. ``keep_alive<Nurse, Patient>``
|
174 |
+
indicates that the argument with index ``Patient`` should be kept alive at least
|
175 |
+
until the argument with index ``Nurse`` is freed by the garbage collector. Argument
|
176 |
+
indices start at one, while zero refers to the return value. For methods, index
|
177 |
+
``1`` refers to the implicit ``this`` pointer, while regular arguments begin at
|
178 |
+
index ``2``. Arbitrarily many call policies can be specified. When a ``Nurse``
|
179 |
+
with value ``None`` is detected at runtime, the call policy does nothing.
|
180 |
+
|
181 |
+
When the nurse is not a pybind11-registered type, the implementation internally
|
182 |
+
relies on the ability to create a *weak reference* to the nurse object. When
|
183 |
+
the nurse object is not a pybind11-registered type and does not support weak
|
184 |
+
references, an exception will be thrown.
|
185 |
+
|
186 |
+
If you use an incorrect argument index, you will get a ``RuntimeError`` saying
|
187 |
+
``Could not activate keep_alive!``. You should review the indices you're using.
|
188 |
+
|
189 |
+
Consider the following example: here, the binding code for a list append
|
190 |
+
operation ties the lifetime of the newly added element to the underlying
|
191 |
+
container:
|
192 |
+
|
193 |
+
.. code-block:: cpp
|
194 |
+
|
195 |
+
py::class_<List>(m, "List")
|
196 |
+
.def("append", &List::append, py::keep_alive<1, 2>());
|
197 |
+
|
198 |
+
For consistency, the argument indexing is identical for constructors. Index
|
199 |
+
``1`` still refers to the implicit ``this`` pointer, i.e. the object which is
|
200 |
+
being constructed. Index ``0`` refers to the return type which is presumed to
|
201 |
+
be ``void`` when a constructor is viewed like a function. The following example
|
202 |
+
ties the lifetime of the constructor element to the constructed object:
|
203 |
+
|
204 |
+
.. code-block:: cpp
|
205 |
+
|
206 |
+
py::class_<Nurse>(m, "Nurse")
|
207 |
+
.def(py::init<Patient &>(), py::keep_alive<1, 2>());
|
208 |
+
|
209 |
+
.. note::
|
210 |
+
|
211 |
+
``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse,
|
212 |
+
Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient ==
|
213 |
+
0) policies from Boost.Python.
|
214 |
+
|
215 |
+
Call guard
|
216 |
+
----------
|
217 |
+
|
218 |
+
The ``call_guard<T>`` policy allows any scope guard type ``T`` to be placed
|
219 |
+
around the function call. For example, this definition:
|
220 |
+
|
221 |
+
.. code-block:: cpp
|
222 |
+
|
223 |
+
m.def("foo", foo, py::call_guard<T>());
|
224 |
+
|
225 |
+
is equivalent to the following pseudocode:
|
226 |
+
|
227 |
+
.. code-block:: cpp
|
228 |
+
|
229 |
+
m.def("foo", [](args...) {
|
230 |
+
T scope_guard;
|
231 |
+
return foo(args...); // forwarded arguments
|
232 |
+
});
|
233 |
+
|
234 |
+
The only requirement is that ``T`` is default-constructible, but otherwise any
|
235 |
+
scope guard will work. This is very useful in combination with ``gil_scoped_release``.
|
236 |
+
See :ref:`gil`.
|
237 |
+
|
238 |
+
Multiple guards can also be specified as ``py::call_guard<T1, T2, T3...>``. The
|
239 |
+
constructor order is left to right and destruction happens in reverse.
|
240 |
+
|
241 |
+
.. seealso::
|
242 |
+
|
243 |
+
The file :file:`tests/test_call_policies.cpp` contains a complete example
|
244 |
+
that demonstrates using `keep_alive` and `call_guard` in more detail.
|
245 |
+
|
246 |
+
.. _python_objects_as_args:
|
247 |
+
|
248 |
+
Python objects as arguments
|
249 |
+
===========================
|
250 |
+
|
251 |
+
pybind11 exposes all major Python types using thin C++ wrapper classes. These
|
252 |
+
wrapper classes can also be used as parameters of functions in bindings, which
|
253 |
+
makes it possible to directly work with native Python types on the C++ side.
|
254 |
+
For instance, the following statement iterates over a Python ``dict``:
|
255 |
+
|
256 |
+
.. code-block:: cpp
|
257 |
+
|
258 |
+
void print_dict(const py::dict& dict) {
|
259 |
+
/* Easily interact with Python types */
|
260 |
+
for (auto item : dict)
|
261 |
+
std::cout << "key=" << std::string(py::str(item.first)) << ", "
|
262 |
+
<< "value=" << std::string(py::str(item.second)) << std::endl;
|
263 |
+
}
|
264 |
+
|
265 |
+
It can be exported:
|
266 |
+
|
267 |
+
.. code-block:: cpp
|
268 |
+
|
269 |
+
m.def("print_dict", &print_dict);
|
270 |
+
|
271 |
+
And used in Python as usual:
|
272 |
+
|
273 |
+
.. code-block:: pycon
|
274 |
+
|
275 |
+
>>> print_dict({"foo": 123, "bar": "hello"})
|
276 |
+
key=foo, value=123
|
277 |
+
key=bar, value=hello
|
278 |
+
|
279 |
+
For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`.
|
280 |
+
|
281 |
+
Accepting \*args and \*\*kwargs
|
282 |
+
===============================
|
283 |
+
|
284 |
+
Python provides a useful mechanism to define functions that accept arbitrary
|
285 |
+
numbers of arguments and keyword arguments:
|
286 |
+
|
287 |
+
.. code-block:: python
|
288 |
+
|
289 |
+
def generic(*args, **kwargs):
|
290 |
+
... # do something with args and kwargs
|
291 |
+
|
292 |
+
Such functions can also be created using pybind11:
|
293 |
+
|
294 |
+
.. code-block:: cpp
|
295 |
+
|
296 |
+
void generic(py::args args, const py::kwargs& kwargs) {
|
297 |
+
/// .. do something with args
|
298 |
+
if (kwargs)
|
299 |
+
/// .. do something with kwargs
|
300 |
+
}
|
301 |
+
|
302 |
+
/// Binding code
|
303 |
+
m.def("generic", &generic);
|
304 |
+
|
305 |
+
The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives
|
306 |
+
from ``py::dict``.
|
307 |
+
|
308 |
+
You may also use just one or the other, and may combine these with other
|
309 |
+
arguments. Note, however, that ``py::kwargs`` must always be the last argument
|
310 |
+
of the function, and ``py::args`` implies that any further arguments are
|
311 |
+
keyword-only (see :ref:`keyword_only_arguments`).
|
312 |
+
|
313 |
+
Please refer to the other examples for details on how to iterate over these,
|
314 |
+
and on how to cast their entries into C++ objects. A demonstration is also
|
315 |
+
available in ``tests/test_kwargs_and_defaults.cpp``.
|
316 |
+
|
317 |
+
.. note::
|
318 |
+
|
319 |
+
When combining \*args or \*\*kwargs with :ref:`keyword_args` you should
|
320 |
+
*not* include ``py::arg`` tags for the ``py::args`` and ``py::kwargs``
|
321 |
+
arguments.
|
322 |
+
|
323 |
+
Default arguments revisited
|
324 |
+
===========================
|
325 |
+
|
326 |
+
The section on :ref:`default_args` previously discussed basic usage of default
|
327 |
+
arguments using pybind11. One noteworthy aspect of their implementation is that
|
328 |
+
default arguments are converted to Python objects right at declaration time.
|
329 |
+
Consider the following example:
|
330 |
+
|
331 |
+
.. code-block:: cpp
|
332 |
+
|
333 |
+
py::class_<MyClass>("MyClass")
|
334 |
+
.def("myFunction", py::arg("arg") = SomeType(123));
|
335 |
+
|
336 |
+
In this case, pybind11 must already be set up to deal with values of the type
|
337 |
+
``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an
|
338 |
+
exception will be thrown.
|
339 |
+
|
340 |
+
Another aspect worth highlighting is that the "preview" of the default argument
|
341 |
+
in the function signature is generated using the object's ``__repr__`` method.
|
342 |
+
If not available, the signature may not be very helpful, e.g.:
|
343 |
+
|
344 |
+
.. code-block:: pycon
|
345 |
+
|
346 |
+
FUNCTIONS
|
347 |
+
...
|
348 |
+
| myFunction(...)
|
349 |
+
| Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType
|
350 |
+
...
|
351 |
+
|
352 |
+
The first way of addressing this is by defining ``SomeType.__repr__``.
|
353 |
+
Alternatively, it is possible to specify the human-readable preview of the
|
354 |
+
default argument manually using the ``arg_v`` notation:
|
355 |
+
|
356 |
+
.. code-block:: cpp
|
357 |
+
|
358 |
+
py::class_<MyClass>("MyClass")
|
359 |
+
.def("myFunction", py::arg_v("arg", SomeType(123), "SomeType(123)"));
|
360 |
+
|
361 |
+
Sometimes it may be necessary to pass a null pointer value as a default
|
362 |
+
argument. In this case, remember to cast it to the underlying type in question,
|
363 |
+
like so:
|
364 |
+
|
365 |
+
.. code-block:: cpp
|
366 |
+
|
367 |
+
py::class_<MyClass>("MyClass")
|
368 |
+
.def("myFunction", py::arg("arg") = static_cast<SomeType *>(nullptr));
|
369 |
+
|
370 |
+
.. _keyword_only_arguments:
|
371 |
+
|
372 |
+
Keyword-only arguments
|
373 |
+
======================
|
374 |
+
|
375 |
+
Python implements keyword-only arguments by specifying an unnamed ``*``
|
376 |
+
argument in a function definition:
|
377 |
+
|
378 |
+
.. code-block:: python
|
379 |
+
|
380 |
+
def f(a, *, b): # a can be positional or via keyword; b must be via keyword
|
381 |
+
pass
|
382 |
+
|
383 |
+
|
384 |
+
f(a=1, b=2) # good
|
385 |
+
f(b=2, a=1) # good
|
386 |
+
f(1, b=2) # good
|
387 |
+
f(1, 2) # TypeError: f() takes 1 positional argument but 2 were given
|
388 |
+
|
389 |
+
Pybind11 provides a ``py::kw_only`` object that allows you to implement
|
390 |
+
the same behaviour by specifying the object between positional and keyword-only
|
391 |
+
argument annotations when registering the function:
|
392 |
+
|
393 |
+
.. code-block:: cpp
|
394 |
+
|
395 |
+
m.def("f", [](int a, int b) { /* ... */ },
|
396 |
+
py::arg("a"), py::kw_only(), py::arg("b"));
|
397 |
+
|
398 |
+
.. versionadded:: 2.6
|
399 |
+
|
400 |
+
A ``py::args`` argument implies that any following arguments are keyword-only,
|
401 |
+
as if ``py::kw_only()`` had been specified in the same relative location of the
|
402 |
+
argument list as the ``py::args`` argument. The ``py::kw_only()`` may be
|
403 |
+
included to be explicit about this, but is not required.
|
404 |
+
|
405 |
+
.. versionchanged:: 2.9
|
406 |
+
This can now be combined with ``py::args``. Before, ``py::args`` could only
|
407 |
+
occur at the end of the argument list, or immediately before a ``py::kwargs``
|
408 |
+
argument at the end.
|
409 |
+
|
410 |
+
|
411 |
+
Positional-only arguments
|
412 |
+
=========================
|
413 |
+
|
414 |
+
Python 3.8 introduced a new positional-only argument syntax, using ``/`` in the
|
415 |
+
function definition (note that this has been a convention for CPython
|
416 |
+
positional arguments, such as in ``pow()``, since Python 2). You can
|
417 |
+
do the same thing in any version of Python using ``py::pos_only()``:
|
418 |
+
|
419 |
+
.. code-block:: cpp
|
420 |
+
|
421 |
+
m.def("f", [](int a, int b) { /* ... */ },
|
422 |
+
py::arg("a"), py::pos_only(), py::arg("b"));
|
423 |
+
|
424 |
+
You now cannot give argument ``a`` by keyword. This can be combined with
|
425 |
+
keyword-only arguments, as well.
|
426 |
+
|
427 |
+
.. versionadded:: 2.6
|
428 |
+
|
429 |
+
.. _nonconverting_arguments:
|
430 |
+
|
431 |
+
Non-converting arguments
|
432 |
+
========================
|
433 |
+
|
434 |
+
Certain argument types may support conversion from one type to another. Some
|
435 |
+
examples of conversions are:
|
436 |
+
|
437 |
+
* :ref:`implicit_conversions` declared using ``py::implicitly_convertible<A,B>()``
|
438 |
+
* Calling a method accepting a double with an integer argument
|
439 |
+
* Calling a ``std::complex<float>`` argument with a non-complex python type
|
440 |
+
(for example, with a float). (Requires the optional ``pybind11/complex.h``
|
441 |
+
header).
|
442 |
+
* Calling a function taking an Eigen matrix reference with a numpy array of the
|
443 |
+
wrong type or of an incompatible data layout. (Requires the optional
|
444 |
+
``pybind11/eigen.h`` header).
|
445 |
+
|
446 |
+
This behaviour is sometimes undesirable: the binding code may prefer to raise
|
447 |
+
an error rather than convert the argument. This behaviour can be obtained
|
448 |
+
through ``py::arg`` by calling the ``.noconvert()`` method of the ``py::arg``
|
449 |
+
object, such as:
|
450 |
+
|
451 |
+
.. code-block:: cpp
|
452 |
+
|
453 |
+
m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert());
|
454 |
+
m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f"));
|
455 |
+
|
456 |
+
Attempting the call the second function (the one without ``.noconvert()``) with
|
457 |
+
an integer will succeed, but attempting to call the ``.noconvert()`` version
|
458 |
+
will fail with a ``TypeError``:
|
459 |
+
|
460 |
+
.. code-block:: pycon
|
461 |
+
|
462 |
+
>>> floats_preferred(4)
|
463 |
+
2.0
|
464 |
+
>>> floats_only(4)
|
465 |
+
Traceback (most recent call last):
|
466 |
+
File "<stdin>", line 1, in <module>
|
467 |
+
TypeError: floats_only(): incompatible function arguments. The following argument types are supported:
|
468 |
+
1. (f: float) -> float
|
469 |
+
|
470 |
+
Invoked with: 4
|
471 |
+
|
472 |
+
You may, of course, combine this with the :var:`_a` shorthand notation (see
|
473 |
+
:ref:`keyword_args`) and/or :ref:`default_args`. It is also permitted to omit
|
474 |
+
the argument name by using the ``py::arg()`` constructor without an argument
|
475 |
+
name, i.e. by specifying ``py::arg().noconvert()``.
|
476 |
+
|
477 |
+
.. note::
|
478 |
+
|
479 |
+
When specifying ``py::arg`` options it is necessary to provide the same
|
480 |
+
number of options as the bound function has arguments. Thus if you want to
|
481 |
+
enable no-convert behaviour for just one of several arguments, you will
|
482 |
+
need to specify a ``py::arg()`` annotation for each argument with the
|
483 |
+
no-convert argument modified to ``py::arg().noconvert()``.
|
484 |
+
|
485 |
+
.. _none_arguments:
|
486 |
+
|
487 |
+
Allow/Prohibiting None arguments
|
488 |
+
================================
|
489 |
+
|
490 |
+
When a C++ type registered with :class:`py::class_` is passed as an argument to
|
491 |
+
a function taking the instance as pointer or shared holder (e.g. ``shared_ptr``
|
492 |
+
or a custom, copyable holder as described in :ref:`smart_pointers`), pybind
|
493 |
+
allows ``None`` to be passed from Python which results in calling the C++
|
494 |
+
function with ``nullptr`` (or an empty holder) for the argument.
|
495 |
+
|
496 |
+
To explicitly enable or disable this behaviour, using the
|
497 |
+
``.none`` method of the :class:`py::arg` object:
|
498 |
+
|
499 |
+
.. code-block:: cpp
|
500 |
+
|
501 |
+
py::class_<Dog>(m, "Dog").def(py::init<>());
|
502 |
+
py::class_<Cat>(m, "Cat").def(py::init<>());
|
503 |
+
m.def("bark", [](Dog *dog) -> std::string {
|
504 |
+
if (dog) return "woof!"; /* Called with a Dog instance */
|
505 |
+
else return "(no dog)"; /* Called with None, dog == nullptr */
|
506 |
+
}, py::arg("dog").none(true));
|
507 |
+
m.def("meow", [](Cat *cat) -> std::string {
|
508 |
+
// Can't be called with None argument
|
509 |
+
return "meow";
|
510 |
+
}, py::arg("cat").none(false));
|
511 |
+
|
512 |
+
With the above, the Python call ``bark(None)`` will return the string ``"(no
|
513 |
+
dog)"``, while attempting to call ``meow(None)`` will raise a ``TypeError``:
|
514 |
+
|
515 |
+
.. code-block:: pycon
|
516 |
+
|
517 |
+
>>> from animals import Dog, Cat, bark, meow
|
518 |
+
>>> bark(Dog())
|
519 |
+
'woof!'
|
520 |
+
>>> meow(Cat())
|
521 |
+
'meow'
|
522 |
+
>>> bark(None)
|
523 |
+
'(no dog)'
|
524 |
+
>>> meow(None)
|
525 |
+
Traceback (most recent call last):
|
526 |
+
File "<stdin>", line 1, in <module>
|
527 |
+
TypeError: meow(): incompatible function arguments. The following argument types are supported:
|
528 |
+
1. (cat: animals.Cat) -> str
|
529 |
+
|
530 |
+
Invoked with: None
|
531 |
+
|
532 |
+
The default behaviour when the tag is unspecified is to allow ``None``.
|
533 |
+
|
534 |
+
.. note::
|
535 |
+
|
536 |
+
Even when ``.none(true)`` is specified for an argument, ``None`` will be converted to a
|
537 |
+
``nullptr`` *only* for custom and :ref:`opaque <opaque>` types. Pointers to built-in types
|
538 |
+
(``double *``, ``int *``, ...) and STL types (``std::vector<T> *``, ...; if ``pybind11/stl.h``
|
539 |
+
is included) are copied when converted to C++ (see :doc:`/advanced/cast/overview`) and will
|
540 |
+
not allow ``None`` as argument. To pass optional argument of these copied types consider
|
541 |
+
using ``std::optional<T>``
|
542 |
+
|
543 |
+
.. _overload_resolution:
|
544 |
+
|
545 |
+
Overload resolution order
|
546 |
+
=========================
|
547 |
+
|
548 |
+
When a function or method with multiple overloads is called from Python,
|
549 |
+
pybind11 determines which overload to call in two passes. The first pass
|
550 |
+
attempts to call each overload without allowing argument conversion (as if
|
551 |
+
every argument had been specified as ``py::arg().noconvert()`` as described
|
552 |
+
above).
|
553 |
+
|
554 |
+
If no overload succeeds in the no-conversion first pass, a second pass is
|
555 |
+
attempted in which argument conversion is allowed (except where prohibited via
|
556 |
+
an explicit ``py::arg().noconvert()`` attribute in the function definition).
|
557 |
+
|
558 |
+
If the second pass also fails a ``TypeError`` is raised.
|
559 |
+
|
560 |
+
Within each pass, overloads are tried in the order they were registered with
|
561 |
+
pybind11. If the ``py::prepend()`` tag is added to the definition, a function
|
562 |
+
can be placed at the beginning of the overload sequence instead, allowing user
|
563 |
+
overloads to proceed built in functions.
|
564 |
+
|
565 |
+
What this means in practice is that pybind11 will prefer any overload that does
|
566 |
+
not require conversion of arguments to an overload that does, but otherwise
|
567 |
+
prefers earlier-defined overloads to later-defined ones.
|
568 |
+
|
569 |
+
.. note::
|
570 |
+
|
571 |
+
pybind11 does *not* further prioritize based on the number/pattern of
|
572 |
+
overloaded arguments. That is, pybind11 does not prioritize a function
|
573 |
+
requiring one conversion over one requiring three, but only prioritizes
|
574 |
+
overloads requiring no conversion at all to overloads that require
|
575 |
+
conversion of at least one argument.
|
576 |
+
|
577 |
+
.. versionadded:: 2.6
|
578 |
+
|
579 |
+
The ``py::prepend()`` tag.
|
580 |
+
|
581 |
+
Binding functions with template parameters
|
582 |
+
==========================================
|
583 |
+
|
584 |
+
You can bind functions that have template parameters. Here's a function:
|
585 |
+
|
586 |
+
.. code-block:: cpp
|
587 |
+
|
588 |
+
template <typename T>
|
589 |
+
void set(T t);
|
590 |
+
|
591 |
+
C++ templates cannot be instantiated at runtime, so you cannot bind the
|
592 |
+
non-instantiated function:
|
593 |
+
|
594 |
+
.. code-block:: cpp
|
595 |
+
|
596 |
+
// BROKEN (this will not compile)
|
597 |
+
m.def("set", &set);
|
598 |
+
|
599 |
+
You must bind each instantiated function template separately. You may bind
|
600 |
+
each instantiation with the same name, which will be treated the same as
|
601 |
+
an overloaded function:
|
602 |
+
|
603 |
+
.. code-block:: cpp
|
604 |
+
|
605 |
+
m.def("set", &set<int>);
|
606 |
+
m.def("set", &set<std::string>);
|
607 |
+
|
608 |
+
Sometimes it's more clear to bind them with separate names, which is also
|
609 |
+
an option:
|
610 |
+
|
611 |
+
.. code-block:: cpp
|
612 |
+
|
613 |
+
m.def("setInt", &set<int>);
|
614 |
+
m.def("setString", &set<std::string>);
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/misc.rst
ADDED
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Miscellaneous
|
2 |
+
#############
|
3 |
+
|
4 |
+
.. _macro_notes:
|
5 |
+
|
6 |
+
General notes regarding convenience macros
|
7 |
+
==========================================
|
8 |
+
|
9 |
+
pybind11 provides a few convenience macros such as
|
10 |
+
:func:`PYBIND11_DECLARE_HOLDER_TYPE` and ``PYBIND11_OVERRIDE_*``. Since these
|
11 |
+
are "just" macros that are evaluated in the preprocessor (which has no concept
|
12 |
+
of types), they *will* get confused by commas in a template argument; for
|
13 |
+
example, consider:
|
14 |
+
|
15 |
+
.. code-block:: cpp
|
16 |
+
|
17 |
+
PYBIND11_OVERRIDE(MyReturnType<T1, T2>, Class<T3, T4>, func)
|
18 |
+
|
19 |
+
The limitation of the C preprocessor interprets this as five arguments (with new
|
20 |
+
arguments beginning after each comma) rather than three. To get around this,
|
21 |
+
there are two alternatives: you can use a type alias, or you can wrap the type
|
22 |
+
using the ``PYBIND11_TYPE`` macro:
|
23 |
+
|
24 |
+
.. code-block:: cpp
|
25 |
+
|
26 |
+
// Version 1: using a type alias
|
27 |
+
using ReturnType = MyReturnType<T1, T2>;
|
28 |
+
using ClassType = Class<T3, T4>;
|
29 |
+
PYBIND11_OVERRIDE(ReturnType, ClassType, func);
|
30 |
+
|
31 |
+
// Version 2: using the PYBIND11_TYPE macro:
|
32 |
+
PYBIND11_OVERRIDE(PYBIND11_TYPE(MyReturnType<T1, T2>),
|
33 |
+
PYBIND11_TYPE(Class<T3, T4>), func)
|
34 |
+
|
35 |
+
The ``PYBIND11_MAKE_OPAQUE`` macro does *not* require the above workarounds.
|
36 |
+
|
37 |
+
.. _gil:
|
38 |
+
|
39 |
+
Global Interpreter Lock (GIL)
|
40 |
+
=============================
|
41 |
+
|
42 |
+
When calling a C++ function from Python, the GIL is always held.
|
43 |
+
The classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
|
44 |
+
used to acquire and release the global interpreter lock in the body of a C++
|
45 |
+
function call. In this way, long-running C++ code can be parallelized using
|
46 |
+
multiple Python threads. Taking :ref:`overriding_virtuals` as an example, this
|
47 |
+
could be realized as follows (important changes highlighted):
|
48 |
+
|
49 |
+
.. code-block:: cpp
|
50 |
+
:emphasize-lines: 8,9,31,32
|
51 |
+
|
52 |
+
class PyAnimal : public Animal {
|
53 |
+
public:
|
54 |
+
/* Inherit the constructors */
|
55 |
+
using Animal::Animal;
|
56 |
+
|
57 |
+
/* Trampoline (need one for each virtual function) */
|
58 |
+
std::string go(int n_times) {
|
59 |
+
/* Acquire GIL before calling Python code */
|
60 |
+
py::gil_scoped_acquire acquire;
|
61 |
+
|
62 |
+
PYBIND11_OVERRIDE_PURE(
|
63 |
+
std::string, /* Return type */
|
64 |
+
Animal, /* Parent class */
|
65 |
+
go, /* Name of function */
|
66 |
+
n_times /* Argument(s) */
|
67 |
+
);
|
68 |
+
}
|
69 |
+
};
|
70 |
+
|
71 |
+
PYBIND11_MODULE(example, m) {
|
72 |
+
py::class_<Animal, PyAnimal> animal(m, "Animal");
|
73 |
+
animal
|
74 |
+
.def(py::init<>())
|
75 |
+
.def("go", &Animal::go);
|
76 |
+
|
77 |
+
py::class_<Dog>(m, "Dog", animal)
|
78 |
+
.def(py::init<>());
|
79 |
+
|
80 |
+
m.def("call_go", [](Animal *animal) -> std::string {
|
81 |
+
/* Release GIL before calling into (potentially long-running) C++ code */
|
82 |
+
py::gil_scoped_release release;
|
83 |
+
return call_go(animal);
|
84 |
+
});
|
85 |
+
}
|
86 |
+
|
87 |
+
The ``call_go`` wrapper can also be simplified using the ``call_guard`` policy
|
88 |
+
(see :ref:`call_policies`) which yields the same result:
|
89 |
+
|
90 |
+
.. code-block:: cpp
|
91 |
+
|
92 |
+
m.def("call_go", &call_go, py::call_guard<py::gil_scoped_release>());
|
93 |
+
|
94 |
+
|
95 |
+
Binding sequence data types, iterators, the slicing protocol, etc.
|
96 |
+
==================================================================
|
97 |
+
|
98 |
+
Please refer to the supplemental example for details.
|
99 |
+
|
100 |
+
.. seealso::
|
101 |
+
|
102 |
+
The file :file:`tests/test_sequences_and_iterators.cpp` contains a
|
103 |
+
complete example that shows how to bind a sequence data type, including
|
104 |
+
length queries (``__len__``), iterators (``__iter__``), the slicing
|
105 |
+
protocol and other kinds of useful operations.
|
106 |
+
|
107 |
+
|
108 |
+
Partitioning code over multiple extension modules
|
109 |
+
=================================================
|
110 |
+
|
111 |
+
It's straightforward to split binding code over multiple extension modules,
|
112 |
+
while referencing types that are declared elsewhere. Everything "just" works
|
113 |
+
without any special precautions. One exception to this rule occurs when
|
114 |
+
extending a type declared in another extension module. Recall the basic example
|
115 |
+
from Section :ref:`inheritance`.
|
116 |
+
|
117 |
+
.. code-block:: cpp
|
118 |
+
|
119 |
+
py::class_<Pet> pet(m, "Pet");
|
120 |
+
pet.def(py::init<const std::string &>())
|
121 |
+
.def_readwrite("name", &Pet::name);
|
122 |
+
|
123 |
+
py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
|
124 |
+
.def(py::init<const std::string &>())
|
125 |
+
.def("bark", &Dog::bark);
|
126 |
+
|
127 |
+
Suppose now that ``Pet`` bindings are defined in a module named ``basic``,
|
128 |
+
whereas the ``Dog`` bindings are defined somewhere else. The challenge is of
|
129 |
+
course that the variable ``pet`` is not available anymore though it is needed
|
130 |
+
to indicate the inheritance relationship to the constructor of ``class_<Dog>``.
|
131 |
+
However, it can be acquired as follows:
|
132 |
+
|
133 |
+
.. code-block:: cpp
|
134 |
+
|
135 |
+
py::object pet = (py::object) py::module_::import("basic").attr("Pet");
|
136 |
+
|
137 |
+
py::class_<Dog>(m, "Dog", pet)
|
138 |
+
.def(py::init<const std::string &>())
|
139 |
+
.def("bark", &Dog::bark);
|
140 |
+
|
141 |
+
Alternatively, you can specify the base class as a template parameter option to
|
142 |
+
``class_``, which performs an automated lookup of the corresponding Python
|
143 |
+
type. Like the above code, however, this also requires invoking the ``import``
|
144 |
+
function once to ensure that the pybind11 binding code of the module ``basic``
|
145 |
+
has been executed:
|
146 |
+
|
147 |
+
.. code-block:: cpp
|
148 |
+
|
149 |
+
py::module_::import("basic");
|
150 |
+
|
151 |
+
py::class_<Dog, Pet>(m, "Dog")
|
152 |
+
.def(py::init<const std::string &>())
|
153 |
+
.def("bark", &Dog::bark);
|
154 |
+
|
155 |
+
Naturally, both methods will fail when there are cyclic dependencies.
|
156 |
+
|
157 |
+
Note that pybind11 code compiled with hidden-by-default symbol visibility (e.g.
|
158 |
+
via the command line flag ``-fvisibility=hidden`` on GCC/Clang), which is
|
159 |
+
required for proper pybind11 functionality, can interfere with the ability to
|
160 |
+
access types defined in another extension module. Working around this requires
|
161 |
+
manually exporting types that are accessed by multiple extension modules;
|
162 |
+
pybind11 provides a macro to do just this:
|
163 |
+
|
164 |
+
.. code-block:: cpp
|
165 |
+
|
166 |
+
class PYBIND11_EXPORT Dog : public Animal {
|
167 |
+
...
|
168 |
+
};
|
169 |
+
|
170 |
+
Note also that it is possible (although would rarely be required) to share arbitrary
|
171 |
+
C++ objects between extension modules at runtime. Internal library data is shared
|
172 |
+
between modules using capsule machinery [#f6]_ which can be also utilized for
|
173 |
+
storing, modifying and accessing user-defined data. Note that an extension module
|
174 |
+
will "see" other extensions' data if and only if they were built with the same
|
175 |
+
pybind11 version. Consider the following example:
|
176 |
+
|
177 |
+
.. code-block:: cpp
|
178 |
+
|
179 |
+
auto data = reinterpret_cast<MyData *>(py::get_shared_data("mydata"));
|
180 |
+
if (!data)
|
181 |
+
data = static_cast<MyData *>(py::set_shared_data("mydata", new MyData(42)));
|
182 |
+
|
183 |
+
If the above snippet was used in several separately compiled extension modules,
|
184 |
+
the first one to be imported would create a ``MyData`` instance and associate
|
185 |
+
a ``"mydata"`` key with a pointer to it. Extensions that are imported later
|
186 |
+
would be then able to access the data behind the same pointer.
|
187 |
+
|
188 |
+
.. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules
|
189 |
+
|
190 |
+
Module Destructors
|
191 |
+
==================
|
192 |
+
|
193 |
+
pybind11 does not provide an explicit mechanism to invoke cleanup code at
|
194 |
+
module destruction time. In rare cases where such functionality is required, it
|
195 |
+
is possible to emulate it using Python capsules or weak references with a
|
196 |
+
destruction callback.
|
197 |
+
|
198 |
+
.. code-block:: cpp
|
199 |
+
|
200 |
+
auto cleanup_callback = []() {
|
201 |
+
// perform cleanup here -- this function is called with the GIL held
|
202 |
+
};
|
203 |
+
|
204 |
+
m.add_object("_cleanup", py::capsule(cleanup_callback));
|
205 |
+
|
206 |
+
This approach has the potential downside that instances of classes exposed
|
207 |
+
within the module may still be alive when the cleanup callback is invoked
|
208 |
+
(whether this is acceptable will generally depend on the application).
|
209 |
+
|
210 |
+
Alternatively, the capsule may also be stashed within a type object, which
|
211 |
+
ensures that it not called before all instances of that type have been
|
212 |
+
collected:
|
213 |
+
|
214 |
+
.. code-block:: cpp
|
215 |
+
|
216 |
+
auto cleanup_callback = []() { /* ... */ };
|
217 |
+
m.attr("BaseClass").attr("_cleanup") = py::capsule(cleanup_callback);
|
218 |
+
|
219 |
+
Both approaches also expose a potentially dangerous ``_cleanup`` attribute in
|
220 |
+
Python, which may be undesirable from an API standpoint (a premature explicit
|
221 |
+
call from Python might lead to undefined behavior). Yet another approach that
|
222 |
+
avoids this issue involves weak reference with a cleanup callback:
|
223 |
+
|
224 |
+
.. code-block:: cpp
|
225 |
+
|
226 |
+
// Register a callback function that is invoked when the BaseClass object is collected
|
227 |
+
py::cpp_function cleanup_callback(
|
228 |
+
[](py::handle weakref) {
|
229 |
+
// perform cleanup here -- this function is called with the GIL held
|
230 |
+
|
231 |
+
weakref.dec_ref(); // release weak reference
|
232 |
+
}
|
233 |
+
);
|
234 |
+
|
235 |
+
// Create a weak reference with a cleanup callback and initially leak it
|
236 |
+
(void) py::weakref(m.attr("BaseClass"), cleanup_callback).release();
|
237 |
+
|
238 |
+
.. note::
|
239 |
+
|
240 |
+
PyPy does not garbage collect objects when the interpreter exits. An alternative
|
241 |
+
approach (which also works on CPython) is to use the :py:mod:`atexit` module [#f7]_,
|
242 |
+
for example:
|
243 |
+
|
244 |
+
.. code-block:: cpp
|
245 |
+
|
246 |
+
auto atexit = py::module_::import("atexit");
|
247 |
+
atexit.attr("register")(py::cpp_function([]() {
|
248 |
+
// perform cleanup here -- this function is called with the GIL held
|
249 |
+
}));
|
250 |
+
|
251 |
+
.. [#f7] https://docs.python.org/3/library/atexit.html
|
252 |
+
|
253 |
+
|
254 |
+
Generating documentation using Sphinx
|
255 |
+
=====================================
|
256 |
+
|
257 |
+
Sphinx [#f4]_ has the ability to inspect the signatures and documentation
|
258 |
+
strings in pybind11-based extension modules to automatically generate beautiful
|
259 |
+
documentation in a variety formats. The python_example repository [#f5]_ contains a
|
260 |
+
simple example repository which uses this approach.
|
261 |
+
|
262 |
+
There are two potential gotchas when using this approach: first, make sure that
|
263 |
+
the resulting strings do not contain any :kbd:`TAB` characters, which break the
|
264 |
+
docstring parsing routines. You may want to use C++11 raw string literals,
|
265 |
+
which are convenient for multi-line comments. Conveniently, any excess
|
266 |
+
indentation will be automatically be removed by Sphinx. However, for this to
|
267 |
+
work, it is important that all lines are indented consistently, i.e.:
|
268 |
+
|
269 |
+
.. code-block:: cpp
|
270 |
+
|
271 |
+
// ok
|
272 |
+
m.def("foo", &foo, R"mydelimiter(
|
273 |
+
The foo function
|
274 |
+
|
275 |
+
Parameters
|
276 |
+
----------
|
277 |
+
)mydelimiter");
|
278 |
+
|
279 |
+
// *not ok*
|
280 |
+
m.def("foo", &foo, R"mydelimiter(The foo function
|
281 |
+
|
282 |
+
Parameters
|
283 |
+
----------
|
284 |
+
)mydelimiter");
|
285 |
+
|
286 |
+
By default, pybind11 automatically generates and prepends a signature to the docstring of a function
|
287 |
+
registered with ``module_::def()`` and ``class_::def()``. Sometimes this
|
288 |
+
behavior is not desirable, because you want to provide your own signature or remove
|
289 |
+
the docstring completely to exclude the function from the Sphinx documentation.
|
290 |
+
The class ``options`` allows you to selectively suppress auto-generated signatures:
|
291 |
+
|
292 |
+
.. code-block:: cpp
|
293 |
+
|
294 |
+
PYBIND11_MODULE(example, m) {
|
295 |
+
py::options options;
|
296 |
+
options.disable_function_signatures();
|
297 |
+
|
298 |
+
m.def("add", [](int a, int b) { return a + b; }, "A function which adds two numbers");
|
299 |
+
}
|
300 |
+
|
301 |
+
Note that changes to the settings affect only function bindings created during the
|
302 |
+
lifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function,
|
303 |
+
the default settings are restored to prevent unwanted side effects.
|
304 |
+
|
305 |
+
.. [#f4] http://www.sphinx-doc.org
|
306 |
+
.. [#f5] http://github.com/pybind/python_example
|
307 |
+
|
308 |
+
.. _avoiding-cpp-types-in-docstrings:
|
309 |
+
|
310 |
+
Avoiding C++ types in docstrings
|
311 |
+
================================
|
312 |
+
|
313 |
+
Docstrings are generated at the time of the declaration, e.g. when ``.def(...)`` is called.
|
314 |
+
At this point parameter and return types should be known to pybind11.
|
315 |
+
If a custom type is not exposed yet through a ``py::class_`` constructor or a custom type caster,
|
316 |
+
its C++ type name will be used instead to generate the signature in the docstring:
|
317 |
+
|
318 |
+
.. code-block:: text
|
319 |
+
|
320 |
+
| __init__(...)
|
321 |
+
| __init__(self: example.Foo, arg0: ns::Bar) -> None
|
322 |
+
^^^^^^^
|
323 |
+
|
324 |
+
|
325 |
+
This limitation can be circumvented by ensuring that C++ classes are registered with pybind11
|
326 |
+
before they are used as a parameter or return type of a function:
|
327 |
+
|
328 |
+
.. code-block:: cpp
|
329 |
+
|
330 |
+
PYBIND11_MODULE(example, m) {
|
331 |
+
|
332 |
+
auto pyFoo = py::class_<ns::Foo>(m, "Foo");
|
333 |
+
auto pyBar = py::class_<ns::Bar>(m, "Bar");
|
334 |
+
|
335 |
+
pyFoo.def(py::init<const ns::Bar&>());
|
336 |
+
pyBar.def(py::init<const ns::Foo&>());
|
337 |
+
}
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/pycpp/index.rst
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Python C++ interface
|
2 |
+
####################
|
3 |
+
|
4 |
+
pybind11 exposes Python types and functions using thin C++ wrappers, which
|
5 |
+
makes it possible to conveniently call Python code from C++ without resorting
|
6 |
+
to Python's C API.
|
7 |
+
|
8 |
+
.. toctree::
|
9 |
+
:maxdepth: 2
|
10 |
+
|
11 |
+
object
|
12 |
+
numpy
|
13 |
+
utilities
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/pycpp/numpy.rst
ADDED
@@ -0,0 +1,455 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.. _numpy:
|
2 |
+
|
3 |
+
NumPy
|
4 |
+
#####
|
5 |
+
|
6 |
+
Buffer protocol
|
7 |
+
===============
|
8 |
+
|
9 |
+
Python supports an extremely general and convenient approach for exchanging
|
10 |
+
data between plugin libraries. Types can expose a buffer view [#f2]_, which
|
11 |
+
provides fast direct access to the raw internal data representation. Suppose we
|
12 |
+
want to bind the following simplistic Matrix class:
|
13 |
+
|
14 |
+
.. code-block:: cpp
|
15 |
+
|
16 |
+
class Matrix {
|
17 |
+
public:
|
18 |
+
Matrix(size_t rows, size_t cols) : m_rows(rows), m_cols(cols) {
|
19 |
+
m_data = new float[rows*cols];
|
20 |
+
}
|
21 |
+
float *data() { return m_data; }
|
22 |
+
size_t rows() const { return m_rows; }
|
23 |
+
size_t cols() const { return m_cols; }
|
24 |
+
private:
|
25 |
+
size_t m_rows, m_cols;
|
26 |
+
float *m_data;
|
27 |
+
};
|
28 |
+
|
29 |
+
The following binding code exposes the ``Matrix`` contents as a buffer object,
|
30 |
+
making it possible to cast Matrices into NumPy arrays. It is even possible to
|
31 |
+
completely avoid copy operations with Python expressions like
|
32 |
+
``np.array(matrix_instance, copy = False)``.
|
33 |
+
|
34 |
+
.. code-block:: cpp
|
35 |
+
|
36 |
+
py::class_<Matrix>(m, "Matrix", py::buffer_protocol())
|
37 |
+
.def_buffer([](Matrix &m) -> py::buffer_info {
|
38 |
+
return py::buffer_info(
|
39 |
+
m.data(), /* Pointer to buffer */
|
40 |
+
sizeof(float), /* Size of one scalar */
|
41 |
+
py::format_descriptor<float>::format(), /* Python struct-style format descriptor */
|
42 |
+
2, /* Number of dimensions */
|
43 |
+
{ m.rows(), m.cols() }, /* Buffer dimensions */
|
44 |
+
{ sizeof(float) * m.cols(), /* Strides (in bytes) for each index */
|
45 |
+
sizeof(float) }
|
46 |
+
);
|
47 |
+
});
|
48 |
+
|
49 |
+
Supporting the buffer protocol in a new type involves specifying the special
|
50 |
+
``py::buffer_protocol()`` tag in the ``py::class_`` constructor and calling the
|
51 |
+
``def_buffer()`` method with a lambda function that creates a
|
52 |
+
``py::buffer_info`` description record on demand describing a given matrix
|
53 |
+
instance. The contents of ``py::buffer_info`` mirror the Python buffer protocol
|
54 |
+
specification.
|
55 |
+
|
56 |
+
.. code-block:: cpp
|
57 |
+
|
58 |
+
struct buffer_info {
|
59 |
+
void *ptr;
|
60 |
+
py::ssize_t itemsize;
|
61 |
+
std::string format;
|
62 |
+
py::ssize_t ndim;
|
63 |
+
std::vector<py::ssize_t> shape;
|
64 |
+
std::vector<py::ssize_t> strides;
|
65 |
+
};
|
66 |
+
|
67 |
+
To create a C++ function that can take a Python buffer object as an argument,
|
68 |
+
simply use the type ``py::buffer`` as one of its arguments. Buffers can exist
|
69 |
+
in a great variety of configurations, hence some safety checks are usually
|
70 |
+
necessary in the function body. Below, you can see a basic example on how to
|
71 |
+
define a custom constructor for the Eigen double precision matrix
|
72 |
+
(``Eigen::MatrixXd``) type, which supports initialization from compatible
|
73 |
+
buffer objects (e.g. a NumPy matrix).
|
74 |
+
|
75 |
+
.. code-block:: cpp
|
76 |
+
|
77 |
+
/* Bind MatrixXd (or some other Eigen type) to Python */
|
78 |
+
typedef Eigen::MatrixXd Matrix;
|
79 |
+
|
80 |
+
typedef Matrix::Scalar Scalar;
|
81 |
+
constexpr bool rowMajor = Matrix::Flags & Eigen::RowMajorBit;
|
82 |
+
|
83 |
+
py::class_<Matrix>(m, "Matrix", py::buffer_protocol())
|
84 |
+
.def(py::init([](py::buffer b) {
|
85 |
+
typedef Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic> Strides;
|
86 |
+
|
87 |
+
/* Request a buffer descriptor from Python */
|
88 |
+
py::buffer_info info = b.request();
|
89 |
+
|
90 |
+
/* Some basic validation checks ... */
|
91 |
+
if (info.format != py::format_descriptor<Scalar>::format())
|
92 |
+
throw std::runtime_error("Incompatible format: expected a double array!");
|
93 |
+
|
94 |
+
if (info.ndim != 2)
|
95 |
+
throw std::runtime_error("Incompatible buffer dimension!");
|
96 |
+
|
97 |
+
auto strides = Strides(
|
98 |
+
info.strides[rowMajor ? 0 : 1] / (py::ssize_t)sizeof(Scalar),
|
99 |
+
info.strides[rowMajor ? 1 : 0] / (py::ssize_t)sizeof(Scalar));
|
100 |
+
|
101 |
+
auto map = Eigen::Map<Matrix, 0, Strides>(
|
102 |
+
static_cast<Scalar *>(info.ptr), info.shape[0], info.shape[1], strides);
|
103 |
+
|
104 |
+
return Matrix(map);
|
105 |
+
}));
|
106 |
+
|
107 |
+
For reference, the ``def_buffer()`` call for this Eigen data type should look
|
108 |
+
as follows:
|
109 |
+
|
110 |
+
.. code-block:: cpp
|
111 |
+
|
112 |
+
.def_buffer([](Matrix &m) -> py::buffer_info {
|
113 |
+
return py::buffer_info(
|
114 |
+
m.data(), /* Pointer to buffer */
|
115 |
+
sizeof(Scalar), /* Size of one scalar */
|
116 |
+
py::format_descriptor<Scalar>::format(), /* Python struct-style format descriptor */
|
117 |
+
2, /* Number of dimensions */
|
118 |
+
{ m.rows(), m.cols() }, /* Buffer dimensions */
|
119 |
+
{ sizeof(Scalar) * (rowMajor ? m.cols() : 1),
|
120 |
+
sizeof(Scalar) * (rowMajor ? 1 : m.rows()) }
|
121 |
+
/* Strides (in bytes) for each index */
|
122 |
+
);
|
123 |
+
})
|
124 |
+
|
125 |
+
For a much easier approach of binding Eigen types (although with some
|
126 |
+
limitations), refer to the section on :doc:`/advanced/cast/eigen`.
|
127 |
+
|
128 |
+
.. seealso::
|
129 |
+
|
130 |
+
The file :file:`tests/test_buffers.cpp` contains a complete example
|
131 |
+
that demonstrates using the buffer protocol with pybind11 in more detail.
|
132 |
+
|
133 |
+
.. [#f2] http://docs.python.org/3/c-api/buffer.html
|
134 |
+
|
135 |
+
Arrays
|
136 |
+
======
|
137 |
+
|
138 |
+
By exchanging ``py::buffer`` with ``py::array`` in the above snippet, we can
|
139 |
+
restrict the function so that it only accepts NumPy arrays (rather than any
|
140 |
+
type of Python object satisfying the buffer protocol).
|
141 |
+
|
142 |
+
In many situations, we want to define a function which only accepts a NumPy
|
143 |
+
array of a certain data type. This is possible via the ``py::array_t<T>``
|
144 |
+
template. For instance, the following function requires the argument to be a
|
145 |
+
NumPy array containing double precision values.
|
146 |
+
|
147 |
+
.. code-block:: cpp
|
148 |
+
|
149 |
+
void f(py::array_t<double> array);
|
150 |
+
|
151 |
+
When it is invoked with a different type (e.g. an integer or a list of
|
152 |
+
integers), the binding code will attempt to cast the input into a NumPy array
|
153 |
+
of the requested type. This feature requires the :file:`pybind11/numpy.h`
|
154 |
+
header to be included. Note that :file:`pybind11/numpy.h` does not depend on
|
155 |
+
the NumPy headers, and thus can be used without declaring a build-time
|
156 |
+
dependency on NumPy; NumPy>=1.7.0 is a runtime dependency.
|
157 |
+
|
158 |
+
Data in NumPy arrays is not guaranteed to packed in a dense manner;
|
159 |
+
furthermore, entries can be separated by arbitrary column and row strides.
|
160 |
+
Sometimes, it can be useful to require a function to only accept dense arrays
|
161 |
+
using either the C (row-major) or Fortran (column-major) ordering. This can be
|
162 |
+
accomplished via a second template argument with values ``py::array::c_style``
|
163 |
+
or ``py::array::f_style``.
|
164 |
+
|
165 |
+
.. code-block:: cpp
|
166 |
+
|
167 |
+
void f(py::array_t<double, py::array::c_style | py::array::forcecast> array);
|
168 |
+
|
169 |
+
The ``py::array::forcecast`` argument is the default value of the second
|
170 |
+
template parameter, and it ensures that non-conforming arguments are converted
|
171 |
+
into an array satisfying the specified requirements instead of trying the next
|
172 |
+
function overload.
|
173 |
+
|
174 |
+
There are several methods on arrays; the methods listed below under references
|
175 |
+
work, as well as the following functions based on the NumPy API:
|
176 |
+
|
177 |
+
- ``.dtype()`` returns the type of the contained values.
|
178 |
+
|
179 |
+
- ``.strides()`` returns a pointer to the strides of the array (optionally pass
|
180 |
+
an integer axis to get a number).
|
181 |
+
|
182 |
+
- ``.flags()`` returns the flag settings. ``.writable()`` and ``.owndata()``
|
183 |
+
are directly available.
|
184 |
+
|
185 |
+
- ``.offset_at()`` returns the offset (optionally pass indices).
|
186 |
+
|
187 |
+
- ``.squeeze()`` returns a view with length-1 axes removed.
|
188 |
+
|
189 |
+
- ``.view(dtype)`` returns a view of the array with a different dtype.
|
190 |
+
|
191 |
+
- ``.reshape({i, j, ...})`` returns a view of the array with a different shape.
|
192 |
+
``.resize({...})`` is also available.
|
193 |
+
|
194 |
+
- ``.index_at(i, j, ...)`` gets the count from the beginning to a given index.
|
195 |
+
|
196 |
+
|
197 |
+
There are also several methods for getting references (described below).
|
198 |
+
|
199 |
+
Structured types
|
200 |
+
================
|
201 |
+
|
202 |
+
In order for ``py::array_t`` to work with structured (record) types, we first
|
203 |
+
need to register the memory layout of the type. This can be done via
|
204 |
+
``PYBIND11_NUMPY_DTYPE`` macro, called in the plugin definition code, which
|
205 |
+
expects the type followed by field names:
|
206 |
+
|
207 |
+
.. code-block:: cpp
|
208 |
+
|
209 |
+
struct A {
|
210 |
+
int x;
|
211 |
+
double y;
|
212 |
+
};
|
213 |
+
|
214 |
+
struct B {
|
215 |
+
int z;
|
216 |
+
A a;
|
217 |
+
};
|
218 |
+
|
219 |
+
// ...
|
220 |
+
PYBIND11_MODULE(test, m) {
|
221 |
+
// ...
|
222 |
+
|
223 |
+
PYBIND11_NUMPY_DTYPE(A, x, y);
|
224 |
+
PYBIND11_NUMPY_DTYPE(B, z, a);
|
225 |
+
/* now both A and B can be used as template arguments to py::array_t */
|
226 |
+
}
|
227 |
+
|
228 |
+
The structure should consist of fundamental arithmetic types, ``std::complex``,
|
229 |
+
previously registered substructures, and arrays of any of the above. Both C++
|
230 |
+
arrays and ``std::array`` are supported. While there is a static assertion to
|
231 |
+
prevent many types of unsupported structures, it is still the user's
|
232 |
+
responsibility to use only "plain" structures that can be safely manipulated as
|
233 |
+
raw memory without violating invariants.
|
234 |
+
|
235 |
+
Vectorizing functions
|
236 |
+
=====================
|
237 |
+
|
238 |
+
Suppose we want to bind a function with the following signature to Python so
|
239 |
+
that it can process arbitrary NumPy array arguments (vectors, matrices, general
|
240 |
+
N-D arrays) in addition to its normal arguments:
|
241 |
+
|
242 |
+
.. code-block:: cpp
|
243 |
+
|
244 |
+
double my_func(int x, float y, double z);
|
245 |
+
|
246 |
+
After including the ``pybind11/numpy.h`` header, this is extremely simple:
|
247 |
+
|
248 |
+
.. code-block:: cpp
|
249 |
+
|
250 |
+
m.def("vectorized_func", py::vectorize(my_func));
|
251 |
+
|
252 |
+
Invoking the function like below causes 4 calls to be made to ``my_func`` with
|
253 |
+
each of the array elements. The significant advantage of this compared to
|
254 |
+
solutions like ``numpy.vectorize()`` is that the loop over the elements runs
|
255 |
+
entirely on the C++ side and can be crunched down into a tight, optimized loop
|
256 |
+
by the compiler. The result is returned as a NumPy array of type
|
257 |
+
``numpy.dtype.float64``.
|
258 |
+
|
259 |
+
.. code-block:: pycon
|
260 |
+
|
261 |
+
>>> x = np.array([[1, 3], [5, 7]])
|
262 |
+
>>> y = np.array([[2, 4], [6, 8]])
|
263 |
+
>>> z = 3
|
264 |
+
>>> result = vectorized_func(x, y, z)
|
265 |
+
|
266 |
+
The scalar argument ``z`` is transparently replicated 4 times. The input
|
267 |
+
arrays ``x`` and ``y`` are automatically converted into the right types (they
|
268 |
+
are of type ``numpy.dtype.int64`` but need to be ``numpy.dtype.int32`` and
|
269 |
+
``numpy.dtype.float32``, respectively).
|
270 |
+
|
271 |
+
.. note::
|
272 |
+
|
273 |
+
Only arithmetic, complex, and POD types passed by value or by ``const &``
|
274 |
+
reference are vectorized; all other arguments are passed through as-is.
|
275 |
+
Functions taking rvalue reference arguments cannot be vectorized.
|
276 |
+
|
277 |
+
In cases where the computation is too complicated to be reduced to
|
278 |
+
``vectorize``, it will be necessary to create and access the buffer contents
|
279 |
+
manually. The following snippet contains a complete example that shows how this
|
280 |
+
works (the code is somewhat contrived, since it could have been done more
|
281 |
+
simply using ``vectorize``).
|
282 |
+
|
283 |
+
.. code-block:: cpp
|
284 |
+
|
285 |
+
#include <pybind11/pybind11.h>
|
286 |
+
#include <pybind11/numpy.h>
|
287 |
+
|
288 |
+
namespace py = pybind11;
|
289 |
+
|
290 |
+
py::array_t<double> add_arrays(py::array_t<double> input1, py::array_t<double> input2) {
|
291 |
+
py::buffer_info buf1 = input1.request(), buf2 = input2.request();
|
292 |
+
|
293 |
+
if (buf1.ndim != 1 || buf2.ndim != 1)
|
294 |
+
throw std::runtime_error("Number of dimensions must be one");
|
295 |
+
|
296 |
+
if (buf1.size != buf2.size)
|
297 |
+
throw std::runtime_error("Input shapes must match");
|
298 |
+
|
299 |
+
/* No pointer is passed, so NumPy will allocate the buffer */
|
300 |
+
auto result = py::array_t<double>(buf1.size);
|
301 |
+
|
302 |
+
py::buffer_info buf3 = result.request();
|
303 |
+
|
304 |
+
double *ptr1 = static_cast<double *>(buf1.ptr);
|
305 |
+
double *ptr2 = static_cast<double *>(buf2.ptr);
|
306 |
+
double *ptr3 = static_cast<double *>(buf3.ptr);
|
307 |
+
|
308 |
+
for (size_t idx = 0; idx < buf1.shape[0]; idx++)
|
309 |
+
ptr3[idx] = ptr1[idx] + ptr2[idx];
|
310 |
+
|
311 |
+
return result;
|
312 |
+
}
|
313 |
+
|
314 |
+
PYBIND11_MODULE(test, m) {
|
315 |
+
m.def("add_arrays", &add_arrays, "Add two NumPy arrays");
|
316 |
+
}
|
317 |
+
|
318 |
+
.. seealso::
|
319 |
+
|
320 |
+
The file :file:`tests/test_numpy_vectorize.cpp` contains a complete
|
321 |
+
example that demonstrates using :func:`vectorize` in more detail.
|
322 |
+
|
323 |
+
Direct access
|
324 |
+
=============
|
325 |
+
|
326 |
+
For performance reasons, particularly when dealing with very large arrays, it
|
327 |
+
is often desirable to directly access array elements without internal checking
|
328 |
+
of dimensions and bounds on every access when indices are known to be already
|
329 |
+
valid. To avoid such checks, the ``array`` class and ``array_t<T>`` template
|
330 |
+
class offer an unchecked proxy object that can be used for this unchecked
|
331 |
+
access through the ``unchecked<N>`` and ``mutable_unchecked<N>`` methods,
|
332 |
+
where ``N`` gives the required dimensionality of the array:
|
333 |
+
|
334 |
+
.. code-block:: cpp
|
335 |
+
|
336 |
+
m.def("sum_3d", [](py::array_t<double> x) {
|
337 |
+
auto r = x.unchecked<3>(); // x must have ndim = 3; can be non-writeable
|
338 |
+
double sum = 0;
|
339 |
+
for (py::ssize_t i = 0; i < r.shape(0); i++)
|
340 |
+
for (py::ssize_t j = 0; j < r.shape(1); j++)
|
341 |
+
for (py::ssize_t k = 0; k < r.shape(2); k++)
|
342 |
+
sum += r(i, j, k);
|
343 |
+
return sum;
|
344 |
+
});
|
345 |
+
m.def("increment_3d", [](py::array_t<double> x) {
|
346 |
+
auto r = x.mutable_unchecked<3>(); // Will throw if ndim != 3 or flags.writeable is false
|
347 |
+
for (py::ssize_t i = 0; i < r.shape(0); i++)
|
348 |
+
for (py::ssize_t j = 0; j < r.shape(1); j++)
|
349 |
+
for (py::ssize_t k = 0; k < r.shape(2); k++)
|
350 |
+
r(i, j, k) += 1.0;
|
351 |
+
}, py::arg().noconvert());
|
352 |
+
|
353 |
+
To obtain the proxy from an ``array`` object, you must specify both the data
|
354 |
+
type and number of dimensions as template arguments, such as ``auto r =
|
355 |
+
myarray.mutable_unchecked<float, 2>()``.
|
356 |
+
|
357 |
+
If the number of dimensions is not known at compile time, you can omit the
|
358 |
+
dimensions template parameter (i.e. calling ``arr_t.unchecked()`` or
|
359 |
+
``arr.unchecked<T>()``. This will give you a proxy object that works in the
|
360 |
+
same way, but results in less optimizable code and thus a small efficiency
|
361 |
+
loss in tight loops.
|
362 |
+
|
363 |
+
Note that the returned proxy object directly references the array's data, and
|
364 |
+
only reads its shape, strides, and writeable flag when constructed. You must
|
365 |
+
take care to ensure that the referenced array is not destroyed or reshaped for
|
366 |
+
the duration of the returned object, typically by limiting the scope of the
|
367 |
+
returned instance.
|
368 |
+
|
369 |
+
The returned proxy object supports some of the same methods as ``py::array`` so
|
370 |
+
that it can be used as a drop-in replacement for some existing, index-checked
|
371 |
+
uses of ``py::array``:
|
372 |
+
|
373 |
+
- ``.ndim()`` returns the number of dimensions
|
374 |
+
|
375 |
+
- ``.data(1, 2, ...)`` and ``r.mutable_data(1, 2, ...)``` returns a pointer to
|
376 |
+
the ``const T`` or ``T`` data, respectively, at the given indices. The
|
377 |
+
latter is only available to proxies obtained via ``a.mutable_unchecked()``.
|
378 |
+
|
379 |
+
- ``.itemsize()`` returns the size of an item in bytes, i.e. ``sizeof(T)``.
|
380 |
+
|
381 |
+
- ``.ndim()`` returns the number of dimensions.
|
382 |
+
|
383 |
+
- ``.shape(n)`` returns the size of dimension ``n``
|
384 |
+
|
385 |
+
- ``.size()`` returns the total number of elements (i.e. the product of the shapes).
|
386 |
+
|
387 |
+
- ``.nbytes()`` returns the number of bytes used by the referenced elements
|
388 |
+
(i.e. ``itemsize()`` times ``size()``).
|
389 |
+
|
390 |
+
.. seealso::
|
391 |
+
|
392 |
+
The file :file:`tests/test_numpy_array.cpp` contains additional examples
|
393 |
+
demonstrating the use of this feature.
|
394 |
+
|
395 |
+
Ellipsis
|
396 |
+
========
|
397 |
+
|
398 |
+
Python provides a convenient ``...`` ellipsis notation that is often used to
|
399 |
+
slice multidimensional arrays. For instance, the following snippet extracts the
|
400 |
+
middle dimensions of a tensor with the first and last index set to zero.
|
401 |
+
|
402 |
+
.. code-block:: python
|
403 |
+
|
404 |
+
a = ... # a NumPy array
|
405 |
+
b = a[0, ..., 0]
|
406 |
+
|
407 |
+
The function ``py::ellipsis()`` function can be used to perform the same
|
408 |
+
operation on the C++ side:
|
409 |
+
|
410 |
+
.. code-block:: cpp
|
411 |
+
|
412 |
+
py::array a = /* A NumPy array */;
|
413 |
+
py::array b = a[py::make_tuple(0, py::ellipsis(), 0)];
|
414 |
+
|
415 |
+
|
416 |
+
Memory view
|
417 |
+
===========
|
418 |
+
|
419 |
+
For a case when we simply want to provide a direct accessor to C/C++ buffer
|
420 |
+
without a concrete class object, we can return a ``memoryview`` object. Suppose
|
421 |
+
we wish to expose a ``memoryview`` for 2x4 uint8_t array, we can do the
|
422 |
+
following:
|
423 |
+
|
424 |
+
.. code-block:: cpp
|
425 |
+
|
426 |
+
const uint8_t buffer[] = {
|
427 |
+
0, 1, 2, 3,
|
428 |
+
4, 5, 6, 7
|
429 |
+
};
|
430 |
+
m.def("get_memoryview2d", []() {
|
431 |
+
return py::memoryview::from_buffer(
|
432 |
+
buffer, // buffer pointer
|
433 |
+
{ 2, 4 }, // shape (rows, cols)
|
434 |
+
{ sizeof(uint8_t) * 4, sizeof(uint8_t) } // strides in bytes
|
435 |
+
);
|
436 |
+
})
|
437 |
+
|
438 |
+
This approach is meant for providing a ``memoryview`` for a C/C++ buffer not
|
439 |
+
managed by Python. The user is responsible for managing the lifetime of the
|
440 |
+
buffer. Using a ``memoryview`` created in this way after deleting the buffer in
|
441 |
+
C++ side results in undefined behavior.
|
442 |
+
|
443 |
+
We can also use ``memoryview::from_memory`` for a simple 1D contiguous buffer:
|
444 |
+
|
445 |
+
.. code-block:: cpp
|
446 |
+
|
447 |
+
m.def("get_memoryview1d", []() {
|
448 |
+
return py::memoryview::from_memory(
|
449 |
+
buffer, // buffer pointer
|
450 |
+
sizeof(uint8_t) * 8 // buffer size
|
451 |
+
);
|
452 |
+
})
|
453 |
+
|
454 |
+
.. versionchanged:: 2.6
|
455 |
+
``memoryview::from_memory`` added.
|
third-party/DPVO/DPViewer/pybind11/docs/advanced/pycpp/object.rst
ADDED
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Python types
|
2 |
+
############
|
3 |
+
|
4 |
+
.. _wrappers:
|
5 |
+
|
6 |
+
Available wrappers
|
7 |
+
==================
|
8 |
+
|
9 |
+
All major Python types are available as thin C++ wrapper classes. These
|
10 |
+
can also be used as function parameters -- see :ref:`python_objects_as_args`.
|
11 |
+
|
12 |
+
Available types include :class:`handle`, :class:`object`, :class:`bool_`,
|
13 |
+
:class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`,
|
14 |
+
:class:`list`, :class:`dict`, :class:`slice`, :class:`none`, :class:`capsule`,
|
15 |
+
:class:`iterable`, :class:`iterator`, :class:`function`, :class:`buffer`,
|
16 |
+
:class:`array`, and :class:`array_t`.
|
17 |
+
|
18 |
+
.. warning::
|
19 |
+
|
20 |
+
Be sure to review the :ref:`pytypes_gotchas` before using this heavily in
|
21 |
+
your C++ API.
|
22 |
+
|
23 |
+
.. _instantiating_compound_types:
|
24 |
+
|
25 |
+
Instantiating compound Python types from C++
|
26 |
+
============================================
|
27 |
+
|
28 |
+
Dictionaries can be initialized in the :class:`dict` constructor:
|
29 |
+
|
30 |
+
.. code-block:: cpp
|
31 |
+
|
32 |
+
using namespace pybind11::literals; // to bring in the `_a` literal
|
33 |
+
py::dict d("spam"_a=py::none(), "eggs"_a=42);
|
34 |
+
|
35 |
+
A tuple of python objects can be instantiated using :func:`py::make_tuple`:
|
36 |
+
|
37 |
+
.. code-block:: cpp
|
38 |
+
|
39 |
+
py::tuple tup = py::make_tuple(42, py::none(), "spam");
|
40 |
+
|
41 |
+
Each element is converted to a supported Python type.
|
42 |
+
|
43 |
+
A `simple namespace`_ can be instantiated using
|
44 |
+
|
45 |
+
.. code-block:: cpp
|
46 |
+
|
47 |
+
using namespace pybind11::literals; // to bring in the `_a` literal
|
48 |
+
py::object SimpleNamespace = py::module_::import("types").attr("SimpleNamespace");
|
49 |
+
py::object ns = SimpleNamespace("spam"_a=py::none(), "eggs"_a=42);
|
50 |
+
|
51 |
+
Attributes on a namespace can be modified with the :func:`py::delattr`,
|
52 |
+
:func:`py::getattr`, and :func:`py::setattr` functions. Simple namespaces can
|
53 |
+
be useful as lightweight stand-ins for class instances.
|
54 |
+
|
55 |
+
.. _simple namespace: https://docs.python.org/3/library/types.html#types.SimpleNamespace
|
56 |
+
|
57 |
+
.. _casting_back_and_forth:
|
58 |
+
|
59 |
+
Casting back and forth
|
60 |
+
======================
|
61 |
+
|
62 |
+
In this kind of mixed code, it is often necessary to convert arbitrary C++
|
63 |
+
types to Python, which can be done using :func:`py::cast`:
|
64 |
+
|
65 |
+
.. code-block:: cpp
|
66 |
+
|
67 |
+
MyClass *cls = ...;
|
68 |
+
py::object obj = py::cast(cls);
|
69 |
+
|
70 |
+
The reverse direction uses the following syntax:
|
71 |
+
|
72 |
+
.. code-block:: cpp
|
73 |
+
|
74 |
+
py::object obj = ...;
|
75 |
+
MyClass *cls = obj.cast<MyClass *>();
|
76 |
+
|
77 |
+
When conversion fails, both directions throw the exception :class:`cast_error`.
|
78 |
+
|
79 |
+
.. _python_libs:
|
80 |
+
|
81 |
+
Accessing Python libraries from C++
|
82 |
+
===================================
|
83 |
+
|
84 |
+
It is also possible to import objects defined in the Python standard
|
85 |
+
library or available in the current Python environment (``sys.path``) and work
|
86 |
+
with these in C++.
|
87 |
+
|
88 |
+
This example obtains a reference to the Python ``Decimal`` class.
|
89 |
+
|
90 |
+
.. code-block:: cpp
|
91 |
+
|
92 |
+
// Equivalent to "from decimal import Decimal"
|
93 |
+
py::object Decimal = py::module_::import("decimal").attr("Decimal");
|
94 |
+
|
95 |
+
.. code-block:: cpp
|
96 |
+
|
97 |
+
// Try to import scipy
|
98 |
+
py::object scipy = py::module_::import("scipy");
|
99 |
+
return scipy.attr("__version__");
|
100 |
+
|
101 |
+
|
102 |
+
.. _calling_python_functions:
|
103 |
+
|
104 |
+
Calling Python functions
|
105 |
+
========================
|
106 |
+
|
107 |
+
It is also possible to call Python classes, functions and methods
|
108 |
+
via ``operator()``.
|
109 |
+
|
110 |
+
.. code-block:: cpp
|
111 |
+
|
112 |
+
// Construct a Python object of class Decimal
|
113 |
+
py::object pi = Decimal("3.14159");
|
114 |
+
|
115 |
+
.. code-block:: cpp
|
116 |
+
|
117 |
+
// Use Python to make our directories
|
118 |
+
py::object os = py::module_::import("os");
|
119 |
+
py::object makedirs = os.attr("makedirs");
|
120 |
+
makedirs("/tmp/path/to/somewhere");
|
121 |
+
|
122 |
+
One can convert the result obtained from Python to a pure C++ version
|
123 |
+
if a ``py::class_`` or type conversion is defined.
|
124 |
+
|
125 |
+
.. code-block:: cpp
|
126 |
+
|
127 |
+
py::function f = <...>;
|
128 |
+
py::object result_py = f(1234, "hello", some_instance);
|
129 |
+
MyClass &result = result_py.cast<MyClass>();
|
130 |
+
|
131 |
+
.. _calling_python_methods:
|
132 |
+
|
133 |
+
Calling Python methods
|
134 |
+
========================
|
135 |
+
|
136 |
+
To call an object's method, one can again use ``.attr`` to obtain access to the
|
137 |
+
Python method.
|
138 |
+
|
139 |
+
.. code-block:: cpp
|
140 |
+
|
141 |
+
// Calculate e^π in decimal
|
142 |
+
py::object exp_pi = pi.attr("exp")();
|
143 |
+
py::print(py::str(exp_pi));
|
144 |
+
|
145 |
+
In the example above ``pi.attr("exp")`` is a *bound method*: it will always call
|
146 |
+
the method for that same instance of the class. Alternately one can create an
|
147 |
+
*unbound method* via the Python class (instead of instance) and pass the ``self``
|
148 |
+
object explicitly, followed by other arguments.
|
149 |
+
|
150 |
+
.. code-block:: cpp
|
151 |
+
|
152 |
+
py::object decimal_exp = Decimal.attr("exp");
|
153 |
+
|
154 |
+
// Compute the e^n for n=0..4
|
155 |
+
for (int n = 0; n < 5; n++) {
|
156 |
+
py::print(decimal_exp(Decimal(n));
|
157 |
+
}
|
158 |
+
|
159 |
+
Keyword arguments
|
160 |
+
=================
|
161 |
+
|
162 |
+
Keyword arguments are also supported. In Python, there is the usual call syntax:
|
163 |
+
|
164 |
+
.. code-block:: python
|
165 |
+
|
166 |
+
def f(number, say, to):
|
167 |
+
... # function code
|
168 |
+
|
169 |
+
|
170 |
+
f(1234, say="hello", to=some_instance) # keyword call in Python
|
171 |
+
|
172 |
+
In C++, the same call can be made using:
|
173 |
+
|
174 |
+
.. code-block:: cpp
|
175 |
+
|
176 |
+
using namespace pybind11::literals; // to bring in the `_a` literal
|
177 |
+
f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
|
178 |
+
|
179 |
+
Unpacking arguments
|
180 |
+
===================
|
181 |
+
|
182 |
+
Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with
|
183 |
+
other arguments:
|
184 |
+
|
185 |
+
.. code-block:: cpp
|
186 |
+
|
187 |
+
// * unpacking
|
188 |
+
py::tuple args = py::make_tuple(1234, "hello", some_instance);
|
189 |
+
f(*args);
|
190 |
+
|
191 |
+
// ** unpacking
|
192 |
+
py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance);
|
193 |
+
f(**kwargs);
|
194 |
+
|
195 |
+
// mixed keywords, * and ** unpacking
|
196 |
+
py::tuple args = py::make_tuple(1234);
|
197 |
+
py::dict kwargs = py::dict("to"_a=some_instance);
|
198 |
+
f(*args, "say"_a="hello", **kwargs);
|
199 |
+
|
200 |
+
Generalized unpacking according to PEP448_ is also supported:
|
201 |
+
|
202 |
+
.. code-block:: cpp
|
203 |
+
|
204 |
+
py::dict kwargs1 = py::dict("number"_a=1234);
|
205 |
+
py::dict kwargs2 = py::dict("to"_a=some_instance);
|
206 |
+
f(**kwargs1, "say"_a="hello", **kwargs2);
|
207 |
+
|
208 |
+
.. seealso::
|
209 |
+
|
210 |
+
The file :file:`tests/test_pytypes.cpp` contains a complete
|
211 |
+
example that demonstrates passing native Python types in more detail. The
|
212 |
+
file :file:`tests/test_callbacks.cpp` presents a few examples of calling
|
213 |
+
Python functions from C++, including keywords arguments and unpacking.
|
214 |
+
|
215 |
+
.. _PEP448: https://www.python.org/dev/peps/pep-0448/
|
216 |
+
|
217 |
+
.. _implicit_casting:
|
218 |
+
|
219 |
+
Implicit casting
|
220 |
+
================
|
221 |
+
|
222 |
+
When using the C++ interface for Python types, or calling Python functions,
|
223 |
+
objects of type :class:`object` are returned. It is possible to invoke implicit
|
224 |
+
conversions to subclasses like :class:`dict`. The same holds for the proxy objects
|
225 |
+
returned by ``operator[]`` or ``obj.attr()``.
|
226 |
+
Casting to subtypes improves code readability and allows values to be passed to
|
227 |
+
C++ functions that require a specific subtype rather than a generic :class:`object`.
|
228 |
+
|
229 |
+
.. code-block:: cpp
|
230 |
+
|
231 |
+
#include <pybind11/numpy.h>
|
232 |
+
using namespace pybind11::literals;
|
233 |
+
|
234 |
+
py::module_ os = py::module_::import("os");
|
235 |
+
py::module_ path = py::module_::import("os.path"); // like 'import os.path as path'
|
236 |
+
py::module_ np = py::module_::import("numpy"); // like 'import numpy as np'
|
237 |
+
|
238 |
+
py::str curdir_abs = path.attr("abspath")(path.attr("curdir"));
|
239 |
+
py::print(py::str("Current directory: ") + curdir_abs);
|
240 |
+
py::dict environ = os.attr("environ");
|
241 |
+
py::print(environ["HOME"]);
|
242 |
+
py::array_t<float> arr = np.attr("ones")(3, "dtype"_a="float32");
|
243 |
+
py::print(py::repr(arr + py::int_(1)));
|
244 |
+
|
245 |
+
These implicit conversions are available for subclasses of :class:`object`; there
|
246 |
+
is no need to call ``obj.cast()`` explicitly as for custom classes, see
|
247 |
+
:ref:`casting_back_and_forth`.
|
248 |
+
|
249 |
+
.. note::
|
250 |
+
If a trivial conversion via move constructor is not possible, both implicit and
|
251 |
+
explicit casting (calling ``obj.cast()``) will attempt a "rich" conversion.
|
252 |
+
For instance, ``py::list env = os.attr("environ");`` will succeed and is
|
253 |
+
equivalent to the Python code ``env = list(os.environ)`` that produces a
|
254 |
+
list of the dict keys.
|
255 |
+
|
256 |
+
.. TODO: Adapt text once PR #2349 has landed
|
257 |
+
|
258 |
+
Handling exceptions
|
259 |
+
===================
|
260 |
+
|
261 |
+
Python exceptions from wrapper classes will be thrown as a ``py::error_already_set``.
|
262 |
+
See :ref:`Handling exceptions from Python in C++
|
263 |
+
<handling_python_exceptions_cpp>` for more information on handling exceptions
|
264 |
+
raised when calling C++ wrapper classes.
|
265 |
+
|
266 |
+
.. _pytypes_gotchas:
|
267 |
+
|
268 |
+
Gotchas
|
269 |
+
=======
|
270 |
+
|
271 |
+
Default-Constructed Wrappers
|
272 |
+
----------------------------
|
273 |
+
|
274 |
+
When a wrapper type is default-constructed, it is **not** a valid Python object (i.e. it is not ``py::none()``). It is simply the same as
|
275 |
+
``PyObject*`` null pointer. To check for this, use
|
276 |
+
``static_cast<bool>(my_wrapper)``.
|
277 |
+
|
278 |
+
Assigning py::none() to wrappers
|
279 |
+
--------------------------------
|
280 |
+
|
281 |
+
You may be tempted to use types like ``py::str`` and ``py::dict`` in C++
|
282 |
+
signatures (either pure C++, or in bound signatures), and assign them default
|
283 |
+
values of ``py::none()``. However, in a best case scenario, it will fail fast
|
284 |
+
because ``None`` is not convertible to that type (e.g. ``py::dict``), or in a
|
285 |
+
worse case scenario, it will silently work but corrupt the types you want to
|
286 |
+
work with (e.g. ``py::str(py::none())`` will yield ``"None"`` in Python).
|
third-party/DPVO/DPViewer/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/DPViewer/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/DPViewer/pybind11/docs/basics.rst
ADDED
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 2017** and newer are supported.
|
36 |
+
|
37 |
+
.. Note::
|
38 |
+
|
39 |
+
To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag
|
40 |
+
``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When
|
41 |
+
building with Visual Studio 2019, this is not strictly necessary, but still advised.
|
42 |
+
|
43 |
+
.. _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017
|
44 |
+
|
45 |
+
To compile and run the tests:
|
46 |
+
|
47 |
+
.. code-block:: batch
|
48 |
+
|
49 |
+
mkdir build
|
50 |
+
cd build
|
51 |
+
cmake ..
|
52 |
+
cmake --build . --config Release --target check
|
53 |
+
|
54 |
+
This will create a Visual Studio project, compile and run the target, all from the
|
55 |
+
command line.
|
56 |
+
|
57 |
+
.. Note::
|
58 |
+
|
59 |
+
If all tests fail, make sure that the Python binary and the testcases are compiled
|
60 |
+
for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
|
61 |
+
can specify **x86_64** as the target architecture for the generated Visual Studio
|
62 |
+
project using ``cmake -A x64 ..``.
|
63 |
+
|
64 |
+
.. seealso::
|
65 |
+
|
66 |
+
Advanced users who are already familiar with Boost.Python may want to skip
|
67 |
+
the tutorial and look at the test cases in the :file:`tests` directory,
|
68 |
+
which exercise all features of pybind11.
|
69 |
+
|
70 |
+
Header and namespace conventions
|
71 |
+
================================
|
72 |
+
|
73 |
+
For brevity, all code examples assume that the following two lines are present:
|
74 |
+
|
75 |
+
.. code-block:: cpp
|
76 |
+
|
77 |
+
#include <pybind11/pybind11.h>
|
78 |
+
|
79 |
+
namespace py = pybind11;
|
80 |
+
|
81 |
+
Some features may require additional headers, but those will be specified as needed.
|
82 |
+
|
83 |
+
.. _simple_example:
|
84 |
+
|
85 |
+
Creating bindings for a simple function
|
86 |
+
=======================================
|
87 |
+
|
88 |
+
Let's start by creating Python bindings for an extremely simple function, which
|
89 |
+
adds two numbers and returns their result:
|
90 |
+
|
91 |
+
.. code-block:: cpp
|
92 |
+
|
93 |
+
int add(int i, int j) {
|
94 |
+
return i + j;
|
95 |
+
}
|
96 |
+
|
97 |
+
For simplicity [#f1]_, we'll put both this function and the binding code into
|
98 |
+
a file named :file:`example.cpp` with the following contents:
|
99 |
+
|
100 |
+
.. code-block:: cpp
|
101 |
+
|
102 |
+
#include <pybind11/pybind11.h>
|
103 |
+
|
104 |
+
int add(int i, int j) {
|
105 |
+
return i + j;
|
106 |
+
}
|
107 |
+
|
108 |
+
PYBIND11_MODULE(example, m) {
|
109 |
+
m.doc() = "pybind11 example plugin"; // optional module docstring
|
110 |
+
|
111 |
+
m.def("add", &add, "A function that adds two numbers");
|
112 |
+
}
|
113 |
+
|
114 |
+
.. [#f1] In practice, implementation and binding code will generally be located
|
115 |
+
in separate files.
|
116 |
+
|
117 |
+
The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
|
118 |
+
``import`` statement is issued from within Python. The module name (``example``)
|
119 |
+
is given as the first macro argument (it should not be in quotes). The second
|
120 |
+
argument (``m``) defines a variable of type :class:`py::module_ <module>` which
|
121 |
+
is the main interface for creating bindings. The method :func:`module_::def`
|
122 |
+
generates binding code that exposes the ``add()`` function to Python.
|
123 |
+
|
124 |
+
.. note::
|
125 |
+
|
126 |
+
Notice how little code was needed to expose our function to Python: all
|
127 |
+
details regarding the function's parameters and return value were
|
128 |
+
automatically inferred using template metaprogramming. This overall
|
129 |
+
approach and the used syntax are borrowed from Boost.Python, though the
|
130 |
+
underlying implementation is very different.
|
131 |
+
|
132 |
+
pybind11 is a header-only library, hence it is not necessary to link against
|
133 |
+
any special libraries and there are no intermediate (magic) translation steps.
|
134 |
+
On Linux, the above example can be compiled using the following command:
|
135 |
+
|
136 |
+
.. code-block:: bash
|
137 |
+
|
138 |
+
$ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
|
139 |
+
|
140 |
+
.. note::
|
141 |
+
|
142 |
+
If you used :ref:`include_as_a_submodule` to get the pybind11 source, then
|
143 |
+
use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of
|
144 |
+
``$(python3 -m pybind11 --includes)`` in the above compilation, as
|
145 |
+
explained in :ref:`building_manually`.
|
146 |
+
|
147 |
+
For more details on the required compiler flags on Linux and macOS, see
|
148 |
+
:ref:`building_manually`. For complete cross-platform compilation instructions,
|
149 |
+
refer to the :ref:`compiling` page.
|
150 |
+
|
151 |
+
The `python_example`_ and `cmake_example`_ repositories are also a good place
|
152 |
+
to start. They are both complete project examples with cross-platform build
|
153 |
+
systems. The only difference between the two is that `python_example`_ uses
|
154 |
+
Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
|
155 |
+
(which may be preferable for existing C++ projects).
|
156 |
+
|
157 |
+
.. _python_example: https://github.com/pybind/python_example
|
158 |
+
.. _cmake_example: https://github.com/pybind/cmake_example
|
159 |
+
|
160 |
+
Building the above C++ code will produce a binary module file that can be
|
161 |
+
imported to Python. Assuming that the compiled module is located in the
|
162 |
+
current directory, the following interactive Python session shows how to
|
163 |
+
load and execute the example:
|
164 |
+
|
165 |
+
.. code-block:: pycon
|
166 |
+
|
167 |
+
$ python
|
168 |
+
Python 3.9.10 (main, Jan 15 2022, 11:48:04)
|
169 |
+
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
|
170 |
+
Type "help", "copyright", "credits" or "license" for more information.
|
171 |
+
>>> import example
|
172 |
+
>>> example.add(1, 2)
|
173 |
+
3
|
174 |
+
>>>
|
175 |
+
|
176 |
+
.. _keyword_args:
|
177 |
+
|
178 |
+
Keyword arguments
|
179 |
+
=================
|
180 |
+
|
181 |
+
With a simple code modification, it is possible to inform Python about the
|
182 |
+
names of the arguments ("i" and "j" in this case).
|
183 |
+
|
184 |
+
.. code-block:: cpp
|
185 |
+
|
186 |
+
m.def("add", &add, "A function which adds two numbers",
|
187 |
+
py::arg("i"), py::arg("j"));
|
188 |
+
|
189 |
+
:class:`arg` is one of several special tag classes which can be used to pass
|
190 |
+
metadata into :func:`module_::def`. With this modified binding code, we can now
|
191 |
+
call the function using keyword arguments, which is a more readable alternative
|
192 |
+
particularly for functions taking many parameters:
|
193 |
+
|
194 |
+
.. code-block:: pycon
|
195 |
+
|
196 |
+
>>> import example
|
197 |
+
>>> example.add(i=1, j=2)
|
198 |
+
3L
|
199 |
+
|
200 |
+
The keyword names also appear in the function signatures within the documentation.
|
201 |
+
|
202 |
+
.. code-block:: pycon
|
203 |
+
|
204 |
+
>>> help(example)
|
205 |
+
|
206 |
+
....
|
207 |
+
|
208 |
+
FUNCTIONS
|
209 |
+
add(...)
|
210 |
+
Signature : (i: int, j: int) -> int
|
211 |
+
|
212 |
+
A function which adds two numbers
|
213 |
+
|
214 |
+
A shorter notation for named arguments is also available:
|
215 |
+
|
216 |
+
.. code-block:: cpp
|
217 |
+
|
218 |
+
// regular notation
|
219 |
+
m.def("add1", &add, py::arg("i"), py::arg("j"));
|
220 |
+
// shorthand
|
221 |
+
using namespace pybind11::literals;
|
222 |
+
m.def("add2", &add, "i"_a, "j"_a);
|
223 |
+
|
224 |
+
The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
|
225 |
+
Note that the literal operator must first be made visible with the directive
|
226 |
+
``using namespace pybind11::literals``. This does not bring in anything else
|
227 |
+
from the ``pybind11`` namespace except for literals.
|
228 |
+
|
229 |
+
.. _default_args:
|
230 |
+
|
231 |
+
Default arguments
|
232 |
+
=================
|
233 |
+
|
234 |
+
Suppose now that the function to be bound has default arguments, e.g.:
|
235 |
+
|
236 |
+
.. code-block:: cpp
|
237 |
+
|
238 |
+
int add(int i = 1, int j = 2) {
|
239 |
+
return i + j;
|
240 |
+
}
|
241 |
+
|
242 |
+
Unfortunately, pybind11 cannot automatically extract these parameters, since they
|
243 |
+
are not part of the function's type information. However, they are simple to specify
|
244 |
+
using an extension of :class:`arg`:
|
245 |
+
|
246 |
+
.. code-block:: cpp
|
247 |
+
|
248 |
+
m.def("add", &add, "A function which adds two numbers",
|
249 |
+
py::arg("i") = 1, py::arg("j") = 2);
|
250 |
+
|
251 |
+
The default values also appear within the documentation.
|
252 |
+
|
253 |
+
.. code-block:: pycon
|
254 |
+
|
255 |
+
>>> help(example)
|
256 |
+
|
257 |
+
....
|
258 |
+
|
259 |
+
FUNCTIONS
|
260 |
+
add(...)
|
261 |
+
Signature : (i: int = 1, j: int = 2) -> int
|
262 |
+
|
263 |
+
A function which adds two numbers
|
264 |
+
|
265 |
+
The shorthand notation is also available for default arguments:
|
266 |
+
|
267 |
+
.. code-block:: cpp
|
268 |
+
|
269 |
+
// regular notation
|
270 |
+
m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
|
271 |
+
// shorthand
|
272 |
+
m.def("add2", &add, "i"_a=1, "j"_a=2);
|
273 |
+
|
274 |
+
Exporting variables
|
275 |
+
===================
|
276 |
+
|
277 |
+
To expose a value from C++, use the ``attr`` function to register it in a
|
278 |
+
module as shown below. Built-in types and general objects (more on that later)
|
279 |
+
are automatically converted when assigned as attributes, and can be explicitly
|
280 |
+
converted using the function ``py::cast``.
|
281 |
+
|
282 |
+
.. code-block:: cpp
|
283 |
+
|
284 |
+
PYBIND11_MODULE(example, m) {
|
285 |
+
m.attr("the_answer") = 42;
|
286 |
+
py::object world = py::cast("World");
|
287 |
+
m.attr("what") = world;
|
288 |
+
}
|
289 |
+
|
290 |
+
These are then accessible from Python:
|
291 |
+
|
292 |
+
.. code-block:: pycon
|
293 |
+
|
294 |
+
>>> import example
|
295 |
+
>>> example.the_answer
|
296 |
+
42
|
297 |
+
>>> example.what
|
298 |
+
'World'
|
299 |
+
|
300 |
+
.. _supported_types:
|
301 |
+
|
302 |
+
Supported data types
|
303 |
+
====================
|
304 |
+
|
305 |
+
A large number of data types are supported out of the box and can be used
|
306 |
+
seamlessly as functions arguments, return values or with ``py::cast`` in general.
|
307 |
+
For a full overview, see the :doc:`advanced/cast/index` section.
|
third-party/DPVO/DPViewer/pybind11/docs/benchmark.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime as dt
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
|
5 |
+
nfns = 4 # Functions per class
|
6 |
+
nargs = 4 # Arguments per function
|
7 |
+
|
8 |
+
|
9 |
+
def generate_dummy_code_pybind11(nclasses=10):
|
10 |
+
decl = ""
|
11 |
+
bindings = ""
|
12 |
+
|
13 |
+
for cl in range(nclasses):
|
14 |
+
decl += f"class cl{cl:03};\n"
|
15 |
+
decl += "\n"
|
16 |
+
|
17 |
+
for cl in range(nclasses):
|
18 |
+
decl += f"class {cl:03} {{\n"
|
19 |
+
decl += "public:\n"
|
20 |
+
bindings += f' py::class_<cl{cl:03}>(m, "cl{cl:03}")\n'
|
21 |
+
for fn in range(nfns):
|
22 |
+
ret = random.randint(0, nclasses - 1)
|
23 |
+
params = [random.randint(0, nclasses - 1) for i in range(nargs)]
|
24 |
+
decl += f" cl{ret:03} *fn_{fn:03}("
|
25 |
+
decl += ", ".join(f"cl{p:03} *" for p in params)
|
26 |
+
decl += ");\n"
|
27 |
+
bindings += f' .def("fn_{fn:03}", &cl{cl:03}::fn_{fn:03})\n'
|
28 |
+
decl += "};\n\n"
|
29 |
+
bindings += " ;\n"
|
30 |
+
|
31 |
+
result = "#include <pybind11/pybind11.h>\n\n"
|
32 |
+
result += "namespace py = pybind11;\n\n"
|
33 |
+
result += decl + "\n"
|
34 |
+
result += "PYBIND11_MODULE(example, m) {\n"
|
35 |
+
result += bindings
|
36 |
+
result += "}"
|
37 |
+
return result
|
38 |
+
|
39 |
+
|
40 |
+
def generate_dummy_code_boost(nclasses=10):
|
41 |
+
decl = ""
|
42 |
+
bindings = ""
|
43 |
+
|
44 |
+
for cl in range(nclasses):
|
45 |
+
decl += f"class cl{cl:03};\n"
|
46 |
+
decl += "\n"
|
47 |
+
|
48 |
+
for cl in range(nclasses):
|
49 |
+
decl += "class cl%03i {\n" % cl
|
50 |
+
decl += "public:\n"
|
51 |
+
bindings += f' py::class_<cl{cl:03}>("cl{cl:03}")\n'
|
52 |
+
for fn in range(nfns):
|
53 |
+
ret = random.randint(0, nclasses - 1)
|
54 |
+
params = [random.randint(0, nclasses - 1) for i in range(nargs)]
|
55 |
+
decl += f" cl{ret:03} *fn_{fn:03}("
|
56 |
+
decl += ", ".join(f"cl{p:03} *" for p in params)
|
57 |
+
decl += ");\n"
|
58 |
+
bindings += f' .def("fn_{fn:03}", &cl{cl:03}::fn_{fn:03}, py::return_value_policy<py::manage_new_object>())\n'
|
59 |
+
decl += "};\n\n"
|
60 |
+
bindings += " ;\n"
|
61 |
+
|
62 |
+
result = "#include <boost/python.hpp>\n\n"
|
63 |
+
result += "namespace py = boost::python;\n\n"
|
64 |
+
result += decl + "\n"
|
65 |
+
result += "BOOST_PYTHON_MODULE(example) {\n"
|
66 |
+
result += bindings
|
67 |
+
result += "}"
|
68 |
+
return result
|
69 |
+
|
70 |
+
|
71 |
+
for codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]:
|
72 |
+
print("{")
|
73 |
+
for i in range(0, 10):
|
74 |
+
nclasses = 2**i
|
75 |
+
with open("test.cpp", "w") as f:
|
76 |
+
f.write(codegen(nclasses))
|
77 |
+
n1 = dt.datetime.now()
|
78 |
+
os.system(
|
79 |
+
"g++ -Os -shared -rdynamic -undefined dynamic_lookup "
|
80 |
+
"-fvisibility=hidden -std=c++14 test.cpp -I include "
|
81 |
+
"-I /System/Library/Frameworks/Python.framework/Headers -o test.so"
|
82 |
+
)
|
83 |
+
n2 = dt.datetime.now()
|
84 |
+
elapsed = (n2 - n1).total_seconds()
|
85 |
+
size = os.stat("test.so").st_size
|
86 |
+
print(" {%i, %f, %i}," % (nclasses * nfns, elapsed, size))
|
87 |
+
print("}")
|
third-party/DPVO/DPViewer/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/DPViewer/pybind11/docs/changelog.rst
ADDED
The diff for this file is too large to render.
See raw diff
|
|
third-party/DPVO/DPViewer/pybind11/docs/classes.rst
ADDED
@@ -0,0 +1,541 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
'Molly'
|
52 |
+
>>> p.setName("Charly")
|
53 |
+
>>> p.getName()
|
54 |
+
'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 |
+
'Molly'
|
128 |
+
>>> p.name = "Charly"
|
129 |
+
>>> p.name
|
130 |
+
'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 |
+
'Molly'
|
286 |
+
>>> p.bark()
|
287 |
+
'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 |
+
'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 |
+
|
439 |
+
.. note::
|
440 |
+
|
441 |
+
To define multiple overloaded constructors, simply declare one after the
|
442 |
+
other using the ``.def(py::init<...>())`` syntax. The existing machinery
|
443 |
+
for specifying keyword and default arguments also works.
|
444 |
+
|
445 |
+
Enumerations and internal types
|
446 |
+
===============================
|
447 |
+
|
448 |
+
Let's now suppose that the example class contains internal types like enumerations, e.g.:
|
449 |
+
|
450 |
+
.. code-block:: cpp
|
451 |
+
|
452 |
+
struct Pet {
|
453 |
+
enum Kind {
|
454 |
+
Dog = 0,
|
455 |
+
Cat
|
456 |
+
};
|
457 |
+
|
458 |
+
struct Attributes {
|
459 |
+
float age = 0;
|
460 |
+
};
|
461 |
+
|
462 |
+
Pet(const std::string &name, Kind type) : name(name), type(type) { }
|
463 |
+
|
464 |
+
std::string name;
|
465 |
+
Kind type;
|
466 |
+
Attributes attr;
|
467 |
+
};
|
468 |
+
|
469 |
+
The binding code for this example looks as follows:
|
470 |
+
|
471 |
+
.. code-block:: cpp
|
472 |
+
|
473 |
+
py::class_<Pet> pet(m, "Pet");
|
474 |
+
|
475 |
+
pet.def(py::init<const std::string &, Pet::Kind>())
|
476 |
+
.def_readwrite("name", &Pet::name)
|
477 |
+
.def_readwrite("type", &Pet::type)
|
478 |
+
.def_readwrite("attr", &Pet::attr);
|
479 |
+
|
480 |
+
py::enum_<Pet::Kind>(pet, "Kind")
|
481 |
+
.value("Dog", Pet::Kind::Dog)
|
482 |
+
.value("Cat", Pet::Kind::Cat)
|
483 |
+
.export_values();
|
484 |
+
|
485 |
+
py::class_<Pet::Attributes> attributes(pet, "Attributes")
|
486 |
+
.def(py::init<>())
|
487 |
+
.def_readwrite("age", &Pet::Attributes::age);
|
488 |
+
|
489 |
+
|
490 |
+
To ensure that the nested types ``Kind`` and ``Attributes`` are created within the scope of ``Pet``, the
|
491 |
+
``pet`` :class:`class_` instance must be supplied to the :class:`enum_` and :class:`class_`
|
492 |
+
constructor. The :func:`enum_::export_values` function exports the enum entries
|
493 |
+
into the parent scope, which should be skipped for newer C++11-style strongly
|
494 |
+
typed enums.
|
495 |
+
|
496 |
+
.. code-block:: pycon
|
497 |
+
|
498 |
+
>>> p = Pet("Lucy", Pet.Cat)
|
499 |
+
>>> p.type
|
500 |
+
Kind.Cat
|
501 |
+
>>> int(p.type)
|
502 |
+
1L
|
503 |
+
|
504 |
+
The entries defined by the enumeration type are exposed in the ``__members__`` property:
|
505 |
+
|
506 |
+
.. code-block:: pycon
|
507 |
+
|
508 |
+
>>> Pet.Kind.__members__
|
509 |
+
{'Dog': Kind.Dog, 'Cat': Kind.Cat}
|
510 |
+
|
511 |
+
The ``name`` property returns the name of the enum value as a unicode string.
|
512 |
+
|
513 |
+
.. note::
|
514 |
+
|
515 |
+
It is also possible to use ``str(enum)``, however these accomplish different
|
516 |
+
goals. The following shows how these two approaches differ.
|
517 |
+
|
518 |
+
.. code-block:: pycon
|
519 |
+
|
520 |
+
>>> p = Pet("Lucy", Pet.Cat)
|
521 |
+
>>> pet_type = p.type
|
522 |
+
>>> pet_type
|
523 |
+
Pet.Cat
|
524 |
+
>>> str(pet_type)
|
525 |
+
'Pet.Cat'
|
526 |
+
>>> pet_type.name
|
527 |
+
'Cat'
|
528 |
+
|
529 |
+
.. note::
|
530 |
+
|
531 |
+
When the special tag ``py::arithmetic()`` is specified to the ``enum_``
|
532 |
+
constructor, pybind11 creates an enumeration that also supports rudimentary
|
533 |
+
arithmetic and bit-level operations like comparisons, and, or, xor, negation,
|
534 |
+
etc.
|
535 |
+
|
536 |
+
.. code-block:: cpp
|
537 |
+
|
538 |
+
py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
|
539 |
+
...
|
540 |
+
|
541 |
+
By default, these are omitted to conserve space.
|
third-party/DPVO/DPViewer/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/DPViewer/pybind11/docs/compiling.rst
ADDED
@@ -0,0 +1,638 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.22)
|
421 |
+
project(example LANGUAGES CXX)
|
422 |
+
|
423 |
+
find_package(Python 3.6 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 FindPython to multi-target Python versions, use the individual
|
437 |
+
targets listed below, and avoid targets that directly include Python parts.
|
438 |
+
|
439 |
+
There are `many ways to hint or force a discovery of a specific Python
|
440 |
+
installation <https://cmake.org/cmake/help/latest/module/FindPython.html>`_),
|
441 |
+
setting ``Python_ROOT_DIR`` may be the most common one (though with
|
442 |
+
virtualenv/venv support, and Conda support, this tends to find the correct
|
443 |
+
Python version more often than the old system did).
|
444 |
+
|
445 |
+
.. warning::
|
446 |
+
|
447 |
+
When the Python libraries (i.e. ``libpythonXX.a`` and ``libpythonXX.so``
|
448 |
+
on Unix) are not available, as is the case on a manylinux image, the
|
449 |
+
``Development`` component will not be resolved by ``FindPython``. When not
|
450 |
+
using the embedding functionality, CMake 3.18+ allows you to specify
|
451 |
+
``Development.Module`` instead of ``Development`` to resolve this issue.
|
452 |
+
|
453 |
+
.. versionadded:: 2.6
|
454 |
+
|
455 |
+
Advanced: interface library targets
|
456 |
+
-----------------------------------
|
457 |
+
|
458 |
+
Pybind11 supports modern CMake usage patterns with a set of interface targets,
|
459 |
+
available in all modes. The targets provided are:
|
460 |
+
|
461 |
+
``pybind11::headers``
|
462 |
+
Just the pybind11 headers and minimum compile requirements
|
463 |
+
|
464 |
+
``pybind11::pybind11``
|
465 |
+
Python headers + ``pybind11::headers``
|
466 |
+
|
467 |
+
``pybind11::python_link_helper``
|
468 |
+
Just the "linking" part of pybind11:module
|
469 |
+
|
470 |
+
``pybind11::module``
|
471 |
+
Everything for extension modules - ``pybind11::pybind11`` + ``Python::Module`` (FindPython CMake 3.15+) or ``pybind11::python_link_helper``
|
472 |
+
|
473 |
+
``pybind11::embed``
|
474 |
+
Everything for embedding the Python interpreter - ``pybind11::pybind11`` + ``Python::Python`` (FindPython) or Python libs
|
475 |
+
|
476 |
+
``pybind11::lto`` / ``pybind11::thin_lto``
|
477 |
+
An alternative to `INTERPROCEDURAL_OPTIMIZATION` for adding link-time optimization.
|
478 |
+
|
479 |
+
``pybind11::windows_extras``
|
480 |
+
``/bigobj`` and ``/mp`` for MSVC.
|
481 |
+
|
482 |
+
``pybind11::opt_size``
|
483 |
+
``/Os`` for MSVC, ``-Os`` for other compilers. Does nothing for debug builds.
|
484 |
+
|
485 |
+
Two helper functions are also provided:
|
486 |
+
|
487 |
+
``pybind11_strip(target)``
|
488 |
+
Strips a target (uses ``CMAKE_STRIP`` after the target is built)
|
489 |
+
|
490 |
+
``pybind11_extension(target)``
|
491 |
+
Sets the correct extension (with SOABI) for a target.
|
492 |
+
|
493 |
+
You can use these targets to build complex applications. For example, the
|
494 |
+
``add_python_module`` function is identical to:
|
495 |
+
|
496 |
+
.. code-block:: cmake
|
497 |
+
|
498 |
+
cmake_minimum_required(VERSION 3.4)
|
499 |
+
project(example LANGUAGES CXX)
|
500 |
+
|
501 |
+
find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
|
502 |
+
|
503 |
+
add_library(example MODULE main.cpp)
|
504 |
+
|
505 |
+
target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras)
|
506 |
+
|
507 |
+
pybind11_extension(example)
|
508 |
+
if(NOT MSVC AND NOT ${CMAKE_BUILD_TYPE} MATCHES Debug|RelWithDebInfo)
|
509 |
+
# Strip unnecessary sections of the binary on Linux/macOS
|
510 |
+
pybind11_strip(example)
|
511 |
+
endif()
|
512 |
+
|
513 |
+
set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden"
|
514 |
+
CUDA_VISIBILITY_PRESET "hidden")
|
515 |
+
|
516 |
+
Instead of setting properties, you can set ``CMAKE_*`` variables to initialize these correctly.
|
517 |
+
|
518 |
+
.. warning::
|
519 |
+
|
520 |
+
Since pybind11 is a metatemplate library, it is crucial that certain
|
521 |
+
compiler flags are provided to ensure high quality code generation. In
|
522 |
+
contrast to the ``pybind11_add_module()`` command, the CMake interface
|
523 |
+
provides a *composable* set of targets to ensure that you retain flexibility.
|
524 |
+
It can be especially important to provide or set these properties; the
|
525 |
+
:ref:`FAQ <faq:symhidden>` contains an explanation on why these are needed.
|
526 |
+
|
527 |
+
.. versionadded:: 2.6
|
528 |
+
|
529 |
+
.. _nopython-mode:
|
530 |
+
|
531 |
+
Advanced: NOPYTHON mode
|
532 |
+
-----------------------
|
533 |
+
|
534 |
+
If you want complete control, you can set ``PYBIND11_NOPYTHON`` to completely
|
535 |
+
disable Python integration (this also happens if you run ``FindPython2`` and
|
536 |
+
``FindPython3`` without running ``FindPython``). This gives you complete
|
537 |
+
freedom to integrate into an existing system (like `Scikit-Build's
|
538 |
+
<https://scikit-build.readthedocs.io>`_ ``PythonExtensions``).
|
539 |
+
``pybind11_add_module`` and ``pybind11_extension`` will be unavailable, and the
|
540 |
+
targets will be missing any Python specific behavior.
|
541 |
+
|
542 |
+
.. versionadded:: 2.6
|
543 |
+
|
544 |
+
Embedding the Python interpreter
|
545 |
+
--------------------------------
|
546 |
+
|
547 |
+
In addition to extension modules, pybind11 also supports embedding Python into
|
548 |
+
a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
|
549 |
+
target. It provides everything needed to get the interpreter running. The Python
|
550 |
+
headers and libraries are attached to the target. Unlike ``pybind11::module``,
|
551 |
+
there is no need to manually set any additional properties here. For more
|
552 |
+
information about usage in C++, see :doc:`/advanced/embedding`.
|
553 |
+
|
554 |
+
.. code-block:: cmake
|
555 |
+
|
556 |
+
cmake_minimum_required(VERSION 3.4...3.18)
|
557 |
+
project(example LANGUAGES CXX)
|
558 |
+
|
559 |
+
find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
|
560 |
+
|
561 |
+
add_executable(example main.cpp)
|
562 |
+
target_link_libraries(example PRIVATE pybind11::embed)
|
563 |
+
|
564 |
+
.. _building_manually:
|
565 |
+
|
566 |
+
Building manually
|
567 |
+
=================
|
568 |
+
|
569 |
+
pybind11 is a header-only library, hence it is not necessary to link against
|
570 |
+
any special libraries and there are no intermediate (magic) translation steps.
|
571 |
+
|
572 |
+
On Linux, you can compile an example such as the one given in
|
573 |
+
:ref:`simple_example` using the following command:
|
574 |
+
|
575 |
+
.. code-block:: bash
|
576 |
+
|
577 |
+
$ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
|
578 |
+
|
579 |
+
The ``python3 -m pybind11 --includes`` command fetches the include paths for
|
580 |
+
both pybind11 and Python headers. This assumes that pybind11 has been installed
|
581 |
+
using ``pip`` or ``conda``. If it hasn't, you can also manually specify
|
582 |
+
``-I <path-to-pybind11>/include`` together with the Python includes path
|
583 |
+
``python3-config --includes``.
|
584 |
+
|
585 |
+
On macOS: the build command is almost the same but it also requires passing
|
586 |
+
the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
|
587 |
+
building the module:
|
588 |
+
|
589 |
+
.. code-block:: bash
|
590 |
+
|
591 |
+
$ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
|
592 |
+
|
593 |
+
In general, it is advisable to include several additional build parameters
|
594 |
+
that can considerably reduce the size of the created binary. Refer to section
|
595 |
+
:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
|
596 |
+
build system that works on all platforms including Windows.
|
597 |
+
|
598 |
+
.. note::
|
599 |
+
|
600 |
+
On Linux and macOS, it's better to (intentionally) not link against
|
601 |
+
``libpython``. The symbols will be resolved when the extension library
|
602 |
+
is loaded into a Python binary. This is preferable because you might
|
603 |
+
have several different installations of a given Python version (e.g. the
|
604 |
+
system-provided Python, and one that ships with a piece of commercial
|
605 |
+
software). In this way, the plugin will work with both versions, instead
|
606 |
+
of possibly importing a second Python library into a process that already
|
607 |
+
contains one (which will lead to a segfault).
|
608 |
+
|
609 |
+
|
610 |
+
Building with Bazel
|
611 |
+
===================
|
612 |
+
|
613 |
+
You can build with the Bazel build system using the `pybind11_bazel
|
614 |
+
<https://github.com/pybind/pybind11_bazel>`_ repository.
|
615 |
+
|
616 |
+
Generating binding code automatically
|
617 |
+
=====================================
|
618 |
+
|
619 |
+
The ``Binder`` project is a tool for automatic generation of pybind11 binding
|
620 |
+
code by introspecting existing C++ codebases using LLVM/Clang. See the
|
621 |
+
[binder]_ documentation for details.
|
622 |
+
|
623 |
+
.. [binder] http://cppbinder.readthedocs.io/en/latest/about.html
|
624 |
+
|
625 |
+
[AutoWIG]_ is a Python library that wraps automatically compiled libraries into
|
626 |
+
high-level languages. It parses C++ code using LLVM/Clang technologies and
|
627 |
+
generates the wrappers using the Mako templating engine. The approach is automatic,
|
628 |
+
extensible, and applies to very complex C++ libraries, composed of thousands of
|
629 |
+
classes or incorporating modern meta-programming constructs.
|
630 |
+
|
631 |
+
.. [AutoWIG] https://github.com/StatisKit/AutoWIG
|
632 |
+
|
633 |
+
[robotpy-build]_ is a is a pure python, cross platform build tool that aims to
|
634 |
+
simplify creation of python wheels for pybind11 projects, and provide
|
635 |
+
cross-project dependency management. Additionally, it is able to autogenerate
|
636 |
+
customizable pybind11-based wrappers by parsing C++ header files.
|
637 |
+
|
638 |
+
.. [robotpy-build] https://robotpy-build.readthedocs.io
|
third-party/DPVO/DPViewer/pybind11/docs/conf.py
ADDED
@@ -0,0 +1,380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
#
|
3 |
+
# pybind11 documentation build configuration file, created by
|
4 |
+
# sphinx-quickstart on Sun Oct 11 19:23:48 2015.
|
5 |
+
#
|
6 |
+
# This file is execfile()d with the current directory set to its
|
7 |
+
# containing dir.
|
8 |
+
#
|
9 |
+
# Note that not all possible configuration values are present in this
|
10 |
+
# autogenerated file.
|
11 |
+
#
|
12 |
+
# All configuration values have a default; values that are commented out
|
13 |
+
# serve to show the default.
|
14 |
+
|
15 |
+
import os
|
16 |
+
import re
|
17 |
+
import subprocess
|
18 |
+
import sys
|
19 |
+
from pathlib import Path
|
20 |
+
|
21 |
+
DIR = Path(__file__).parent.resolve()
|
22 |
+
|
23 |
+
# If extensions (or modules to document with autodoc) are in another directory,
|
24 |
+
# add these directories to sys.path here. If the directory is relative to the
|
25 |
+
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
26 |
+
# sys.path.insert(0, os.path.abspath('.'))
|
27 |
+
|
28 |
+
# -- General configuration ------------------------------------------------
|
29 |
+
|
30 |
+
# If your documentation needs a minimal Sphinx version, state it here.
|
31 |
+
# needs_sphinx = '1.0'
|
32 |
+
|
33 |
+
# Add any Sphinx extension module names here, as strings. They can be
|
34 |
+
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
|
35 |
+
# ones.
|
36 |
+
extensions = [
|
37 |
+
"breathe",
|
38 |
+
"sphinxcontrib.rsvgconverter",
|
39 |
+
"sphinxcontrib.moderncmakedomain",
|
40 |
+
]
|
41 |
+
|
42 |
+
breathe_projects = {"pybind11": ".build/doxygenxml/"}
|
43 |
+
breathe_default_project = "pybind11"
|
44 |
+
breathe_domain_by_extension = {"h": "cpp"}
|
45 |
+
|
46 |
+
# Add any paths that contain templates here, relative to this directory.
|
47 |
+
templates_path = [".templates"]
|
48 |
+
|
49 |
+
# The suffix(es) of source filenames.
|
50 |
+
# You can specify multiple suffix as a list of string:
|
51 |
+
# source_suffix = ['.rst', '.md']
|
52 |
+
source_suffix = ".rst"
|
53 |
+
|
54 |
+
# The encoding of source files.
|
55 |
+
# source_encoding = 'utf-8-sig'
|
56 |
+
|
57 |
+
# The master toctree document.
|
58 |
+
master_doc = "index"
|
59 |
+
|
60 |
+
# General information about the project.
|
61 |
+
project = "pybind11"
|
62 |
+
copyright = "2017, Wenzel Jakob"
|
63 |
+
author = "Wenzel Jakob"
|
64 |
+
|
65 |
+
# The version info for the project you're documenting, acts as replacement for
|
66 |
+
# |version| and |release|, also used in various other places throughout the
|
67 |
+
# built documents.
|
68 |
+
|
69 |
+
# Read the listed version
|
70 |
+
with open("../pybind11/_version.py") as f:
|
71 |
+
code = compile(f.read(), "../pybind11/_version.py", "exec")
|
72 |
+
loc = {}
|
73 |
+
exec(code, loc)
|
74 |
+
|
75 |
+
# The full version, including alpha/beta/rc tags.
|
76 |
+
version = loc["__version__"]
|
77 |
+
|
78 |
+
# The language for content autogenerated by Sphinx. Refer to documentation
|
79 |
+
# for a list of supported languages.
|
80 |
+
#
|
81 |
+
# This is also used if you do content translation via gettext catalogs.
|
82 |
+
# Usually you set "language" from the command line for these cases.
|
83 |
+
language = None
|
84 |
+
|
85 |
+
# There are two options for replacing |today|: either, you set today to some
|
86 |
+
# non-false value, then it is used:
|
87 |
+
# today = ''
|
88 |
+
# Else, today_fmt is used as the format for a strftime call.
|
89 |
+
# today_fmt = '%B %d, %Y'
|
90 |
+
|
91 |
+
# List of patterns, relative to source directory, that match files and
|
92 |
+
# directories to ignore when looking for source files.
|
93 |
+
exclude_patterns = [".build", "release.rst"]
|
94 |
+
|
95 |
+
# The reST default role (used for this markup: `text`) to use for all
|
96 |
+
# documents.
|
97 |
+
default_role = "any"
|
98 |
+
|
99 |
+
# If true, '()' will be appended to :func: etc. cross-reference text.
|
100 |
+
# add_function_parentheses = True
|
101 |
+
|
102 |
+
# If true, the current module name will be prepended to all description
|
103 |
+
# unit titles (such as .. function::).
|
104 |
+
# add_module_names = True
|
105 |
+
|
106 |
+
# If true, sectionauthor and moduleauthor directives will be shown in the
|
107 |
+
# output. They are ignored by default.
|
108 |
+
# show_authors = False
|
109 |
+
|
110 |
+
# The name of the Pygments (syntax highlighting) style to use.
|
111 |
+
# pygments_style = 'monokai'
|
112 |
+
|
113 |
+
# A list of ignored prefixes for module index sorting.
|
114 |
+
# modindex_common_prefix = []
|
115 |
+
|
116 |
+
# If true, keep warnings as "system message" paragraphs in the built documents.
|
117 |
+
# keep_warnings = False
|
118 |
+
|
119 |
+
# If true, `todo` and `todoList` produce output, else they produce nothing.
|
120 |
+
todo_include_todos = False
|
121 |
+
|
122 |
+
|
123 |
+
# -- Options for HTML output ----------------------------------------------
|
124 |
+
|
125 |
+
# The theme to use for HTML and HTML Help pages. See the documentation for
|
126 |
+
# a list of builtin themes.
|
127 |
+
|
128 |
+
on_rtd = os.environ.get("READTHEDOCS", None) == "True"
|
129 |
+
|
130 |
+
if not on_rtd: # only import and set the theme if we're building docs locally
|
131 |
+
import sphinx_rtd_theme
|
132 |
+
|
133 |
+
html_theme = "sphinx_rtd_theme"
|
134 |
+
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
135 |
+
|
136 |
+
html_context = {"css_files": ["_static/theme_overrides.css"]}
|
137 |
+
else:
|
138 |
+
html_context = {
|
139 |
+
"css_files": [
|
140 |
+
"//media.readthedocs.org/css/sphinx_rtd_theme.css",
|
141 |
+
"//media.readthedocs.org/css/readthedocs-doc-embed.css",
|
142 |
+
"_static/theme_overrides.css",
|
143 |
+
]
|
144 |
+
}
|
145 |
+
|
146 |
+
# Theme options are theme-specific and customize the look and feel of a theme
|
147 |
+
# further. For a list of options available for each theme, see the
|
148 |
+
# documentation.
|
149 |
+
# html_theme_options = {}
|
150 |
+
|
151 |
+
# Add any paths that contain custom themes here, relative to this directory.
|
152 |
+
# html_theme_path = []
|
153 |
+
|
154 |
+
# The name for this set of Sphinx documents. If None, it defaults to
|
155 |
+
# "<project> v<version> documentation".
|
156 |
+
# html_title = None
|
157 |
+
|
158 |
+
# A shorter title for the navigation bar. Default is the same as html_title.
|
159 |
+
# html_short_title = None
|
160 |
+
|
161 |
+
# The name of an image file (relative to this directory) to place at the top
|
162 |
+
# of the sidebar.
|
163 |
+
# html_logo = None
|
164 |
+
|
165 |
+
# The name of an image file (within the static path) to use as favicon of the
|
166 |
+
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
167 |
+
# pixels large.
|
168 |
+
# html_favicon = None
|
169 |
+
|
170 |
+
# Add any paths that contain custom static files (such as style sheets) here,
|
171 |
+
# relative to this directory. They are copied after the builtin static files,
|
172 |
+
# so a file named "default.css" will overwrite the builtin "default.css".
|
173 |
+
html_static_path = ["_static"]
|
174 |
+
|
175 |
+
# Add any extra paths that contain custom files (such as robots.txt or
|
176 |
+
# .htaccess) here, relative to this directory. These files are copied
|
177 |
+
# directly to the root of the documentation.
|
178 |
+
# html_extra_path = []
|
179 |
+
|
180 |
+
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
181 |
+
# using the given strftime format.
|
182 |
+
# html_last_updated_fmt = '%b %d, %Y'
|
183 |
+
|
184 |
+
# If true, SmartyPants will be used to convert quotes and dashes to
|
185 |
+
# typographically correct entities.
|
186 |
+
# html_use_smartypants = True
|
187 |
+
|
188 |
+
# Custom sidebar templates, maps document names to template names.
|
189 |
+
# html_sidebars = {}
|
190 |
+
|
191 |
+
# Additional templates that should be rendered to pages, maps page names to
|
192 |
+
# template names.
|
193 |
+
# html_additional_pages = {}
|
194 |
+
|
195 |
+
# If false, no module index is generated.
|
196 |
+
# html_domain_indices = True
|
197 |
+
|
198 |
+
# If false, no index is generated.
|
199 |
+
# html_use_index = True
|
200 |
+
|
201 |
+
# If true, the index is split into individual pages for each letter.
|
202 |
+
# html_split_index = False
|
203 |
+
|
204 |
+
# If true, links to the reST sources are added to the pages.
|
205 |
+
# html_show_sourcelink = True
|
206 |
+
|
207 |
+
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
|
208 |
+
# html_show_sphinx = True
|
209 |
+
|
210 |
+
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
|
211 |
+
# html_show_copyright = True
|
212 |
+
|
213 |
+
# If true, an OpenSearch description file will be output, and all pages will
|
214 |
+
# contain a <link> tag referring to it. The value of this option must be the
|
215 |
+
# base URL from which the finished HTML is served.
|
216 |
+
# html_use_opensearch = ''
|
217 |
+
|
218 |
+
# This is the file name suffix for HTML files (e.g. ".xhtml").
|
219 |
+
# html_file_suffix = None
|
220 |
+
|
221 |
+
# Language to be used for generating the HTML full-text search index.
|
222 |
+
# Sphinx supports the following languages:
|
223 |
+
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
|
224 |
+
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
|
225 |
+
# html_search_language = 'en'
|
226 |
+
|
227 |
+
# A dictionary with options for the search language support, empty by default.
|
228 |
+
# Now only 'ja' uses this config value
|
229 |
+
# html_search_options = {'type': 'default'}
|
230 |
+
|
231 |
+
# The name of a javascript file (relative to the configuration directory) that
|
232 |
+
# implements a search results scorer. If empty, the default will be used.
|
233 |
+
# html_search_scorer = 'scorer.js'
|
234 |
+
|
235 |
+
# Output file base name for HTML help builder.
|
236 |
+
htmlhelp_basename = "pybind11doc"
|
237 |
+
|
238 |
+
# -- Options for LaTeX output ---------------------------------------------
|
239 |
+
|
240 |
+
latex_engine = "pdflatex"
|
241 |
+
|
242 |
+
latex_elements = {
|
243 |
+
# The paper size ('letterpaper' or 'a4paper').
|
244 |
+
# 'papersize': 'letterpaper',
|
245 |
+
#
|
246 |
+
# The font size ('10pt', '11pt' or '12pt').
|
247 |
+
# 'pointsize': '10pt',
|
248 |
+
#
|
249 |
+
# Additional stuff for the LaTeX preamble.
|
250 |
+
# remove blank pages (between the title page and the TOC, etc.)
|
251 |
+
"classoptions": ",openany,oneside",
|
252 |
+
"preamble": r"""
|
253 |
+
\usepackage{fontawesome}
|
254 |
+
\usepackage{textgreek}
|
255 |
+
\DeclareUnicodeCharacter{00A0}{}
|
256 |
+
\DeclareUnicodeCharacter{2194}{\faArrowsH}
|
257 |
+
\DeclareUnicodeCharacter{1F382}{\faBirthdayCake}
|
258 |
+
\DeclareUnicodeCharacter{1F355}{\faAdjust}
|
259 |
+
\DeclareUnicodeCharacter{0301}{'}
|
260 |
+
\DeclareUnicodeCharacter{03C0}{\textpi}
|
261 |
+
|
262 |
+
""",
|
263 |
+
# Latex figure (float) alignment
|
264 |
+
# 'figure_align': 'htbp',
|
265 |
+
}
|
266 |
+
|
267 |
+
# Grouping the document tree into LaTeX files. List of tuples
|
268 |
+
# (source start file, target name, title,
|
269 |
+
# author, documentclass [howto, manual, or own class]).
|
270 |
+
latex_documents = [
|
271 |
+
(master_doc, "pybind11.tex", "pybind11 Documentation", "Wenzel Jakob", "manual"),
|
272 |
+
]
|
273 |
+
|
274 |
+
# The name of an image file (relative to this directory) to place at the top of
|
275 |
+
# the title page.
|
276 |
+
# latex_logo = 'pybind11-logo.png'
|
277 |
+
|
278 |
+
# For "manual" documents, if this is true, then toplevel headings are parts,
|
279 |
+
# not chapters.
|
280 |
+
# latex_use_parts = False
|
281 |
+
|
282 |
+
# If true, show page references after internal links.
|
283 |
+
# latex_show_pagerefs = False
|
284 |
+
|
285 |
+
# If true, show URL addresses after external links.
|
286 |
+
# latex_show_urls = False
|
287 |
+
|
288 |
+
# Documents to append as an appendix to all manuals.
|
289 |
+
# latex_appendices = []
|
290 |
+
|
291 |
+
# If false, no module index is generated.
|
292 |
+
# latex_domain_indices = True
|
293 |
+
|
294 |
+
|
295 |
+
# -- Options for manual page output ---------------------------------------
|
296 |
+
|
297 |
+
# One entry per manual page. List of tuples
|
298 |
+
# (source start file, name, description, authors, manual section).
|
299 |
+
man_pages = [(master_doc, "pybind11", "pybind11 Documentation", [author], 1)]
|
300 |
+
|
301 |
+
# If true, show URL addresses after external links.
|
302 |
+
# man_show_urls = False
|
303 |
+
|
304 |
+
|
305 |
+
# -- Options for Texinfo output -------------------------------------------
|
306 |
+
|
307 |
+
# Grouping the document tree into Texinfo files. List of tuples
|
308 |
+
# (source start file, target name, title, author,
|
309 |
+
# dir menu entry, description, category)
|
310 |
+
texinfo_documents = [
|
311 |
+
(
|
312 |
+
master_doc,
|
313 |
+
"pybind11",
|
314 |
+
"pybind11 Documentation",
|
315 |
+
author,
|
316 |
+
"pybind11",
|
317 |
+
"One line description of project.",
|
318 |
+
"Miscellaneous",
|
319 |
+
),
|
320 |
+
]
|
321 |
+
|
322 |
+
# Documents to append as an appendix to all manuals.
|
323 |
+
# texinfo_appendices = []
|
324 |
+
|
325 |
+
# If false, no module index is generated.
|
326 |
+
# texinfo_domain_indices = True
|
327 |
+
|
328 |
+
# How to display URL addresses: 'footnote', 'no', or 'inline'.
|
329 |
+
# texinfo_show_urls = 'footnote'
|
330 |
+
|
331 |
+
# If true, do not generate a @detailmenu in the "Top" node's menu.
|
332 |
+
# texinfo_no_detailmenu = False
|
333 |
+
|
334 |
+
primary_domain = "cpp"
|
335 |
+
highlight_language = "cpp"
|
336 |
+
|
337 |
+
|
338 |
+
def generate_doxygen_xml(app):
|
339 |
+
build_dir = os.path.join(app.confdir, ".build")
|
340 |
+
if not os.path.exists(build_dir):
|
341 |
+
os.mkdir(build_dir)
|
342 |
+
|
343 |
+
try:
|
344 |
+
subprocess.call(["doxygen", "--version"])
|
345 |
+
retcode = subprocess.call(["doxygen"], cwd=app.confdir)
|
346 |
+
if retcode < 0:
|
347 |
+
sys.stderr.write(f"doxygen error code: {-retcode}\n")
|
348 |
+
except OSError as e:
|
349 |
+
sys.stderr.write(f"doxygen execution failed: {e}\n")
|
350 |
+
|
351 |
+
|
352 |
+
def prepare(app):
|
353 |
+
with open(DIR.parent / "README.rst") as f:
|
354 |
+
contents = f.read()
|
355 |
+
|
356 |
+
if app.builder.name == "latex":
|
357 |
+
# Remove badges and stuff from start
|
358 |
+
contents = contents[contents.find(r".. start") :]
|
359 |
+
|
360 |
+
# Filter out section titles for index.rst for LaTeX
|
361 |
+
contents = re.sub(r"^(.*)\n[-~]{3,}$", r"**\1**", contents, flags=re.MULTILINE)
|
362 |
+
|
363 |
+
with open(DIR / "readme.rst", "w") as f:
|
364 |
+
f.write(contents)
|
365 |
+
|
366 |
+
|
367 |
+
def clean_up(app, exception):
|
368 |
+
(DIR / "readme.rst").unlink()
|
369 |
+
|
370 |
+
|
371 |
+
def setup(app):
|
372 |
+
|
373 |
+
# Add hook for building doxygen xml when needed
|
374 |
+
app.connect("builder-inited", generate_doxygen_xml)
|
375 |
+
|
376 |
+
# Copy the readme in
|
377 |
+
app.connect("builder-inited", prepare)
|
378 |
+
|
379 |
+
# Clean up the generated readme
|
380 |
+
app.connect("build-finished", clean_up)
|
third-party/DPVO/DPViewer/pybind11/docs/faq.rst
ADDED
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 that does not match what you compiled with.
|
12 |
+
|
13 |
+
"Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
|
14 |
+
========================================================================
|
15 |
+
|
16 |
+
See the first answer.
|
17 |
+
|
18 |
+
"SystemError: dynamic module not initialized properly"
|
19 |
+
======================================================
|
20 |
+
|
21 |
+
See the first answer.
|
22 |
+
|
23 |
+
The Python interpreter immediately crashes when importing my module
|
24 |
+
===================================================================
|
25 |
+
|
26 |
+
See the first answer.
|
27 |
+
|
28 |
+
.. _faq_reference_arguments:
|
29 |
+
|
30 |
+
Limitations involving reference arguments
|
31 |
+
=========================================
|
32 |
+
|
33 |
+
In C++, it's fairly common to pass arguments using mutable references or
|
34 |
+
mutable pointers, which allows both read and write access to the value
|
35 |
+
supplied by the caller. This is sometimes done for efficiency reasons, or to
|
36 |
+
realize functions that have multiple return values. Here are two very basic
|
37 |
+
examples:
|
38 |
+
|
39 |
+
.. code-block:: cpp
|
40 |
+
|
41 |
+
void increment(int &i) { i++; }
|
42 |
+
void increment_ptr(int *i) { (*i)++; }
|
43 |
+
|
44 |
+
In Python, all arguments are passed by reference, so there is no general
|
45 |
+
issue in binding such code from Python.
|
46 |
+
|
47 |
+
However, certain basic Python types (like ``str``, ``int``, ``bool``,
|
48 |
+
``float``, etc.) are **immutable**. This means that the following attempt
|
49 |
+
to port the function to Python doesn't have the same effect on the value
|
50 |
+
provided by the caller -- in fact, it does nothing at all.
|
51 |
+
|
52 |
+
.. code-block:: python
|
53 |
+
|
54 |
+
def increment(i):
|
55 |
+
i += 1 # nope..
|
56 |
+
|
57 |
+
pybind11 is also affected by such language-level conventions, which means that
|
58 |
+
binding ``increment`` or ``increment_ptr`` will also create Python functions
|
59 |
+
that don't modify their arguments.
|
60 |
+
|
61 |
+
Although inconvenient, one workaround is to encapsulate the immutable types in
|
62 |
+
a custom type that does allow modifications.
|
63 |
+
|
64 |
+
An other alternative involves binding a small wrapper lambda function that
|
65 |
+
returns a tuple with all output arguments (see the remainder of the
|
66 |
+
documentation for examples on binding lambda functions). An example:
|
67 |
+
|
68 |
+
.. code-block:: cpp
|
69 |
+
|
70 |
+
int foo(int &i) { i++; return 123; }
|
71 |
+
|
72 |
+
and the binding code
|
73 |
+
|
74 |
+
.. code-block:: cpp
|
75 |
+
|
76 |
+
m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
|
77 |
+
|
78 |
+
|
79 |
+
How can I reduce the build time?
|
80 |
+
================================
|
81 |
+
|
82 |
+
It's good practice to split binding code over multiple files, as in the
|
83 |
+
following example:
|
84 |
+
|
85 |
+
:file:`example.cpp`:
|
86 |
+
|
87 |
+
.. code-block:: cpp
|
88 |
+
|
89 |
+
void init_ex1(py::module_ &);
|
90 |
+
void init_ex2(py::module_ &);
|
91 |
+
/* ... */
|
92 |
+
|
93 |
+
PYBIND11_MODULE(example, m) {
|
94 |
+
init_ex1(m);
|
95 |
+
init_ex2(m);
|
96 |
+
/* ... */
|
97 |
+
}
|
98 |
+
|
99 |
+
:file:`ex1.cpp`:
|
100 |
+
|
101 |
+
.. code-block:: cpp
|
102 |
+
|
103 |
+
void init_ex1(py::module_ &m) {
|
104 |
+
m.def("add", [](int a, int b) { return a + b; });
|
105 |
+
}
|
106 |
+
|
107 |
+
:file:`ex2.cpp`:
|
108 |
+
|
109 |
+
.. code-block:: cpp
|
110 |
+
|
111 |
+
void init_ex2(py::module_ &m) {
|
112 |
+
m.def("sub", [](int a, int b) { return a - b; });
|
113 |
+
}
|
114 |
+
|
115 |
+
:command:`python`:
|
116 |
+
|
117 |
+
.. code-block:: pycon
|
118 |
+
|
119 |
+
>>> import example
|
120 |
+
>>> example.add(1, 2)
|
121 |
+
3
|
122 |
+
>>> example.sub(1, 1)
|
123 |
+
0
|
124 |
+
|
125 |
+
As shown above, the various ``init_ex`` functions should be contained in
|
126 |
+
separate files that can be compiled independently from one another, and then
|
127 |
+
linked together into the same final shared object. Following this approach
|
128 |
+
will:
|
129 |
+
|
130 |
+
1. reduce memory requirements per compilation unit.
|
131 |
+
|
132 |
+
2. enable parallel builds (if desired).
|
133 |
+
|
134 |
+
3. allow for faster incremental builds. For instance, when a single class
|
135 |
+
definition is changed, only a subset of the binding code will generally need
|
136 |
+
to be recompiled.
|
137 |
+
|
138 |
+
"recursive template instantiation exceeded maximum depth of 256"
|
139 |
+
================================================================
|
140 |
+
|
141 |
+
If you receive an error about excessive recursive template evaluation, try
|
142 |
+
specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The
|
143 |
+
culprit is generally the generation of function signatures at compile time
|
144 |
+
using C++14 template metaprogramming.
|
145 |
+
|
146 |
+
.. _`faq:hidden_visibility`:
|
147 |
+
|
148 |
+
"'SomeClass' declared with greater visibility than the type of its field 'SomeClass::member' [-Wattributes]"
|
149 |
+
============================================================================================================
|
150 |
+
|
151 |
+
This error typically indicates that you are compiling without the required
|
152 |
+
``-fvisibility`` flag. pybind11 code internally forces hidden visibility on
|
153 |
+
all internal code, but if non-hidden (and thus *exported*) code attempts to
|
154 |
+
include a pybind type (for example, ``py::object`` or ``py::list``) you can run
|
155 |
+
into this warning.
|
156 |
+
|
157 |
+
To avoid it, make sure you are specifying ``-fvisibility=hidden`` when
|
158 |
+
compiling pybind code.
|
159 |
+
|
160 |
+
As to why ``-fvisibility=hidden`` is necessary, because pybind modules could
|
161 |
+
have been compiled under different versions of pybind itself, it is also
|
162 |
+
important that the symbols defined in one module do not clash with the
|
163 |
+
potentially-incompatible symbols defined in another. While Python extension
|
164 |
+
modules are usually loaded with localized symbols (under POSIX systems
|
165 |
+
typically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default
|
166 |
+
can be changed, but even if it isn't it is not always enough to guarantee
|
167 |
+
complete independence of the symbols involved when not using
|
168 |
+
``-fvisibility=hidden``.
|
169 |
+
|
170 |
+
Additionally, ``-fvisibility=hidden`` can deliver considerably binary size
|
171 |
+
savings. (See the following section for more details.)
|
172 |
+
|
173 |
+
|
174 |
+
.. _`faq:symhidden`:
|
175 |
+
|
176 |
+
How can I create smaller binaries?
|
177 |
+
==================================
|
178 |
+
|
179 |
+
To do its job, pybind11 extensively relies on a programming technique known as
|
180 |
+
*template metaprogramming*, which is a way of performing computation at compile
|
181 |
+
time using type information. Template metaprogramming usually instantiates code
|
182 |
+
involving significant numbers of deeply nested types that are either completely
|
183 |
+
removed or reduced to just a few instructions during the compiler's optimization
|
184 |
+
phase. However, due to the nested nature of these types, the resulting symbol
|
185 |
+
names in the compiled extension library can be extremely long. For instance,
|
186 |
+
the included test suite contains the following symbol:
|
187 |
+
|
188 |
+
.. only:: html
|
189 |
+
|
190 |
+
.. code-block:: none
|
191 |
+
|
192 |
+
__ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
|
193 |
+
|
194 |
+
.. only:: not html
|
195 |
+
|
196 |
+
.. code-block:: cpp
|
197 |
+
|
198 |
+
__ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
|
199 |
+
|
200 |
+
which is the mangled form of the following function type:
|
201 |
+
|
202 |
+
.. code-block:: cpp
|
203 |
+
|
204 |
+
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])
|
205 |
+
|
206 |
+
The memory needed to store just the mangled name of this function (196 bytes)
|
207 |
+
is larger than the actual piece of code (111 bytes) it represents! On the other
|
208 |
+
hand, it's silly to even give this function a name -- after all, it's just a
|
209 |
+
tiny cog in a bigger piece of machinery that is not exposed to the outside
|
210 |
+
world. So we'll generally only want to export symbols for those functions which
|
211 |
+
are actually called from the outside.
|
212 |
+
|
213 |
+
This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
|
214 |
+
and Clang, which sets the default symbol visibility to *hidden*, which has a
|
215 |
+
tremendous impact on the final binary size of the resulting extension library.
|
216 |
+
(On Visual Studio, symbols are already hidden by default, so nothing needs to
|
217 |
+
be done there.)
|
218 |
+
|
219 |
+
In addition to decreasing binary size, ``-fvisibility=hidden`` also avoids
|
220 |
+
potential serious issues when loading multiple modules and is required for
|
221 |
+
proper pybind operation. See the previous FAQ entry for more details.
|
222 |
+
|
223 |
+
How can I properly handle Ctrl-C in long-running functions?
|
224 |
+
===========================================================
|
225 |
+
|
226 |
+
Ctrl-C is received by the Python interpreter, and holds it until the GIL
|
227 |
+
is released, so a long-running function won't be interrupted.
|
228 |
+
|
229 |
+
To interrupt from inside your function, you can use the ``PyErr_CheckSignals()``
|
230 |
+
function, that will tell if a signal has been raised on the Python side. This
|
231 |
+
function merely checks a flag, so its impact is negligible. When a signal has
|
232 |
+
been received, you must either explicitly interrupt execution by throwing
|
233 |
+
``py::error_already_set`` (which will propagate the existing
|
234 |
+
``KeyboardInterrupt``), or clear the error (which you usually will not want):
|
235 |
+
|
236 |
+
.. code-block:: cpp
|
237 |
+
|
238 |
+
PYBIND11_MODULE(example, m)
|
239 |
+
{
|
240 |
+
m.def("long running_func", []()
|
241 |
+
{
|
242 |
+
for (;;) {
|
243 |
+
if (PyErr_CheckSignals() != 0)
|
244 |
+
throw py::error_already_set();
|
245 |
+
// Long running iteration
|
246 |
+
}
|
247 |
+
});
|
248 |
+
}
|
249 |
+
|
250 |
+
CMake doesn't detect the right Python version
|
251 |
+
=============================================
|
252 |
+
|
253 |
+
The CMake-based build system will try to automatically detect the installed
|
254 |
+
version of Python and link against that. When this fails, or when there are
|
255 |
+
multiple versions of Python and it finds the wrong one, delete
|
256 |
+
``CMakeCache.txt`` and then add ``-DPYTHON_EXECUTABLE=$(which python)`` to your
|
257 |
+
CMake configure line. (Replace ``$(which python)`` with a path to python if
|
258 |
+
your prefer.)
|
259 |
+
|
260 |
+
You can alternatively try ``-DPYBIND11_FINDPYTHON=ON``, which will activate the
|
261 |
+
new CMake FindPython support instead of pybind11's custom search. Requires
|
262 |
+
CMake 3.12+, and 3.15+ or 3.18.2+ are even better. You can set this in your
|
263 |
+
``CMakeLists.txt`` before adding or finding pybind11, as well.
|
264 |
+
|
265 |
+
Inconsistent detection of Python version in CMake and pybind11
|
266 |
+
==============================================================
|
267 |
+
|
268 |
+
The functions ``find_package(PythonInterp)`` and ``find_package(PythonLibs)``
|
269 |
+
provided by CMake for Python version detection are modified by pybind11 due to
|
270 |
+
unreliability and limitations that make them unsuitable for pybind11's needs.
|
271 |
+
Instead pybind11 provides its own, more reliable Python detection CMake code.
|
272 |
+
Conflicts can arise, however, when using pybind11 in a project that *also* uses
|
273 |
+
the CMake Python detection in a system with several Python versions installed.
|
274 |
+
|
275 |
+
This difference may cause inconsistencies and errors if *both* mechanisms are
|
276 |
+
used in the same project.
|
277 |
+
|
278 |
+
There are three possible solutions:
|
279 |
+
|
280 |
+
1. Avoid using ``find_package(PythonInterp)`` and ``find_package(PythonLibs)``
|
281 |
+
from CMake and rely on pybind11 in detecting Python version. If this is not
|
282 |
+
possible, the CMake machinery should be called *before* including pybind11.
|
283 |
+
2. Set ``PYBIND11_FINDPYTHON`` to ``True`` or use ``find_package(Python
|
284 |
+
COMPONENTS Interpreter Development)`` on modern CMake (3.12+, 3.15+ better,
|
285 |
+
3.18.2+ best). Pybind11 in these cases uses the new CMake FindPython instead
|
286 |
+
of the old, deprecated search tools, and these modules are much better at
|
287 |
+
finding the correct Python.
|
288 |
+
3. Set ``PYBIND11_NOPYTHON`` to ``TRUE``. Pybind11 will not search for Python.
|
289 |
+
However, you will have to use the target-based system, and do more setup
|
290 |
+
yourself, because it does not know about or include things that depend on
|
291 |
+
Python, like ``pybind11_add_module``. This might be ideal for integrating
|
292 |
+
into an existing system, like scikit-build's Python helpers.
|
293 |
+
|
294 |
+
How to cite this project?
|
295 |
+
=========================
|
296 |
+
|
297 |
+
We suggest the following BibTeX template to cite pybind11 in scientific
|
298 |
+
discourse:
|
299 |
+
|
300 |
+
.. code-block:: bash
|
301 |
+
|
302 |
+
@misc{pybind11,
|
303 |
+
author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan},
|
304 |
+
year = {2017},
|
305 |
+
note = {https://github.com/pybind/pybind11},
|
306 |
+
title = {pybind11 -- Seamless operability between C++11 and Python}
|
307 |
+
}
|
third-party/DPVO/DPViewer/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/DPViewer/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/DPViewer/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/DPViewer/pybind11/docs/pybind11-logo.png
ADDED
![]() |
third-party/DPVO/DPViewer/pybind11/docs/pybind11_vs_boost_python1.png
ADDED
![]() |
third-party/DPVO/DPViewer/pybind11/docs/pybind11_vs_boost_python1.svg
ADDED
|
third-party/DPVO/DPViewer/pybind11/docs/pybind11_vs_boost_python2.png
ADDED
![]() |
third-party/DPVO/DPViewer/pybind11/docs/pybind11_vs_boost_python2.svg
ADDED
|
third-party/DPVO/DPViewer/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/DPViewer/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/DPViewer/pybind11/docs/requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
breathe==4.32.0
|
2 |
+
sphinx==4.4.0
|
3 |
+
sphinx_rtd_theme==1.0.0
|
4 |
+
sphinxcontrib-moderncmakedomain==3.21.4
|
5 |
+
sphinxcontrib-svg2pdfconverter==1.2.0
|
third-party/DPVO/DPViewer/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/DPViewer/pybind11/include/pybind11/attr.h
ADDED
@@ -0,0 +1,676 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 "detail/common.h"
|
14 |
+
#include "cast.h"
|
15 |
+
|
16 |
+
#include <functional>
|
17 |
+
|
18 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
19 |
+
|
20 |
+
/// \addtogroup annotations
|
21 |
+
/// @{
|
22 |
+
|
23 |
+
/// Annotation for methods
|
24 |
+
struct is_method {
|
25 |
+
handle class_;
|
26 |
+
explicit is_method(const handle &c) : class_(c) {}
|
27 |
+
};
|
28 |
+
|
29 |
+
/// Annotation for operators
|
30 |
+
struct is_operator {};
|
31 |
+
|
32 |
+
/// Annotation for classes that cannot be subclassed
|
33 |
+
struct is_final {};
|
34 |
+
|
35 |
+
/// Annotation for parent scope
|
36 |
+
struct scope {
|
37 |
+
handle value;
|
38 |
+
explicit scope(const handle &s) : value(s) {}
|
39 |
+
};
|
40 |
+
|
41 |
+
/// Annotation for documentation
|
42 |
+
struct doc {
|
43 |
+
const char *value;
|
44 |
+
explicit doc(const char *value) : value(value) {}
|
45 |
+
};
|
46 |
+
|
47 |
+
/// Annotation for function names
|
48 |
+
struct name {
|
49 |
+
const char *value;
|
50 |
+
explicit name(const char *value) : value(value) {}
|
51 |
+
};
|
52 |
+
|
53 |
+
/// Annotation indicating that a function is an overload associated with a given "sibling"
|
54 |
+
struct sibling {
|
55 |
+
handle value;
|
56 |
+
explicit sibling(const handle &value) : value(value.ptr()) {}
|
57 |
+
};
|
58 |
+
|
59 |
+
/// Annotation indicating that a class derives from another given type
|
60 |
+
template <typename T>
|
61 |
+
struct base {
|
62 |
+
|
63 |
+
PYBIND11_DEPRECATED(
|
64 |
+
"base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
|
65 |
+
base() = default;
|
66 |
+
};
|
67 |
+
|
68 |
+
/// Keep patient alive while nurse lives
|
69 |
+
template <size_t Nurse, size_t Patient>
|
70 |
+
struct keep_alive {};
|
71 |
+
|
72 |
+
/// Annotation indicating that a class is involved in a multiple inheritance relationship
|
73 |
+
struct multiple_inheritance {};
|
74 |
+
|
75 |
+
/// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
|
76 |
+
struct dynamic_attr {};
|
77 |
+
|
78 |
+
/// Annotation which enables the buffer protocol for a type
|
79 |
+
struct buffer_protocol {};
|
80 |
+
|
81 |
+
/// Annotation which requests that a special metaclass is created for a type
|
82 |
+
struct metaclass {
|
83 |
+
handle value;
|
84 |
+
|
85 |
+
PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
|
86 |
+
metaclass() = default;
|
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(PYBIND11_DETAILED_ERROR_MESSAGES)
|
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 |
+
"#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
|
503 |
+
"more information.");
|
504 |
+
#endif
|
505 |
+
}
|
506 |
+
r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
|
507 |
+
|
508 |
+
check_kw_only_arg(a, r);
|
509 |
+
}
|
510 |
+
};
|
511 |
+
|
512 |
+
/// Process a keyword-only-arguments-follow pseudo argument
|
513 |
+
template <>
|
514 |
+
struct process_attribute<kw_only> : process_attribute_default<kw_only> {
|
515 |
+
static void init(const kw_only &, function_record *r) {
|
516 |
+
append_self_arg_if_needed(r);
|
517 |
+
if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) {
|
518 |
+
pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative "
|
519 |
+
"argument location (or omit kw_only() entirely)");
|
520 |
+
}
|
521 |
+
r->nargs_pos = static_cast<std::uint16_t>(r->args.size());
|
522 |
+
}
|
523 |
+
};
|
524 |
+
|
525 |
+
/// Process a positional-only-argument maker
|
526 |
+
template <>
|
527 |
+
struct process_attribute<pos_only> : process_attribute_default<pos_only> {
|
528 |
+
static void init(const pos_only &, function_record *r) {
|
529 |
+
append_self_arg_if_needed(r);
|
530 |
+
r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
|
531 |
+
if (r->nargs_pos_only > r->nargs_pos) {
|
532 |
+
pybind11_fail("pos_only(): cannot follow a py::args() argument");
|
533 |
+
}
|
534 |
+
// It also can't follow a kw_only, but a static_assert in pybind11.h checks that
|
535 |
+
}
|
536 |
+
};
|
537 |
+
|
538 |
+
/// Process a parent class attribute. Single inheritance only (class_ itself already guarantees
|
539 |
+
/// that)
|
540 |
+
template <typename T>
|
541 |
+
struct process_attribute<T, enable_if_t<is_pyobject<T>::value>>
|
542 |
+
: process_attribute_default<handle> {
|
543 |
+
static void init(const handle &h, type_record *r) { r->bases.append(h); }
|
544 |
+
};
|
545 |
+
|
546 |
+
/// Process a parent class attribute (deprecated, does not support multiple inheritance)
|
547 |
+
template <typename T>
|
548 |
+
struct process_attribute<base<T>> : process_attribute_default<base<T>> {
|
549 |
+
static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
|
550 |
+
};
|
551 |
+
|
552 |
+
/// Process a multiple inheritance attribute
|
553 |
+
template <>
|
554 |
+
struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
|
555 |
+
static void init(const multiple_inheritance &, type_record *r) {
|
556 |
+
r->multiple_inheritance = true;
|
557 |
+
}
|
558 |
+
};
|
559 |
+
|
560 |
+
template <>
|
561 |
+
struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
|
562 |
+
static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
|
563 |
+
};
|
564 |
+
|
565 |
+
template <>
|
566 |
+
struct process_attribute<custom_type_setup> {
|
567 |
+
static void init(const custom_type_setup &value, type_record *r) {
|
568 |
+
r->custom_type_setup_callback = value.value;
|
569 |
+
}
|
570 |
+
};
|
571 |
+
|
572 |
+
template <>
|
573 |
+
struct process_attribute<is_final> : process_attribute_default<is_final> {
|
574 |
+
static void init(const is_final &, type_record *r) { r->is_final = true; }
|
575 |
+
};
|
576 |
+
|
577 |
+
template <>
|
578 |
+
struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
|
579 |
+
static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
|
580 |
+
};
|
581 |
+
|
582 |
+
template <>
|
583 |
+
struct process_attribute<metaclass> : process_attribute_default<metaclass> {
|
584 |
+
static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
|
585 |
+
};
|
586 |
+
|
587 |
+
template <>
|
588 |
+
struct process_attribute<module_local> : process_attribute_default<module_local> {
|
589 |
+
static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
|
590 |
+
};
|
591 |
+
|
592 |
+
/// Process a 'prepend' attribute, putting this at the beginning of the overload chain
|
593 |
+
template <>
|
594 |
+
struct process_attribute<prepend> : process_attribute_default<prepend> {
|
595 |
+
static void init(const prepend &, function_record *r) { r->prepend = true; }
|
596 |
+
};
|
597 |
+
|
598 |
+
/// Process an 'arithmetic' attribute for enums (does nothing here)
|
599 |
+
template <>
|
600 |
+
struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
|
601 |
+
|
602 |
+
template <typename... Ts>
|
603 |
+
struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {};
|
604 |
+
|
605 |
+
/**
|
606 |
+
* Process a keep_alive call policy -- invokes keep_alive_impl during the
|
607 |
+
* pre-call handler if both Nurse, Patient != 0 and use the post-call handler
|
608 |
+
* otherwise
|
609 |
+
*/
|
610 |
+
template <size_t Nurse, size_t Patient>
|
611 |
+
struct process_attribute<keep_alive<Nurse, Patient>>
|
612 |
+
: public process_attribute_default<keep_alive<Nurse, Patient>> {
|
613 |
+
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
|
614 |
+
static void precall(function_call &call) {
|
615 |
+
keep_alive_impl(Nurse, Patient, call, handle());
|
616 |
+
}
|
617 |
+
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
|
618 |
+
static void postcall(function_call &, handle) {}
|
619 |
+
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
|
620 |
+
static void precall(function_call &) {}
|
621 |
+
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
|
622 |
+
static void postcall(function_call &call, handle ret) {
|
623 |
+
keep_alive_impl(Nurse, Patient, call, ret);
|
624 |
+
}
|
625 |
+
};
|
626 |
+
|
627 |
+
/// Recursively iterate over variadic template arguments
|
628 |
+
template <typename... Args>
|
629 |
+
struct process_attributes {
|
630 |
+
static void init(const Args &...args, function_record *r) {
|
631 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
|
632 |
+
PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
|
633 |
+
using expander = int[];
|
634 |
+
(void) expander{
|
635 |
+
0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
|
636 |
+
}
|
637 |
+
static void init(const Args &...args, type_record *r) {
|
638 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
|
639 |
+
PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
|
640 |
+
using expander = int[];
|
641 |
+
(void) expander{0,
|
642 |
+
(process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
|
643 |
+
}
|
644 |
+
static void precall(function_call &call) {
|
645 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call);
|
646 |
+
using expander = int[];
|
647 |
+
(void) expander{0,
|
648 |
+
(process_attribute<typename std::decay<Args>::type>::precall(call), 0)...};
|
649 |
+
}
|
650 |
+
static void postcall(function_call &call, handle fn_ret) {
|
651 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret);
|
652 |
+
PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret);
|
653 |
+
using expander = int[];
|
654 |
+
(void) expander{
|
655 |
+
0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...};
|
656 |
+
}
|
657 |
+
};
|
658 |
+
|
659 |
+
template <typename T>
|
660 |
+
using is_call_guard = is_instantiation<call_guard, T>;
|
661 |
+
|
662 |
+
/// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
|
663 |
+
template <typename... Extra>
|
664 |
+
using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
|
665 |
+
|
666 |
+
/// Check the number of named arguments at compile time
|
667 |
+
template <typename... Extra,
|
668 |
+
size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
|
669 |
+
size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
|
670 |
+
constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
|
671 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);
|
672 |
+
return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs;
|
673 |
+
}
|
674 |
+
|
675 |
+
PYBIND11_NAMESPACE_END(detail)
|
676 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
third-party/DPVO/DPViewer/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/DPViewer/pybind11/include/pybind11/cast.h
ADDED
@@ -0,0 +1,1665 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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__" 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 |
+
handle load_src = src;
|
383 |
+
if (!src) {
|
384 |
+
return false;
|
385 |
+
}
|
386 |
+
if (!PyUnicode_Check(load_src.ptr())) {
|
387 |
+
return load_raw(load_src);
|
388 |
+
}
|
389 |
+
|
390 |
+
// For UTF-8 we avoid the need for a temporary `bytes` object by using
|
391 |
+
// `PyUnicode_AsUTF8AndSize`.
|
392 |
+
if (PYBIND11_SILENCE_MSVC_C4127(UTF_N == 8)) {
|
393 |
+
Py_ssize_t size = -1;
|
394 |
+
const auto *buffer
|
395 |
+
= reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
|
396 |
+
if (!buffer) {
|
397 |
+
PyErr_Clear();
|
398 |
+
return false;
|
399 |
+
}
|
400 |
+
value = StringType(buffer, static_cast<size_t>(size));
|
401 |
+
return true;
|
402 |
+
}
|
403 |
+
|
404 |
+
auto utfNbytes
|
405 |
+
= reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
|
406 |
+
UTF_N == 8 ? "utf-8"
|
407 |
+
: UTF_N == 16 ? "utf-16"
|
408 |
+
: "utf-32",
|
409 |
+
nullptr));
|
410 |
+
if (!utfNbytes) {
|
411 |
+
PyErr_Clear();
|
412 |
+
return false;
|
413 |
+
}
|
414 |
+
|
415 |
+
const auto *buffer
|
416 |
+
= reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
|
417 |
+
size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
|
418 |
+
// Skip BOM for UTF-16/32
|
419 |
+
if (PYBIND11_SILENCE_MSVC_C4127(UTF_N > 8)) {
|
420 |
+
buffer++;
|
421 |
+
length--;
|
422 |
+
}
|
423 |
+
value = StringType(buffer, length);
|
424 |
+
|
425 |
+
// If we're loading a string_view we need to keep the encoded Python object alive:
|
426 |
+
if (IsView) {
|
427 |
+
loader_life_support::add_patient(utfNbytes);
|
428 |
+
}
|
429 |
+
|
430 |
+
return true;
|
431 |
+
}
|
432 |
+
|
433 |
+
static handle
|
434 |
+
cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
|
435 |
+
const char *buffer = reinterpret_cast<const char *>(src.data());
|
436 |
+
auto nbytes = ssize_t(src.size() * sizeof(CharT));
|
437 |
+
handle s = decode_utfN(buffer, nbytes);
|
438 |
+
if (!s) {
|
439 |
+
throw error_already_set();
|
440 |
+
}
|
441 |
+
return s;
|
442 |
+
}
|
443 |
+
|
444 |
+
PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
|
445 |
+
|
446 |
+
private:
|
447 |
+
static handle decode_utfN(const char *buffer, ssize_t nbytes) {
|
448 |
+
#if !defined(PYPY_VERSION)
|
449 |
+
return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
|
450 |
+
: UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
|
451 |
+
: PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
|
452 |
+
#else
|
453 |
+
// PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
|
454 |
+
// well), so bypass the whole thing by just passing the encoding as a string value, which
|
455 |
+
// works properly:
|
456 |
+
return PyUnicode_Decode(buffer,
|
457 |
+
nbytes,
|
458 |
+
UTF_N == 8 ? "utf-8"
|
459 |
+
: UTF_N == 16 ? "utf-16"
|
460 |
+
: "utf-32",
|
461 |
+
nullptr);
|
462 |
+
#endif
|
463 |
+
}
|
464 |
+
|
465 |
+
// When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.
|
466 |
+
// without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
|
467 |
+
// which supports loading a unicode from a str, doesn't take this path.
|
468 |
+
template <typename C = CharT>
|
469 |
+
bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
|
470 |
+
if (PYBIND11_BYTES_CHECK(src.ptr())) {
|
471 |
+
// We were passed raw bytes; accept it into a std::string or char*
|
472 |
+
// without any encoding attempt.
|
473 |
+
const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
|
474 |
+
if (!bytes) {
|
475 |
+
pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
|
476 |
+
}
|
477 |
+
value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
|
478 |
+
return true;
|
479 |
+
}
|
480 |
+
if (PyByteArray_Check(src.ptr())) {
|
481 |
+
// We were passed a bytearray; accept it into a std::string or char*
|
482 |
+
// without any encoding attempt.
|
483 |
+
const char *bytearray = PyByteArray_AsString(src.ptr());
|
484 |
+
if (!bytearray) {
|
485 |
+
pybind11_fail("Unexpected PyByteArray_AsString() failure.");
|
486 |
+
}
|
487 |
+
value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
|
488 |
+
return true;
|
489 |
+
}
|
490 |
+
|
491 |
+
return false;
|
492 |
+
}
|
493 |
+
|
494 |
+
template <typename C = CharT>
|
495 |
+
bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
|
496 |
+
return false;
|
497 |
+
}
|
498 |
+
};
|
499 |
+
|
500 |
+
template <typename CharT, class Traits, class Allocator>
|
501 |
+
struct type_caster<std::basic_string<CharT, Traits, Allocator>,
|
502 |
+
enable_if_t<is_std_char_type<CharT>::value>>
|
503 |
+
: string_caster<std::basic_string<CharT, Traits, Allocator>> {};
|
504 |
+
|
505 |
+
#ifdef PYBIND11_HAS_STRING_VIEW
|
506 |
+
template <typename CharT, class Traits>
|
507 |
+
struct type_caster<std::basic_string_view<CharT, Traits>,
|
508 |
+
enable_if_t<is_std_char_type<CharT>::value>>
|
509 |
+
: string_caster<std::basic_string_view<CharT, Traits>, true> {};
|
510 |
+
#endif
|
511 |
+
|
512 |
+
// Type caster for C-style strings. We basically use a std::string type caster, but also add the
|
513 |
+
// ability to use None as a nullptr char* (which the string caster doesn't allow).
|
514 |
+
template <typename CharT>
|
515 |
+
struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
|
516 |
+
using StringType = std::basic_string<CharT>;
|
517 |
+
using StringCaster = make_caster<StringType>;
|
518 |
+
StringCaster str_caster;
|
519 |
+
bool none = false;
|
520 |
+
CharT one_char = 0;
|
521 |
+
|
522 |
+
public:
|
523 |
+
bool load(handle src, bool convert) {
|
524 |
+
if (!src) {
|
525 |
+
return false;
|
526 |
+
}
|
527 |
+
if (src.is_none()) {
|
528 |
+
// Defer accepting None to other overloads (if we aren't in convert mode):
|
529 |
+
if (!convert) {
|
530 |
+
return false;
|
531 |
+
}
|
532 |
+
none = true;
|
533 |
+
return true;
|
534 |
+
}
|
535 |
+
return str_caster.load(src, convert);
|
536 |
+
}
|
537 |
+
|
538 |
+
static handle cast(const CharT *src, return_value_policy policy, handle parent) {
|
539 |
+
if (src == nullptr) {
|
540 |
+
return pybind11::none().inc_ref();
|
541 |
+
}
|
542 |
+
return StringCaster::cast(StringType(src), policy, parent);
|
543 |
+
}
|
544 |
+
|
545 |
+
static handle cast(CharT src, return_value_policy policy, handle parent) {
|
546 |
+
if (std::is_same<char, CharT>::value) {
|
547 |
+
handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
|
548 |
+
if (!s) {
|
549 |
+
throw error_already_set();
|
550 |
+
}
|
551 |
+
return s;
|
552 |
+
}
|
553 |
+
return StringCaster::cast(StringType(1, src), policy, parent);
|
554 |
+
}
|
555 |
+
|
556 |
+
explicit operator CharT *() {
|
557 |
+
return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
|
558 |
+
}
|
559 |
+
explicit operator CharT &() {
|
560 |
+
if (none) {
|
561 |
+
throw value_error("Cannot convert None to a character");
|
562 |
+
}
|
563 |
+
|
564 |
+
auto &value = static_cast<StringType &>(str_caster);
|
565 |
+
size_t str_len = value.size();
|
566 |
+
if (str_len == 0) {
|
567 |
+
throw value_error("Cannot convert empty string to a character");
|
568 |
+
}
|
569 |
+
|
570 |
+
// If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
|
571 |
+
// is too high, and one for multiple unicode characters (caught later), so we need to
|
572 |
+
// figure out how long the first encoded character is in bytes to distinguish between these
|
573 |
+
// two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
|
574 |
+
// those can fit into a single char value.
|
575 |
+
if (PYBIND11_SILENCE_MSVC_C4127(StringCaster::UTF_N == 8) && str_len > 1 && str_len <= 4) {
|
576 |
+
auto v0 = static_cast<unsigned char>(value[0]);
|
577 |
+
// low bits only: 0-127
|
578 |
+
// 0b110xxxxx - start of 2-byte sequence
|
579 |
+
// 0b1110xxxx - start of 3-byte sequence
|
580 |
+
// 0b11110xxx - start of 4-byte sequence
|
581 |
+
size_t char0_bytes = (v0 & 0x80) == 0 ? 1
|
582 |
+
: (v0 & 0xE0) == 0xC0 ? 2
|
583 |
+
: (v0 & 0xF0) == 0xE0 ? 3
|
584 |
+
: 4;
|
585 |
+
|
586 |
+
if (char0_bytes == str_len) {
|
587 |
+
// If we have a 128-255 value, we can decode it into a single char:
|
588 |
+
if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
|
589 |
+
one_char = static_cast<CharT>(((v0 & 3) << 6)
|
590 |
+
+ (static_cast<unsigned char>(value[1]) & 0x3F));
|
591 |
+
return one_char;
|
592 |
+
}
|
593 |
+
// Otherwise we have a single character, but it's > U+00FF
|
594 |
+
throw value_error("Character code point not in range(0x100)");
|
595 |
+
}
|
596 |
+
}
|
597 |
+
|
598 |
+
// UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
|
599 |
+
// surrogate pair with total length 2 instantly indicates a range error (but not a "your
|
600 |
+
// string was too long" error).
|
601 |
+
else if (PYBIND11_SILENCE_MSVC_C4127(StringCaster::UTF_N == 16) && str_len == 2) {
|
602 |
+
one_char = static_cast<CharT>(value[0]);
|
603 |
+
if (one_char >= 0xD800 && one_char < 0xE000) {
|
604 |
+
throw value_error("Character code point not in range(0x10000)");
|
605 |
+
}
|
606 |
+
}
|
607 |
+
|
608 |
+
if (str_len != 1) {
|
609 |
+
throw value_error("Expected a character, but multi-character string found");
|
610 |
+
}
|
611 |
+
|
612 |
+
one_char = value[0];
|
613 |
+
return one_char;
|
614 |
+
}
|
615 |
+
|
616 |
+
static constexpr auto name = const_name(PYBIND11_STRING_NAME);
|
617 |
+
template <typename _T>
|
618 |
+
using cast_op_type = pybind11::detail::cast_op_type<_T>;
|
619 |
+
};
|
620 |
+
|
621 |
+
// Base implementation for std::tuple and std::pair
|
622 |
+
template <template <typename...> class Tuple, typename... Ts>
|
623 |
+
class tuple_caster {
|
624 |
+
using type = Tuple<Ts...>;
|
625 |
+
static constexpr auto size = sizeof...(Ts);
|
626 |
+
using indices = make_index_sequence<size>;
|
627 |
+
|
628 |
+
public:
|
629 |
+
bool load(handle src, bool convert) {
|
630 |
+
if (!isinstance<sequence>(src)) {
|
631 |
+
return false;
|
632 |
+
}
|
633 |
+
const auto seq = reinterpret_borrow<sequence>(src);
|
634 |
+
if (seq.size() != size) {
|
635 |
+
return false;
|
636 |
+
}
|
637 |
+
return load_impl(seq, convert, indices{});
|
638 |
+
}
|
639 |
+
|
640 |
+
template <typename T>
|
641 |
+
static handle cast(T &&src, return_value_policy policy, handle parent) {
|
642 |
+
return cast_impl(std::forward<T>(src), policy, parent, indices{});
|
643 |
+
}
|
644 |
+
|
645 |
+
// copied from the PYBIND11_TYPE_CASTER macro
|
646 |
+
template <typename T>
|
647 |
+
static handle cast(T *src, return_value_policy policy, handle parent) {
|
648 |
+
if (!src) {
|
649 |
+
return none().release();
|
650 |
+
}
|
651 |
+
if (policy == return_value_policy::take_ownership) {
|
652 |
+
auto h = cast(std::move(*src), policy, parent);
|
653 |
+
delete src;
|
654 |
+
return h;
|
655 |
+
}
|
656 |
+
return cast(*src, policy, parent);
|
657 |
+
}
|
658 |
+
|
659 |
+
static constexpr auto name
|
660 |
+
= const_name("Tuple[") + concat(make_caster<Ts>::name...) + const_name("]");
|
661 |
+
|
662 |
+
template <typename T>
|
663 |
+
using cast_op_type = type;
|
664 |
+
|
665 |
+
explicit operator type() & { return implicit_cast(indices{}); }
|
666 |
+
explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
|
667 |
+
|
668 |
+
protected:
|
669 |
+
template <size_t... Is>
|
670 |
+
type implicit_cast(index_sequence<Is...>) & {
|
671 |
+
return type(cast_op<Ts>(std::get<Is>(subcasters))...);
|
672 |
+
}
|
673 |
+
template <size_t... Is>
|
674 |
+
type implicit_cast(index_sequence<Is...>) && {
|
675 |
+
return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
|
676 |
+
}
|
677 |
+
|
678 |
+
static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
|
679 |
+
|
680 |
+
template <size_t... Is>
|
681 |
+
bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
|
682 |
+
#ifdef __cpp_fold_expressions
|
683 |
+
if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
|
684 |
+
return false;
|
685 |
+
}
|
686 |
+
#else
|
687 |
+
for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
|
688 |
+
if (!r) {
|
689 |
+
return false;
|
690 |
+
}
|
691 |
+
}
|
692 |
+
#endif
|
693 |
+
return true;
|
694 |
+
}
|
695 |
+
|
696 |
+
/* Implementation: Convert a C++ tuple into a Python tuple */
|
697 |
+
template <typename T, size_t... Is>
|
698 |
+
static handle
|
699 |
+
cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
|
700 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
|
701 |
+
PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
|
702 |
+
std::array<object, size> entries{{reinterpret_steal<object>(
|
703 |
+
make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
|
704 |
+
for (const auto &entry : entries) {
|
705 |
+
if (!entry) {
|
706 |
+
return handle();
|
707 |
+
}
|
708 |
+
}
|
709 |
+
tuple result(size);
|
710 |
+
int counter = 0;
|
711 |
+
for (auto &entry : entries) {
|
712 |
+
PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
|
713 |
+
}
|
714 |
+
return result.release();
|
715 |
+
}
|
716 |
+
|
717 |
+
Tuple<make_caster<Ts>...> subcasters;
|
718 |
+
};
|
719 |
+
|
720 |
+
template <typename T1, typename T2>
|
721 |
+
class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
|
722 |
+
|
723 |
+
template <typename... Ts>
|
724 |
+
class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
|
725 |
+
|
726 |
+
/// Helper class which abstracts away certain actions. Users can provide specializations for
|
727 |
+
/// custom holders, but it's only necessary if the type has a non-standard interface.
|
728 |
+
template <typename T>
|
729 |
+
struct holder_helper {
|
730 |
+
static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
|
731 |
+
};
|
732 |
+
|
733 |
+
/// Type caster for holder types like std::shared_ptr, etc.
|
734 |
+
/// The SFINAE hook is provided to help work around the current lack of support
|
735 |
+
/// for smart-pointer interoperability. Please consider it an implementation
|
736 |
+
/// detail that may change in the future, as formal support for smart-pointer
|
737 |
+
/// interoperability is added into pybind11.
|
738 |
+
template <typename type, typename holder_type, typename SFINAE = void>
|
739 |
+
struct copyable_holder_caster : public type_caster_base<type> {
|
740 |
+
public:
|
741 |
+
using base = type_caster_base<type>;
|
742 |
+
static_assert(std::is_base_of<base, type_caster<type>>::value,
|
743 |
+
"Holder classes are only supported for custom types");
|
744 |
+
using base::base;
|
745 |
+
using base::cast;
|
746 |
+
using base::typeinfo;
|
747 |
+
using base::value;
|
748 |
+
|
749 |
+
bool load(handle src, bool convert) {
|
750 |
+
return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
|
751 |
+
}
|
752 |
+
|
753 |
+
explicit operator type *() { return this->value; }
|
754 |
+
// static_cast works around compiler error with MSVC 17 and CUDA 10.2
|
755 |
+
// see issue #2180
|
756 |
+
explicit operator type &() { return *(static_cast<type *>(this->value)); }
|
757 |
+
explicit operator holder_type *() { return std::addressof(holder); }
|
758 |
+
explicit operator holder_type &() { return holder; }
|
759 |
+
|
760 |
+
static handle cast(const holder_type &src, return_value_policy, handle) {
|
761 |
+
const auto *ptr = holder_helper<holder_type>::get(src);
|
762 |
+
return type_caster_base<type>::cast_holder(ptr, &src);
|
763 |
+
}
|
764 |
+
|
765 |
+
protected:
|
766 |
+
friend class type_caster_generic;
|
767 |
+
void check_holder_compat() {
|
768 |
+
if (typeinfo->default_holder) {
|
769 |
+
throw cast_error("Unable to load a custom holder type from a default-holder instance");
|
770 |
+
}
|
771 |
+
}
|
772 |
+
|
773 |
+
bool load_value(value_and_holder &&v_h) {
|
774 |
+
if (v_h.holder_constructed()) {
|
775 |
+
value = v_h.value_ptr();
|
776 |
+
holder = v_h.template holder<holder_type>();
|
777 |
+
return true;
|
778 |
+
}
|
779 |
+
throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
|
780 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
781 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
|
782 |
+
"type information)");
|
783 |
+
#else
|
784 |
+
"of type '"
|
785 |
+
+ type_id<holder_type>() + "''");
|
786 |
+
#endif
|
787 |
+
}
|
788 |
+
|
789 |
+
template <typename T = holder_type,
|
790 |
+
detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
|
791 |
+
bool try_implicit_casts(handle, bool) {
|
792 |
+
return false;
|
793 |
+
}
|
794 |
+
|
795 |
+
template <typename T = holder_type,
|
796 |
+
detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
|
797 |
+
bool try_implicit_casts(handle src, bool convert) {
|
798 |
+
for (auto &cast : typeinfo->implicit_casts) {
|
799 |
+
copyable_holder_caster sub_caster(*cast.first);
|
800 |
+
if (sub_caster.load(src, convert)) {
|
801 |
+
value = cast.second(sub_caster.value);
|
802 |
+
holder = holder_type(sub_caster.holder, (type *) value);
|
803 |
+
return true;
|
804 |
+
}
|
805 |
+
}
|
806 |
+
return false;
|
807 |
+
}
|
808 |
+
|
809 |
+
static bool try_direct_conversions(handle) { return false; }
|
810 |
+
|
811 |
+
holder_type holder;
|
812 |
+
};
|
813 |
+
|
814 |
+
/// Specialize for the common std::shared_ptr, so users don't need to
|
815 |
+
template <typename T>
|
816 |
+
class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
|
817 |
+
|
818 |
+
/// Type caster for holder types like std::unique_ptr.
|
819 |
+
/// Please consider the SFINAE hook an implementation detail, as explained
|
820 |
+
/// in the comment for the copyable_holder_caster.
|
821 |
+
template <typename type, typename holder_type, typename SFINAE = void>
|
822 |
+
struct move_only_holder_caster {
|
823 |
+
static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
|
824 |
+
"Holder classes are only supported for custom types");
|
825 |
+
|
826 |
+
static handle cast(holder_type &&src, return_value_policy, handle) {
|
827 |
+
auto *ptr = holder_helper<holder_type>::get(src);
|
828 |
+
return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
|
829 |
+
}
|
830 |
+
static constexpr auto name = type_caster_base<type>::name;
|
831 |
+
};
|
832 |
+
|
833 |
+
template <typename type, typename deleter>
|
834 |
+
class type_caster<std::unique_ptr<type, deleter>>
|
835 |
+
: public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
|
836 |
+
|
837 |
+
template <typename type, typename holder_type>
|
838 |
+
using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
|
839 |
+
copyable_holder_caster<type, holder_type>,
|
840 |
+
move_only_holder_caster<type, holder_type>>;
|
841 |
+
|
842 |
+
template <typename T, bool Value = false>
|
843 |
+
struct always_construct_holder {
|
844 |
+
static constexpr bool value = Value;
|
845 |
+
};
|
846 |
+
|
847 |
+
/// Create a specialization for custom holder types (silently ignores std::shared_ptr)
|
848 |
+
#define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
|
849 |
+
namespace pybind11 { \
|
850 |
+
namespace detail { \
|
851 |
+
template <typename type> \
|
852 |
+
struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { \
|
853 |
+
}; \
|
854 |
+
template <typename type> \
|
855 |
+
class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
|
856 |
+
: public type_caster_holder<type, holder_type> {}; \
|
857 |
+
} \
|
858 |
+
}
|
859 |
+
|
860 |
+
// PYBIND11_DECLARE_HOLDER_TYPE holder types:
|
861 |
+
template <typename base, typename holder>
|
862 |
+
struct is_holder_type
|
863 |
+
: std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
|
864 |
+
// Specialization for always-supported unique_ptr holders:
|
865 |
+
template <typename base, typename deleter>
|
866 |
+
struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
|
867 |
+
|
868 |
+
template <typename T>
|
869 |
+
struct handle_type_name {
|
870 |
+
static constexpr auto name = const_name<T>();
|
871 |
+
};
|
872 |
+
template <>
|
873 |
+
struct handle_type_name<bool_> {
|
874 |
+
static constexpr auto name = const_name("bool");
|
875 |
+
};
|
876 |
+
template <>
|
877 |
+
struct handle_type_name<bytes> {
|
878 |
+
static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
|
879 |
+
};
|
880 |
+
template <>
|
881 |
+
struct handle_type_name<int_> {
|
882 |
+
static constexpr auto name = const_name("int");
|
883 |
+
};
|
884 |
+
template <>
|
885 |
+
struct handle_type_name<iterable> {
|
886 |
+
static constexpr auto name = const_name("Iterable");
|
887 |
+
};
|
888 |
+
template <>
|
889 |
+
struct handle_type_name<iterator> {
|
890 |
+
static constexpr auto name = const_name("Iterator");
|
891 |
+
};
|
892 |
+
template <>
|
893 |
+
struct handle_type_name<float_> {
|
894 |
+
static constexpr auto name = const_name("float");
|
895 |
+
};
|
896 |
+
template <>
|
897 |
+
struct handle_type_name<none> {
|
898 |
+
static constexpr auto name = const_name("None");
|
899 |
+
};
|
900 |
+
template <>
|
901 |
+
struct handle_type_name<args> {
|
902 |
+
static constexpr auto name = const_name("*args");
|
903 |
+
};
|
904 |
+
template <>
|
905 |
+
struct handle_type_name<kwargs> {
|
906 |
+
static constexpr auto name = const_name("**kwargs");
|
907 |
+
};
|
908 |
+
|
909 |
+
template <typename type>
|
910 |
+
struct pyobject_caster {
|
911 |
+
template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
|
912 |
+
pyobject_caster() : value() {}
|
913 |
+
|
914 |
+
// `type` may not be default constructible (e.g. frozenset, anyset). Initializing `value`
|
915 |
+
// to a nil handle is safe since it will only be accessed if `load` succeeds.
|
916 |
+
template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
|
917 |
+
pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
|
918 |
+
|
919 |
+
template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
|
920 |
+
bool load(handle src, bool /* convert */) {
|
921 |
+
value = src;
|
922 |
+
return static_cast<bool>(value);
|
923 |
+
}
|
924 |
+
|
925 |
+
template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
|
926 |
+
bool load(handle src, bool /* convert */) {
|
927 |
+
if (!isinstance<type>(src)) {
|
928 |
+
return false;
|
929 |
+
}
|
930 |
+
value = reinterpret_borrow<type>(src);
|
931 |
+
return true;
|
932 |
+
}
|
933 |
+
|
934 |
+
static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
|
935 |
+
return src.inc_ref();
|
936 |
+
}
|
937 |
+
PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
|
938 |
+
};
|
939 |
+
|
940 |
+
template <typename T>
|
941 |
+
class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
|
942 |
+
|
943 |
+
// Our conditions for enabling moving are quite restrictive:
|
944 |
+
// At compile time:
|
945 |
+
// - T needs to be a non-const, non-pointer, non-reference type
|
946 |
+
// - type_caster<T>::operator T&() must exist
|
947 |
+
// - the type must be move constructible (obviously)
|
948 |
+
// At run-time:
|
949 |
+
// - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
|
950 |
+
// must have ref_count() == 1)h
|
951 |
+
// If any of the above are not satisfied, we fall back to copying.
|
952 |
+
template <typename T>
|
953 |
+
using move_is_plain_type
|
954 |
+
= satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
|
955 |
+
template <typename T, typename SFINAE = void>
|
956 |
+
struct move_always : std::false_type {};
|
957 |
+
template <typename T>
|
958 |
+
struct move_always<
|
959 |
+
T,
|
960 |
+
enable_if_t<
|
961 |
+
all_of<move_is_plain_type<T>,
|
962 |
+
negation<is_copy_constructible<T>>,
|
963 |
+
std::is_move_constructible<T>,
|
964 |
+
std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
|
965 |
+
: std::true_type {};
|
966 |
+
template <typename T, typename SFINAE = void>
|
967 |
+
struct move_if_unreferenced : std::false_type {};
|
968 |
+
template <typename T>
|
969 |
+
struct move_if_unreferenced<
|
970 |
+
T,
|
971 |
+
enable_if_t<
|
972 |
+
all_of<move_is_plain_type<T>,
|
973 |
+
negation<move_always<T>>,
|
974 |
+
std::is_move_constructible<T>,
|
975 |
+
std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
|
976 |
+
: std::true_type {};
|
977 |
+
template <typename T>
|
978 |
+
using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
|
979 |
+
|
980 |
+
// Detect whether returning a `type` from a cast on type's type_caster is going to result in a
|
981 |
+
// reference or pointer to a local variable of the type_caster. Basically, only
|
982 |
+
// non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
|
983 |
+
// everything else returns a reference/pointer to a local variable.
|
984 |
+
template <typename type>
|
985 |
+
using cast_is_temporary_value_reference
|
986 |
+
= bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
|
987 |
+
&& !std::is_base_of<type_caster_generic, make_caster<type>>::value
|
988 |
+
&& !std::is_same<intrinsic_t<type>, void>::value>;
|
989 |
+
|
990 |
+
// When a value returned from a C++ function is being cast back to Python, we almost always want to
|
991 |
+
// force `policy = move`, regardless of the return value policy the function/method was declared
|
992 |
+
// with.
|
993 |
+
template <typename Return, typename SFINAE = void>
|
994 |
+
struct return_value_policy_override {
|
995 |
+
static return_value_policy policy(return_value_policy p) { return p; }
|
996 |
+
};
|
997 |
+
|
998 |
+
template <typename Return>
|
999 |
+
struct return_value_policy_override<
|
1000 |
+
Return,
|
1001 |
+
detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
|
1002 |
+
static return_value_policy policy(return_value_policy p) {
|
1003 |
+
return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
|
1004 |
+
? return_value_policy::move
|
1005 |
+
: p;
|
1006 |
+
}
|
1007 |
+
};
|
1008 |
+
|
1009 |
+
// Basic python -> C++ casting; throws if casting fails
|
1010 |
+
template <typename T, typename SFINAE>
|
1011 |
+
type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
|
1012 |
+
static_assert(!detail::is_pyobject<T>::value,
|
1013 |
+
"Internal error: type_caster should only be used for C++ types");
|
1014 |
+
if (!conv.load(handle, true)) {
|
1015 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1016 |
+
throw cast_error("Unable to cast Python instance to C++ type (#define "
|
1017 |
+
"PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
|
1018 |
+
#else
|
1019 |
+
throw cast_error("Unable to cast Python instance of type "
|
1020 |
+
+ (std::string) str(type::handle_of(handle)) + " to C++ type '"
|
1021 |
+
+ type_id<T>() + "'");
|
1022 |
+
#endif
|
1023 |
+
}
|
1024 |
+
return conv;
|
1025 |
+
}
|
1026 |
+
// Wrapper around the above that also constructs and returns a type_caster
|
1027 |
+
template <typename T>
|
1028 |
+
make_caster<T> load_type(const handle &handle) {
|
1029 |
+
make_caster<T> conv;
|
1030 |
+
load_type(conv, handle);
|
1031 |
+
return conv;
|
1032 |
+
}
|
1033 |
+
|
1034 |
+
PYBIND11_NAMESPACE_END(detail)
|
1035 |
+
|
1036 |
+
// pytype -> C++ type
|
1037 |
+
template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
|
1038 |
+
T cast(const handle &handle) {
|
1039 |
+
using namespace detail;
|
1040 |
+
static_assert(!cast_is_temporary_value_reference<T>::value,
|
1041 |
+
"Unable to cast type to reference: value is local to type caster");
|
1042 |
+
return cast_op<T>(load_type<T>(handle));
|
1043 |
+
}
|
1044 |
+
|
1045 |
+
// pytype -> pytype (calls converting constructor)
|
1046 |
+
template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
|
1047 |
+
T cast(const handle &handle) {
|
1048 |
+
return T(reinterpret_borrow<object>(handle));
|
1049 |
+
}
|
1050 |
+
|
1051 |
+
// C++ type -> py::object
|
1052 |
+
template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
|
1053 |
+
object cast(T &&value,
|
1054 |
+
return_value_policy policy = return_value_policy::automatic_reference,
|
1055 |
+
handle parent = handle()) {
|
1056 |
+
using no_ref_T = typename std::remove_reference<T>::type;
|
1057 |
+
if (policy == return_value_policy::automatic) {
|
1058 |
+
policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
|
1059 |
+
: std::is_lvalue_reference<T>::value ? return_value_policy::copy
|
1060 |
+
: return_value_policy::move;
|
1061 |
+
} else if (policy == return_value_policy::automatic_reference) {
|
1062 |
+
policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
|
1063 |
+
: std::is_lvalue_reference<T>::value ? return_value_policy::copy
|
1064 |
+
: return_value_policy::move;
|
1065 |
+
}
|
1066 |
+
return reinterpret_steal<object>(
|
1067 |
+
detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
|
1068 |
+
}
|
1069 |
+
|
1070 |
+
template <typename T>
|
1071 |
+
T handle::cast() const {
|
1072 |
+
return pybind11::cast<T>(*this);
|
1073 |
+
}
|
1074 |
+
template <>
|
1075 |
+
inline void handle::cast() const {
|
1076 |
+
return;
|
1077 |
+
}
|
1078 |
+
|
1079 |
+
template <typename T>
|
1080 |
+
detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
|
1081 |
+
if (obj.ref_count() > 1) {
|
1082 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1083 |
+
throw cast_error(
|
1084 |
+
"Unable to cast Python instance to C++ rvalue: instance has multiple references"
|
1085 |
+
" (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
|
1086 |
+
#else
|
1087 |
+
throw cast_error("Unable to move from Python " + (std::string) str(type::handle_of(obj))
|
1088 |
+
+ " instance to C++ " + type_id<T>()
|
1089 |
+
+ " instance: instance has multiple references");
|
1090 |
+
#endif
|
1091 |
+
}
|
1092 |
+
|
1093 |
+
// Move into a temporary and return that, because the reference may be a local value of `conv`
|
1094 |
+
T ret = std::move(detail::load_type<T>(obj).operator T &());
|
1095 |
+
return ret;
|
1096 |
+
}
|
1097 |
+
|
1098 |
+
// Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
|
1099 |
+
// - If we have to move (because T has no copy constructor), do it. This will fail if the moved
|
1100 |
+
// object has multiple references, but trying to copy will fail to compile.
|
1101 |
+
// - If both movable and copyable, check ref count: if 1, move; otherwise copy
|
1102 |
+
// - Otherwise (not movable), copy.
|
1103 |
+
template <typename T>
|
1104 |
+
detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
|
1105 |
+
cast(object &&object) {
|
1106 |
+
return move<T>(std::move(object));
|
1107 |
+
}
|
1108 |
+
template <typename T>
|
1109 |
+
detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
|
1110 |
+
cast(object &&object) {
|
1111 |
+
if (object.ref_count() > 1) {
|
1112 |
+
return cast<T>(object);
|
1113 |
+
}
|
1114 |
+
return move<T>(std::move(object));
|
1115 |
+
}
|
1116 |
+
template <typename T>
|
1117 |
+
detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
|
1118 |
+
cast(object &&object) {
|
1119 |
+
return cast<T>(object);
|
1120 |
+
}
|
1121 |
+
|
1122 |
+
// pytype rvalue -> pytype (calls converting constructor)
|
1123 |
+
template <typename T>
|
1124 |
+
detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
|
1125 |
+
return T(std::move(object));
|
1126 |
+
}
|
1127 |
+
|
1128 |
+
template <typename T>
|
1129 |
+
T object::cast() const & {
|
1130 |
+
return pybind11::cast<T>(*this);
|
1131 |
+
}
|
1132 |
+
template <typename T>
|
1133 |
+
T object::cast() && {
|
1134 |
+
return pybind11::cast<T>(std::move(*this));
|
1135 |
+
}
|
1136 |
+
template <>
|
1137 |
+
inline void object::cast() const & {
|
1138 |
+
return;
|
1139 |
+
}
|
1140 |
+
template <>
|
1141 |
+
inline void object::cast() && {
|
1142 |
+
return;
|
1143 |
+
}
|
1144 |
+
|
1145 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
1146 |
+
|
1147 |
+
// Declared in pytypes.h:
|
1148 |
+
template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
|
1149 |
+
object object_or_cast(T &&o) {
|
1150 |
+
return pybind11::cast(std::forward<T>(o));
|
1151 |
+
}
|
1152 |
+
|
1153 |
+
// Placeholder type for the unneeded (and dead code) static variable in the
|
1154 |
+
// PYBIND11_OVERRIDE_OVERRIDE macro
|
1155 |
+
struct override_unused {};
|
1156 |
+
template <typename ret_type>
|
1157 |
+
using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
|
1158 |
+
make_caster<ret_type>,
|
1159 |
+
override_unused>;
|
1160 |
+
|
1161 |
+
// Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
|
1162 |
+
// store the result in the given variable. For other types, this is a no-op.
|
1163 |
+
template <typename T>
|
1164 |
+
enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
|
1165 |
+
make_caster<T> &caster) {
|
1166 |
+
return cast_op<T>(load_type(caster, o));
|
1167 |
+
}
|
1168 |
+
template <typename T>
|
1169 |
+
enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
|
1170 |
+
override_unused &) {
|
1171 |
+
pybind11_fail("Internal error: cast_ref fallback invoked");
|
1172 |
+
}
|
1173 |
+
|
1174 |
+
// Trampoline use: Having a pybind11::cast with an invalid reference type is going to
|
1175 |
+
// static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
|
1176 |
+
// that only does anything in cases where pybind11::cast is valid.
|
1177 |
+
template <typename T>
|
1178 |
+
enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
|
1179 |
+
pybind11_fail("Internal error: cast_safe fallback invoked");
|
1180 |
+
}
|
1181 |
+
template <typename T>
|
1182 |
+
enable_if_t<std::is_same<void, intrinsic_t<T>>::value, void> cast_safe(object &&) {}
|
1183 |
+
template <typename T>
|
1184 |
+
enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>,
|
1185 |
+
std::is_same<void, intrinsic_t<T>>>::value,
|
1186 |
+
T>
|
1187 |
+
cast_safe(object &&o) {
|
1188 |
+
return pybind11::cast<T>(std::move(o));
|
1189 |
+
}
|
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(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1196 |
+
inline cast_error cast_error_unable_to_convert_call_arg() {
|
1197 |
+
return cast_error("Unable to convert call argument to Python object (#define "
|
1198 |
+
"PYBIND11_DETAILED_ERROR_MESSAGES or 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(PYBIND11_DETAILED_ERROR_MESSAGES)
|
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>(detail::make_caster<T>::cast(
|
1270 |
+
std::forward<T>(x), return_value_policy::automatic, {}))),
|
1271 |
+
descr(descr)
|
1272 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
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(PYBIND11_DETAILED_ERROR_MESSAGES)
|
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
|
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(PYBIND11_DETAILED_ERROR_MESSAGES)
|
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(std::move(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(PYBIND11_DETAILED_ERROR_MESSAGES)
|
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(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1536 |
+
multiple_values_error();
|
1537 |
+
#else
|
1538 |
+
multiple_values_error(a.name);
|
1539 |
+
#endif
|
1540 |
+
}
|
1541 |
+
if (!a.value) {
|
1542 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
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(PYBIND11_DETAILED_ERROR_MESSAGES)
|
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(
|
1569 |
+
"Got kwargs without a name; only named arguments "
|
1570 |
+
"may be passed via py::arg() to a python function call. "
|
1571 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
|
1572 |
+
}
|
1573 |
+
[[noreturn]] static void nameless_argument_error(const std::string &type) {
|
1574 |
+
throw type_error("Got kwargs without a name of type '" + type
|
1575 |
+
+ "'; only named "
|
1576 |
+
"arguments may be passed via py::arg() to a python function call. ");
|
1577 |
+
}
|
1578 |
+
[[noreturn]] static void multiple_values_error() {
|
1579 |
+
throw type_error(
|
1580 |
+
"Got multiple values for keyword argument "
|
1581 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
|
1582 |
+
}
|
1583 |
+
|
1584 |
+
[[noreturn]] static void multiple_values_error(const std::string &name) {
|
1585 |
+
throw type_error("Got multiple values for keyword argument '" + name + "'");
|
1586 |
+
}
|
1587 |
+
|
1588 |
+
private:
|
1589 |
+
tuple m_args;
|
1590 |
+
dict m_kwargs;
|
1591 |
+
};
|
1592 |
+
|
1593 |
+
// [workaround(intel)] Separate function required here
|
1594 |
+
// We need to put this into a separate function because the Intel compiler
|
1595 |
+
// fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
|
1596 |
+
// (tested with ICC 2021.1 Beta 20200827).
|
1597 |
+
template <typename... Args>
|
1598 |
+
constexpr bool args_are_all_positional() {
|
1599 |
+
return all_of<is_positional<Args>...>::value;
|
1600 |
+
}
|
1601 |
+
|
1602 |
+
/// Collect only positional arguments for a Python function call
|
1603 |
+
template <return_value_policy policy,
|
1604 |
+
typename... Args,
|
1605 |
+
typename = enable_if_t<args_are_all_positional<Args...>()>>
|
1606 |
+
simple_collector<policy> collect_arguments(Args &&...args) {
|
1607 |
+
return simple_collector<policy>(std::forward<Args>(args)...);
|
1608 |
+
}
|
1609 |
+
|
1610 |
+
/// Collect all arguments, including keywords and unpacking (only instantiated when needed)
|
1611 |
+
template <return_value_policy policy,
|
1612 |
+
typename... Args,
|
1613 |
+
typename = enable_if_t<!args_are_all_positional<Args...>()>>
|
1614 |
+
unpacking_collector<policy> collect_arguments(Args &&...args) {
|
1615 |
+
// Following argument order rules for generalized unpacking according to PEP 448
|
1616 |
+
static_assert(constexpr_last<is_positional, Args...>()
|
1617 |
+
< constexpr_first<is_keyword_or_ds, Args...>()
|
1618 |
+
&& constexpr_last<is_s_unpacking, Args...>()
|
1619 |
+
< constexpr_first<is_ds_unpacking, Args...>(),
|
1620 |
+
"Invalid function call: positional args must precede keywords and ** unpacking; "
|
1621 |
+
"* unpacking must precede ** unpacking");
|
1622 |
+
return unpacking_collector<policy>(std::forward<Args>(args)...);
|
1623 |
+
}
|
1624 |
+
|
1625 |
+
template <typename Derived>
|
1626 |
+
template <return_value_policy policy, typename... Args>
|
1627 |
+
object object_api<Derived>::operator()(Args &&...args) const {
|
1628 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1629 |
+
if (!PyGILState_Check()) {
|
1630 |
+
pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
|
1631 |
+
}
|
1632 |
+
#endif
|
1633 |
+
return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
|
1634 |
+
}
|
1635 |
+
|
1636 |
+
template <typename Derived>
|
1637 |
+
template <return_value_policy policy, typename... Args>
|
1638 |
+
object object_api<Derived>::call(Args &&...args) const {
|
1639 |
+
return operator()<policy>(std::forward<Args>(args)...);
|
1640 |
+
}
|
1641 |
+
|
1642 |
+
PYBIND11_NAMESPACE_END(detail)
|
1643 |
+
|
1644 |
+
template <typename T>
|
1645 |
+
handle type::handle_of() {
|
1646 |
+
static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
|
1647 |
+
"py::type::of<T> only supports the case where T is a registered C++ types.");
|
1648 |
+
|
1649 |
+
return detail::get_type_handle(typeid(T), true);
|
1650 |
+
}
|
1651 |
+
|
1652 |
+
#define PYBIND11_MAKE_OPAQUE(...) \
|
1653 |
+
namespace pybind11 { \
|
1654 |
+
namespace detail { \
|
1655 |
+
template <> \
|
1656 |
+
class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
|
1657 |
+
} \
|
1658 |
+
}
|
1659 |
+
|
1660 |
+
/// Lets you pass a type containing a `,` through a macro parameter without needing a separate
|
1661 |
+
/// typedef, e.g.:
|
1662 |
+
/// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
|
1663 |
+
#define PYBIND11_TYPE(...) __VA_ARGS__
|
1664 |
+
|
1665 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
third-party/DPVO/DPViewer/pybind11/include/pybind11/chrono.h
ADDED
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
22 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
23 |
+
|
24 |
+
template <typename type>
|
25 |
+
class duration_caster {
|
26 |
+
public:
|
27 |
+
using rep = typename type::rep;
|
28 |
+
using period = typename type::period;
|
29 |
+
|
30 |
+
// signed 25 bits required by the standard.
|
31 |
+
using days = std::chrono::duration<int_least32_t, std::ratio<86400>>;
|
32 |
+
|
33 |
+
bool load(handle src, bool) {
|
34 |
+
using namespace std::chrono;
|
35 |
+
|
36 |
+
// Lazy initialise the PyDateTime import
|
37 |
+
if (!PyDateTimeAPI) {
|
38 |
+
PyDateTime_IMPORT;
|
39 |
+
}
|
40 |
+
|
41 |
+
if (!src) {
|
42 |
+
return false;
|
43 |
+
}
|
44 |
+
// If invoked with datetime.delta object
|
45 |
+
if (PyDelta_Check(src.ptr())) {
|
46 |
+
value = type(duration_cast<duration<rep, period>>(
|
47 |
+
days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
|
48 |
+
+ seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
|
49 |
+
+ microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
|
50 |
+
return true;
|
51 |
+
}
|
52 |
+
// If invoked with a float we assume it is seconds and convert
|
53 |
+
if (PyFloat_Check(src.ptr())) {
|
54 |
+
value = type(duration_cast<duration<rep, period>>(
|
55 |
+
duration<double>(PyFloat_AsDouble(src.ptr()))));
|
56 |
+
return true;
|
57 |
+
}
|
58 |
+
return false;
|
59 |
+
}
|
60 |
+
|
61 |
+
// If this is a duration just return it back
|
62 |
+
static const std::chrono::duration<rep, period> &
|
63 |
+
get_duration(const std::chrono::duration<rep, period> &src) {
|
64 |
+
return src;
|
65 |
+
}
|
66 |
+
|
67 |
+
// If this is a time_point get the time_since_epoch
|
68 |
+
template <typename Clock>
|
69 |
+
static std::chrono::duration<rep, period>
|
70 |
+
get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
|
71 |
+
return src.time_since_epoch();
|
72 |
+
}
|
73 |
+
|
74 |
+
static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
|
75 |
+
using namespace std::chrono;
|
76 |
+
|
77 |
+
// Use overloaded function to get our duration from our source
|
78 |
+
// Works out if it is a duration or time_point and get the duration
|
79 |
+
auto d = get_duration(src);
|
80 |
+
|
81 |
+
// Lazy initialise the PyDateTime import
|
82 |
+
if (!PyDateTimeAPI) {
|
83 |
+
PyDateTime_IMPORT;
|
84 |
+
}
|
85 |
+
|
86 |
+
// Declare these special duration types so the conversions happen with the correct
|
87 |
+
// primitive types (int)
|
88 |
+
using dd_t = duration<int, std::ratio<86400>>;
|
89 |
+
using ss_t = duration<int, std::ratio<1>>;
|
90 |
+
using us_t = duration<int, std::micro>;
|
91 |
+
|
92 |
+
auto dd = duration_cast<dd_t>(d);
|
93 |
+
auto subd = d - dd;
|
94 |
+
auto ss = duration_cast<ss_t>(subd);
|
95 |
+
auto us = duration_cast<us_t>(subd - ss);
|
96 |
+
return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
|
97 |
+
}
|
98 |
+
|
99 |
+
PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta"));
|
100 |
+
};
|
101 |
+
|
102 |
+
inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
|
103 |
+
#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
|
104 |
+
if (localtime_s(buf, time))
|
105 |
+
return nullptr;
|
106 |
+
return buf;
|
107 |
+
#else
|
108 |
+
static std::mutex mtx;
|
109 |
+
std::lock_guard<std::mutex> lock(mtx);
|
110 |
+
std::tm *tm_ptr = std::localtime(time);
|
111 |
+
if (tm_ptr != nullptr) {
|
112 |
+
*buf = *tm_ptr;
|
113 |
+
}
|
114 |
+
return tm_ptr;
|
115 |
+
#endif
|
116 |
+
}
|
117 |
+
|
118 |
+
// This is for casting times on the system clock into datetime.datetime instances
|
119 |
+
template <typename Duration>
|
120 |
+
class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
|
121 |
+
public:
|
122 |
+
using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
|
123 |
+
bool load(handle src, bool) {
|
124 |
+
using namespace std::chrono;
|
125 |
+
|
126 |
+
// Lazy initialise the PyDateTime import
|
127 |
+
if (!PyDateTimeAPI) {
|
128 |
+
PyDateTime_IMPORT;
|
129 |
+
}
|
130 |
+
|
131 |
+
if (!src) {
|
132 |
+
return false;
|
133 |
+
}
|
134 |
+
|
135 |
+
std::tm cal;
|
136 |
+
microseconds msecs;
|
137 |
+
|
138 |
+
if (PyDateTime_Check(src.ptr())) {
|
139 |
+
cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
|
140 |
+
cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
|
141 |
+
cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
|
142 |
+
cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
|
143 |
+
cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
|
144 |
+
cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
|
145 |
+
cal.tm_isdst = -1;
|
146 |
+
msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
|
147 |
+
} else if (PyDate_Check(src.ptr())) {
|
148 |
+
cal.tm_sec = 0;
|
149 |
+
cal.tm_min = 0;
|
150 |
+
cal.tm_hour = 0;
|
151 |
+
cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
|
152 |
+
cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
|
153 |
+
cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
|
154 |
+
cal.tm_isdst = -1;
|
155 |
+
msecs = microseconds(0);
|
156 |
+
} else if (PyTime_Check(src.ptr())) {
|
157 |
+
cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
|
158 |
+
cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
|
159 |
+
cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
|
160 |
+
cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
|
161 |
+
cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
|
162 |
+
cal.tm_year = 70; // earliest available date for Python's datetime
|
163 |
+
cal.tm_isdst = -1;
|
164 |
+
msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
|
165 |
+
} else {
|
166 |
+
return false;
|
167 |
+
}
|
168 |
+
|
169 |
+
value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
|
170 |
+
return true;
|
171 |
+
}
|
172 |
+
|
173 |
+
static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,
|
174 |
+
return_value_policy /* policy */,
|
175 |
+
handle /* parent */) {
|
176 |
+
using namespace std::chrono;
|
177 |
+
|
178 |
+
// Lazy initialise the PyDateTime import
|
179 |
+
if (!PyDateTimeAPI) {
|
180 |
+
PyDateTime_IMPORT;
|
181 |
+
}
|
182 |
+
|
183 |
+
// Get out microseconds, and make sure they are positive, to avoid bug in eastern
|
184 |
+
// hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)
|
185 |
+
using us_t = duration<int, std::micro>;
|
186 |
+
auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
|
187 |
+
if (us.count() < 0) {
|
188 |
+
us += seconds(1);
|
189 |
+
}
|
190 |
+
|
191 |
+
// Subtract microseconds BEFORE `system_clock::to_time_t`, because:
|
192 |
+
// > If std::time_t has lower precision, it is implementation-defined whether the value is
|
193 |
+
// rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
|
194 |
+
std::time_t tt
|
195 |
+
= system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
|
196 |
+
|
197 |
+
std::tm localtime;
|
198 |
+
std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
|
199 |
+
if (!localtime_ptr) {
|
200 |
+
throw cast_error("Unable to represent system_clock in local time");
|
201 |
+
}
|
202 |
+
return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
|
203 |
+
localtime.tm_mon + 1,
|
204 |
+
localtime.tm_mday,
|
205 |
+
localtime.tm_hour,
|
206 |
+
localtime.tm_min,
|
207 |
+
localtime.tm_sec,
|
208 |
+
us.count());
|
209 |
+
}
|
210 |
+
PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime"));
|
211 |
+
};
|
212 |
+
|
213 |
+
// Other clocks that are not the system clock are not measured as datetime.datetime objects
|
214 |
+
// since they are not measured on calendar time. So instead we just make them timedeltas
|
215 |
+
// Or if they have passed us a time as a float we convert that
|
216 |
+
template <typename Clock, typename Duration>
|
217 |
+
class type_caster<std::chrono::time_point<Clock, Duration>>
|
218 |
+
: public duration_caster<std::chrono::time_point<Clock, Duration>> {};
|
219 |
+
|
220 |
+
template <typename Rep, typename Period>
|
221 |
+
class type_caster<std::chrono::duration<Rep, Period>>
|
222 |
+
: public duration_caster<std::chrono::duration<Rep, Period>> {};
|
223 |
+
|
224 |
+
PYBIND11_NAMESPACE_END(detail)
|
225 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
third-party/DPVO/DPViewer/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/DPViewer/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/DPViewer/pybind11/include/pybind11/detail/class.h
ADDED
@@ -0,0 +1,734 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 !defined(PYPY_VERSION)
|
19 |
+
# define PYBIND11_BUILTIN_QUALNAME
|
20 |
+
# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
|
21 |
+
#else
|
22 |
+
// In PyPy, we still set __qualname__ so that we can produce reliable function type
|
23 |
+
// signatures; in CPython 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 |
+
/**
|
159 |
+
* Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
|
160 |
+
* methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
|
161 |
+
* when called on a class, or a PyMethod, when called on an instance. Override that behaviour here
|
162 |
+
* to do a special case bypass for PyInstanceMethod_Types.
|
163 |
+
*/
|
164 |
+
extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
|
165 |
+
PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
|
166 |
+
if (descr && PyInstanceMethod_Check(descr)) {
|
167 |
+
Py_INCREF(descr);
|
168 |
+
return descr;
|
169 |
+
}
|
170 |
+
return PyType_Type.tp_getattro(obj, name);
|
171 |
+
}
|
172 |
+
|
173 |
+
/// metaclass `__call__` function that is used to create all pybind11 objects.
|
174 |
+
extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
|
175 |
+
|
176 |
+
// use the default metaclass call to create/initialize the object
|
177 |
+
PyObject *self = PyType_Type.tp_call(type, args, kwargs);
|
178 |
+
if (self == nullptr) {
|
179 |
+
return nullptr;
|
180 |
+
}
|
181 |
+
|
182 |
+
// This must be a pybind11 instance
|
183 |
+
auto *instance = reinterpret_cast<detail::instance *>(self);
|
184 |
+
|
185 |
+
// Ensure that the base __init__ function(s) were called
|
186 |
+
for (const auto &vh : values_and_holders(instance)) {
|
187 |
+
if (!vh.holder_constructed()) {
|
188 |
+
PyErr_Format(PyExc_TypeError,
|
189 |
+
"%.200s.__init__() must be called when overriding __init__",
|
190 |
+
get_fully_qualified_tp_name(vh.type->type).c_str());
|
191 |
+
Py_DECREF(self);
|
192 |
+
return nullptr;
|
193 |
+
}
|
194 |
+
}
|
195 |
+
|
196 |
+
return self;
|
197 |
+
}
|
198 |
+
|
199 |
+
/// Cleanup the type-info for a pybind11-registered type.
|
200 |
+
extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
|
201 |
+
auto *type = (PyTypeObject *) obj;
|
202 |
+
auto &internals = get_internals();
|
203 |
+
|
204 |
+
// A pybind11-registered type will:
|
205 |
+
// 1) be found in internals.registered_types_py
|
206 |
+
// 2) have exactly one associated `detail::type_info`
|
207 |
+
auto found_type = internals.registered_types_py.find(type);
|
208 |
+
if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
|
209 |
+
&& found_type->second[0]->type == type) {
|
210 |
+
|
211 |
+
auto *tinfo = found_type->second[0];
|
212 |
+
auto tindex = std::type_index(*tinfo->cpptype);
|
213 |
+
internals.direct_conversions.erase(tindex);
|
214 |
+
|
215 |
+
if (tinfo->module_local) {
|
216 |
+
get_local_internals().registered_types_cpp.erase(tindex);
|
217 |
+
} else {
|
218 |
+
internals.registered_types_cpp.erase(tindex);
|
219 |
+
}
|
220 |
+
internals.registered_types_py.erase(tinfo->type);
|
221 |
+
|
222 |
+
// Actually just `std::erase_if`, but that's only available in C++20
|
223 |
+
auto &cache = internals.inactive_override_cache;
|
224 |
+
for (auto it = cache.begin(), last = cache.end(); it != last;) {
|
225 |
+
if (it->first == (PyObject *) tinfo->type) {
|
226 |
+
it = cache.erase(it);
|
227 |
+
} else {
|
228 |
+
++it;
|
229 |
+
}
|
230 |
+
}
|
231 |
+
|
232 |
+
delete tinfo;
|
233 |
+
}
|
234 |
+
|
235 |
+
PyType_Type.tp_dealloc(obj);
|
236 |
+
}
|
237 |
+
|
238 |
+
/** This metaclass is assigned by default to all pybind11 types and is required in order
|
239 |
+
for static properties to function correctly. Users may override this using `py::metaclass`.
|
240 |
+
Return value: New reference. */
|
241 |
+
inline PyTypeObject *make_default_metaclass() {
|
242 |
+
constexpr auto *name = "pybind11_type";
|
243 |
+
auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
|
244 |
+
|
245 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
246 |
+
issue no Python C API calls which could potentially invoke the
|
247 |
+
garbage collector (the GC will call type_traverse(), which will in
|
248 |
+
turn find the newly constructed type in an invalid state) */
|
249 |
+
auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
|
250 |
+
if (!heap_type) {
|
251 |
+
pybind11_fail("make_default_metaclass(): error allocating metaclass!");
|
252 |
+
}
|
253 |
+
|
254 |
+
heap_type->ht_name = name_obj.inc_ref().ptr();
|
255 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
256 |
+
heap_type->ht_qualname = name_obj.inc_ref().ptr();
|
257 |
+
#endif
|
258 |
+
|
259 |
+
auto *type = &heap_type->ht_type;
|
260 |
+
type->tp_name = name;
|
261 |
+
type->tp_base = type_incref(&PyType_Type);
|
262 |
+
type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
|
263 |
+
|
264 |
+
type->tp_call = pybind11_meta_call;
|
265 |
+
|
266 |
+
type->tp_setattro = pybind11_meta_setattro;
|
267 |
+
type->tp_getattro = pybind11_meta_getattro;
|
268 |
+
|
269 |
+
type->tp_dealloc = pybind11_meta_dealloc;
|
270 |
+
|
271 |
+
if (PyType_Ready(type) < 0) {
|
272 |
+
pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
|
273 |
+
}
|
274 |
+
|
275 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
276 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
277 |
+
|
278 |
+
return type;
|
279 |
+
}
|
280 |
+
|
281 |
+
/// For multiple inheritance types we need to recursively register/deregister base pointers for any
|
282 |
+
/// base classes with pointers that are difference from the instance value pointer so that we can
|
283 |
+
/// correctly recognize an offset base class pointer. This calls a function with any offset base
|
284 |
+
/// ptrs.
|
285 |
+
inline void traverse_offset_bases(void *valueptr,
|
286 |
+
const detail::type_info *tinfo,
|
287 |
+
instance *self,
|
288 |
+
bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
|
289 |
+
for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
|
290 |
+
if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
|
291 |
+
for (auto &c : parent_tinfo->implicit_casts) {
|
292 |
+
if (c.first == tinfo->cpptype) {
|
293 |
+
auto *parentptr = c.second(valueptr);
|
294 |
+
if (parentptr != valueptr) {
|
295 |
+
f(parentptr, self);
|
296 |
+
}
|
297 |
+
traverse_offset_bases(parentptr, parent_tinfo, self, f);
|
298 |
+
break;
|
299 |
+
}
|
300 |
+
}
|
301 |
+
}
|
302 |
+
}
|
303 |
+
}
|
304 |
+
|
305 |
+
inline bool register_instance_impl(void *ptr, instance *self) {
|
306 |
+
get_internals().registered_instances.emplace(ptr, self);
|
307 |
+
return true; // unused, but gives the same signature as the deregister func
|
308 |
+
}
|
309 |
+
inline bool deregister_instance_impl(void *ptr, instance *self) {
|
310 |
+
auto ®istered_instances = get_internals().registered_instances;
|
311 |
+
auto range = registered_instances.equal_range(ptr);
|
312 |
+
for (auto it = range.first; it != range.second; ++it) {
|
313 |
+
if (self == it->second) {
|
314 |
+
registered_instances.erase(it);
|
315 |
+
return true;
|
316 |
+
}
|
317 |
+
}
|
318 |
+
return false;
|
319 |
+
}
|
320 |
+
|
321 |
+
inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
|
322 |
+
register_instance_impl(valptr, self);
|
323 |
+
if (!tinfo->simple_ancestors) {
|
324 |
+
traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
|
325 |
+
}
|
326 |
+
}
|
327 |
+
|
328 |
+
inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
|
329 |
+
bool ret = deregister_instance_impl(valptr, self);
|
330 |
+
if (!tinfo->simple_ancestors) {
|
331 |
+
traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
|
332 |
+
}
|
333 |
+
return ret;
|
334 |
+
}
|
335 |
+
|
336 |
+
/// Instance creation function for all pybind11 types. It allocates the internal instance layout
|
337 |
+
/// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
|
338 |
+
/// cast to a reference or pointer), and initialization is done by an `__init__` function.
|
339 |
+
inline PyObject *make_new_instance(PyTypeObject *type) {
|
340 |
+
#if defined(PYPY_VERSION)
|
341 |
+
// PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
|
342 |
+
// inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
|
343 |
+
ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
|
344 |
+
if (type->tp_basicsize < instance_size) {
|
345 |
+
type->tp_basicsize = instance_size;
|
346 |
+
}
|
347 |
+
#endif
|
348 |
+
PyObject *self = type->tp_alloc(type, 0);
|
349 |
+
auto *inst = reinterpret_cast<instance *>(self);
|
350 |
+
// Allocate the value/holder internals:
|
351 |
+
inst->allocate_layout();
|
352 |
+
|
353 |
+
return self;
|
354 |
+
}
|
355 |
+
|
356 |
+
/// Instance creation function for all pybind11 types. It only allocates space for the
|
357 |
+
/// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
|
358 |
+
extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
|
359 |
+
return make_new_instance(type);
|
360 |
+
}
|
361 |
+
|
362 |
+
/// An `__init__` function constructs the C++ object. Users should provide at least one
|
363 |
+
/// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
|
364 |
+
/// following default function will be used which simply throws an exception.
|
365 |
+
extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
|
366 |
+
PyTypeObject *type = Py_TYPE(self);
|
367 |
+
std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
|
368 |
+
PyErr_SetString(PyExc_TypeError, msg.c_str());
|
369 |
+
return -1;
|
370 |
+
}
|
371 |
+
|
372 |
+
inline void add_patient(PyObject *nurse, PyObject *patient) {
|
373 |
+
auto &internals = get_internals();
|
374 |
+
auto *instance = reinterpret_cast<detail::instance *>(nurse);
|
375 |
+
instance->has_patients = true;
|
376 |
+
Py_INCREF(patient);
|
377 |
+
internals.patients[nurse].push_back(patient);
|
378 |
+
}
|
379 |
+
|
380 |
+
inline void clear_patients(PyObject *self) {
|
381 |
+
auto *instance = reinterpret_cast<detail::instance *>(self);
|
382 |
+
auto &internals = get_internals();
|
383 |
+
auto pos = internals.patients.find(self);
|
384 |
+
assert(pos != internals.patients.end());
|
385 |
+
// Clearing the patients can cause more Python code to run, which
|
386 |
+
// can invalidate the iterator. Extract the vector of patients
|
387 |
+
// from the unordered_map first.
|
388 |
+
auto patients = std::move(pos->second);
|
389 |
+
internals.patients.erase(pos);
|
390 |
+
instance->has_patients = false;
|
391 |
+
for (PyObject *&patient : patients) {
|
392 |
+
Py_CLEAR(patient);
|
393 |
+
}
|
394 |
+
}
|
395 |
+
|
396 |
+
/// Clears all internal data from the instance and removes it from registered instances in
|
397 |
+
/// preparation for deallocation.
|
398 |
+
inline void clear_instance(PyObject *self) {
|
399 |
+
auto *instance = reinterpret_cast<detail::instance *>(self);
|
400 |
+
|
401 |
+
// Deallocate any values/holders, if present:
|
402 |
+
for (auto &v_h : values_and_holders(instance)) {
|
403 |
+
if (v_h) {
|
404 |
+
|
405 |
+
// We have to deregister before we call dealloc because, for virtual MI types, we still
|
406 |
+
// need to be able to get the parent pointers.
|
407 |
+
if (v_h.instance_registered()
|
408 |
+
&& !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
|
409 |
+
pybind11_fail(
|
410 |
+
"pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
|
411 |
+
}
|
412 |
+
|
413 |
+
if (instance->owned || v_h.holder_constructed()) {
|
414 |
+
v_h.type->dealloc(v_h);
|
415 |
+
}
|
416 |
+
}
|
417 |
+
}
|
418 |
+
// Deallocate the value/holder layout internals:
|
419 |
+
instance->deallocate_layout();
|
420 |
+
|
421 |
+
if (instance->weakrefs) {
|
422 |
+
PyObject_ClearWeakRefs(self);
|
423 |
+
}
|
424 |
+
|
425 |
+
PyObject **dict_ptr = _PyObject_GetDictPtr(self);
|
426 |
+
if (dict_ptr) {
|
427 |
+
Py_CLEAR(*dict_ptr);
|
428 |
+
}
|
429 |
+
|
430 |
+
if (instance->has_patients) {
|
431 |
+
clear_patients(self);
|
432 |
+
}
|
433 |
+
}
|
434 |
+
|
435 |
+
/// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
|
436 |
+
/// to destroy the C++ object itself, while the rest is Python bookkeeping.
|
437 |
+
extern "C" inline void pybind11_object_dealloc(PyObject *self) {
|
438 |
+
clear_instance(self);
|
439 |
+
|
440 |
+
auto *type = Py_TYPE(self);
|
441 |
+
type->tp_free(self);
|
442 |
+
|
443 |
+
#if PY_VERSION_HEX < 0x03080000
|
444 |
+
// `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
|
445 |
+
// as part of a derived type's dealloc, in which case we're not allowed to decref
|
446 |
+
// the type here. For cross-module compatibility, we shouldn't compare directly
|
447 |
+
// with `pybind11_object_dealloc`, but with the common one stashed in internals.
|
448 |
+
auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
|
449 |
+
if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
|
450 |
+
Py_DECREF(type);
|
451 |
+
#else
|
452 |
+
// This was not needed before Python 3.8 (Python issue 35810)
|
453 |
+
// https://github.com/pybind/pybind11/issues/1946
|
454 |
+
Py_DECREF(type);
|
455 |
+
#endif
|
456 |
+
}
|
457 |
+
|
458 |
+
std::string error_string();
|
459 |
+
|
460 |
+
/** Create the type which can be used as a common base for all classes. This is
|
461 |
+
needed in order to satisfy Python's requirements for multiple inheritance.
|
462 |
+
Return value: New reference. */
|
463 |
+
inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
|
464 |
+
constexpr auto *name = "pybind11_object";
|
465 |
+
auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
|
466 |
+
|
467 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
468 |
+
issue no Python C API calls which could potentially invoke the
|
469 |
+
garbage collector (the GC will call type_traverse(), which will in
|
470 |
+
turn find the newly constructed type in an invalid state) */
|
471 |
+
auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
|
472 |
+
if (!heap_type) {
|
473 |
+
pybind11_fail("make_object_base_type(): error allocating type!");
|
474 |
+
}
|
475 |
+
|
476 |
+
heap_type->ht_name = name_obj.inc_ref().ptr();
|
477 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
478 |
+
heap_type->ht_qualname = name_obj.inc_ref().ptr();
|
479 |
+
#endif
|
480 |
+
|
481 |
+
auto *type = &heap_type->ht_type;
|
482 |
+
type->tp_name = name;
|
483 |
+
type->tp_base = type_incref(&PyBaseObject_Type);
|
484 |
+
type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
|
485 |
+
type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
|
486 |
+
|
487 |
+
type->tp_new = pybind11_object_new;
|
488 |
+
type->tp_init = pybind11_object_init;
|
489 |
+
type->tp_dealloc = pybind11_object_dealloc;
|
490 |
+
|
491 |
+
/* Support weak references (needed for the keep_alive feature) */
|
492 |
+
type->tp_weaklistoffset = offsetof(instance, weakrefs);
|
493 |
+
|
494 |
+
if (PyType_Ready(type) < 0) {
|
495 |
+
pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
|
496 |
+
}
|
497 |
+
|
498 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
499 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
500 |
+
|
501 |
+
assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
|
502 |
+
return (PyObject *) heap_type;
|
503 |
+
}
|
504 |
+
|
505 |
+
/// dynamic_attr: Support for `d = instance.__dict__`.
|
506 |
+
extern "C" inline PyObject *pybind11_get_dict(PyObject *self, void *) {
|
507 |
+
PyObject *&dict = *_PyObject_GetDictPtr(self);
|
508 |
+
if (!dict) {
|
509 |
+
dict = PyDict_New();
|
510 |
+
}
|
511 |
+
Py_XINCREF(dict);
|
512 |
+
return dict;
|
513 |
+
}
|
514 |
+
|
515 |
+
/// dynamic_attr: Support for `instance.__dict__ = dict()`.
|
516 |
+
extern "C" inline int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *) {
|
517 |
+
if (!PyDict_Check(new_dict)) {
|
518 |
+
PyErr_Format(PyExc_TypeError,
|
519 |
+
"__dict__ must be set to a dictionary, not a '%.200s'",
|
520 |
+
get_fully_qualified_tp_name(Py_TYPE(new_dict)).c_str());
|
521 |
+
return -1;
|
522 |
+
}
|
523 |
+
PyObject *&dict = *_PyObject_GetDictPtr(self);
|
524 |
+
Py_INCREF(new_dict);
|
525 |
+
Py_CLEAR(dict);
|
526 |
+
dict = new_dict;
|
527 |
+
return 0;
|
528 |
+
}
|
529 |
+
|
530 |
+
/// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
|
531 |
+
extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
|
532 |
+
PyObject *&dict = *_PyObject_GetDictPtr(self);
|
533 |
+
Py_VISIT(dict);
|
534 |
+
return 0;
|
535 |
+
}
|
536 |
+
|
537 |
+
/// dynamic_attr: Allow the GC to clear the dictionary.
|
538 |
+
extern "C" inline int pybind11_clear(PyObject *self) {
|
539 |
+
PyObject *&dict = *_PyObject_GetDictPtr(self);
|
540 |
+
Py_CLEAR(dict);
|
541 |
+
return 0;
|
542 |
+
}
|
543 |
+
|
544 |
+
/// Give instances of this type a `__dict__` and opt into garbage collection.
|
545 |
+
inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
|
546 |
+
auto *type = &heap_type->ht_type;
|
547 |
+
type->tp_flags |= Py_TPFLAGS_HAVE_GC;
|
548 |
+
type->tp_dictoffset = type->tp_basicsize; // place dict at the end
|
549 |
+
type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
|
550 |
+
type->tp_traverse = pybind11_traverse;
|
551 |
+
type->tp_clear = pybind11_clear;
|
552 |
+
|
553 |
+
static PyGetSetDef getset[] = {
|
554 |
+
{const_cast<char *>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
|
555 |
+
{nullptr, nullptr, nullptr, nullptr, nullptr}};
|
556 |
+
type->tp_getset = getset;
|
557 |
+
}
|
558 |
+
|
559 |
+
/// buffer_protocol: Fill in the view as specified by flags.
|
560 |
+
extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
|
561 |
+
// Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
|
562 |
+
type_info *tinfo = nullptr;
|
563 |
+
for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
|
564 |
+
tinfo = get_type_info((PyTypeObject *) type.ptr());
|
565 |
+
if (tinfo && tinfo->get_buffer) {
|
566 |
+
break;
|
567 |
+
}
|
568 |
+
}
|
569 |
+
if (view == nullptr || !tinfo || !tinfo->get_buffer) {
|
570 |
+
if (view) {
|
571 |
+
view->obj = nullptr;
|
572 |
+
}
|
573 |
+
PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
|
574 |
+
return -1;
|
575 |
+
}
|
576 |
+
std::memset(view, 0, sizeof(Py_buffer));
|
577 |
+
buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
|
578 |
+
if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
|
579 |
+
delete info;
|
580 |
+
// view->obj = nullptr; // Was just memset to 0, so not necessary
|
581 |
+
PyErr_SetString(PyExc_BufferError, "Writable buffer requested for readonly storage");
|
582 |
+
return -1;
|
583 |
+
}
|
584 |
+
view->obj = obj;
|
585 |
+
view->ndim = 1;
|
586 |
+
view->internal = info;
|
587 |
+
view->buf = info->ptr;
|
588 |
+
view->itemsize = info->itemsize;
|
589 |
+
view->len = view->itemsize;
|
590 |
+
for (auto s : info->shape) {
|
591 |
+
view->len *= s;
|
592 |
+
}
|
593 |
+
view->readonly = static_cast<int>(info->readonly);
|
594 |
+
if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
|
595 |
+
view->format = const_cast<char *>(info->format.c_str());
|
596 |
+
}
|
597 |
+
if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
|
598 |
+
view->ndim = (int) info->ndim;
|
599 |
+
view->strides = info->strides.data();
|
600 |
+
view->shape = info->shape.data();
|
601 |
+
}
|
602 |
+
Py_INCREF(view->obj);
|
603 |
+
return 0;
|
604 |
+
}
|
605 |
+
|
606 |
+
/// buffer_protocol: Release the resources of the buffer.
|
607 |
+
extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
|
608 |
+
delete (buffer_info *) view->internal;
|
609 |
+
}
|
610 |
+
|
611 |
+
/// Give this type a buffer interface.
|
612 |
+
inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
|
613 |
+
heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
|
614 |
+
|
615 |
+
heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
|
616 |
+
heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
|
617 |
+
}
|
618 |
+
|
619 |
+
/** Create a brand new Python type according to the `type_record` specification.
|
620 |
+
Return value: New reference. */
|
621 |
+
inline PyObject *make_new_python_type(const type_record &rec) {
|
622 |
+
auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
|
623 |
+
|
624 |
+
auto qualname = name;
|
625 |
+
if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
|
626 |
+
qualname = reinterpret_steal<object>(
|
627 |
+
PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
|
628 |
+
}
|
629 |
+
|
630 |
+
object module_;
|
631 |
+
if (rec.scope) {
|
632 |
+
if (hasattr(rec.scope, "__module__")) {
|
633 |
+
module_ = rec.scope.attr("__module__");
|
634 |
+
} else if (hasattr(rec.scope, "__name__")) {
|
635 |
+
module_ = rec.scope.attr("__name__");
|
636 |
+
}
|
637 |
+
}
|
638 |
+
|
639 |
+
const auto *full_name = c_str(
|
640 |
+
#if !defined(PYPY_VERSION)
|
641 |
+
module_ ? str(module_).cast<std::string>() + "." + rec.name :
|
642 |
+
#endif
|
643 |
+
rec.name);
|
644 |
+
|
645 |
+
char *tp_doc = nullptr;
|
646 |
+
if (rec.doc && options::show_user_defined_docstrings()) {
|
647 |
+
/* Allocate memory for docstring (using PyObject_MALLOC, since
|
648 |
+
Python will free this later on) */
|
649 |
+
size_t size = std::strlen(rec.doc) + 1;
|
650 |
+
tp_doc = (char *) PyObject_MALLOC(size);
|
651 |
+
std::memcpy((void *) tp_doc, rec.doc, size);
|
652 |
+
}
|
653 |
+
|
654 |
+
auto &internals = get_internals();
|
655 |
+
auto bases = tuple(rec.bases);
|
656 |
+
auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
|
657 |
+
|
658 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
659 |
+
issue no Python C API calls which could potentially invoke the
|
660 |
+
garbage collector (the GC will call type_traverse(), which will in
|
661 |
+
turn find the newly constructed type in an invalid state) */
|
662 |
+
auto *metaclass
|
663 |
+
= rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
|
664 |
+
|
665 |
+
auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
|
666 |
+
if (!heap_type) {
|
667 |
+
pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
|
668 |
+
}
|
669 |
+
|
670 |
+
heap_type->ht_name = name.release().ptr();
|
671 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
672 |
+
heap_type->ht_qualname = qualname.inc_ref().ptr();
|
673 |
+
#endif
|
674 |
+
|
675 |
+
auto *type = &heap_type->ht_type;
|
676 |
+
type->tp_name = full_name;
|
677 |
+
type->tp_doc = tp_doc;
|
678 |
+
type->tp_base = type_incref((PyTypeObject *) base);
|
679 |
+
type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
|
680 |
+
if (!bases.empty()) {
|
681 |
+
type->tp_bases = bases.release().ptr();
|
682 |
+
}
|
683 |
+
|
684 |
+
/* Don't inherit base __init__ */
|
685 |
+
type->tp_init = pybind11_object_init;
|
686 |
+
|
687 |
+
/* Supported protocols */
|
688 |
+
type->tp_as_number = &heap_type->as_number;
|
689 |
+
type->tp_as_sequence = &heap_type->as_sequence;
|
690 |
+
type->tp_as_mapping = &heap_type->as_mapping;
|
691 |
+
type->tp_as_async = &heap_type->as_async;
|
692 |
+
|
693 |
+
/* Flags */
|
694 |
+
type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
|
695 |
+
if (!rec.is_final) {
|
696 |
+
type->tp_flags |= Py_TPFLAGS_BASETYPE;
|
697 |
+
}
|
698 |
+
|
699 |
+
if (rec.dynamic_attr) {
|
700 |
+
enable_dynamic_attributes(heap_type);
|
701 |
+
}
|
702 |
+
|
703 |
+
if (rec.buffer_protocol) {
|
704 |
+
enable_buffer_protocol(heap_type);
|
705 |
+
}
|
706 |
+
|
707 |
+
if (rec.custom_type_setup_callback) {
|
708 |
+
rec.custom_type_setup_callback(heap_type);
|
709 |
+
}
|
710 |
+
|
711 |
+
if (PyType_Ready(type) < 0) {
|
712 |
+
pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
|
713 |
+
}
|
714 |
+
|
715 |
+
assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
|
716 |
+
|
717 |
+
/* Register type with the parent scope */
|
718 |
+
if (rec.scope) {
|
719 |
+
setattr(rec.scope, rec.name, (PyObject *) type);
|
720 |
+
} else {
|
721 |
+
Py_INCREF(type); // Keep it alive forever (reference leak)
|
722 |
+
}
|
723 |
+
|
724 |
+
if (module_) { // Needed by pydoc
|
725 |
+
setattr((PyObject *) type, "__module__", module_);
|
726 |
+
}
|
727 |
+
|
728 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
|
729 |
+
|
730 |
+
return (PyObject *) type;
|
731 |
+
}
|
732 |
+
|
733 |
+
PYBIND11_NAMESPACE_END(detail)
|
734 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
third-party/DPVO/DPViewer/pybind11/include/pybind11/detail/common.h
ADDED
@@ -0,0 +1,1168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 10
|
14 |
+
#define PYBIND11_VERSION_PATCH 0.dev1
|
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 0x020A00D1
|
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
|
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 |
+
# if _MSC_VER < 1910
|
85 |
+
# error pybind11 2.10+ requires MSVC 2017 or newer
|
86 |
+
# endif
|
87 |
+
#endif
|
88 |
+
|
89 |
+
#if !defined(PYBIND11_EXPORT)
|
90 |
+
# if defined(WIN32) || defined(_WIN32)
|
91 |
+
# define PYBIND11_EXPORT __declspec(dllexport)
|
92 |
+
# else
|
93 |
+
# define PYBIND11_EXPORT __attribute__((visibility("default")))
|
94 |
+
# endif
|
95 |
+
#endif
|
96 |
+
|
97 |
+
#if !defined(PYBIND11_EXPORT_EXCEPTION)
|
98 |
+
# ifdef __MINGW32__
|
99 |
+
// workaround for:
|
100 |
+
// error: 'dllexport' implies default visibility, but xxx has already been declared with a
|
101 |
+
// different visibility
|
102 |
+
# define PYBIND11_EXPORT_EXCEPTION
|
103 |
+
# else
|
104 |
+
# define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
|
105 |
+
# endif
|
106 |
+
#endif
|
107 |
+
|
108 |
+
// For CUDA, GCC7, GCC8:
|
109 |
+
// PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.
|
110 |
+
// When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.
|
111 |
+
// However, the measured shared-library size saving when using noinline are only
|
112 |
+
// 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,
|
113 |
+
// the default under pybind11/tests).
|
114 |
+
#if !defined(PYBIND11_NOINLINE_FORCED) \
|
115 |
+
&& (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))
|
116 |
+
# define PYBIND11_NOINLINE_DISABLED
|
117 |
+
#endif
|
118 |
+
|
119 |
+
// The PYBIND11_NOINLINE macro is for function DEFINITIONS.
|
120 |
+
// In contrast, FORWARD DECLARATIONS should never use this macro:
|
121 |
+
// https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions
|
122 |
+
#if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.
|
123 |
+
# define PYBIND11_NOINLINE inline
|
124 |
+
#elif defined(_MSC_VER)
|
125 |
+
# define PYBIND11_NOINLINE __declspec(noinline) inline
|
126 |
+
#else
|
127 |
+
# define PYBIND11_NOINLINE __attribute__((noinline)) inline
|
128 |
+
#endif
|
129 |
+
|
130 |
+
#if defined(__MINGW32__)
|
131 |
+
// For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
|
132 |
+
// whether it is used or not
|
133 |
+
# define PYBIND11_DEPRECATED(reason)
|
134 |
+
#elif defined(PYBIND11_CPP14)
|
135 |
+
# define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
|
136 |
+
#else
|
137 |
+
# define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
|
138 |
+
#endif
|
139 |
+
|
140 |
+
#if defined(PYBIND11_CPP17)
|
141 |
+
# define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
|
142 |
+
#elif defined(_MSC_VER) && !defined(__clang__)
|
143 |
+
# define PYBIND11_MAYBE_UNUSED
|
144 |
+
#else
|
145 |
+
# define PYBIND11_MAYBE_UNUSED __attribute__((__unused__))
|
146 |
+
#endif
|
147 |
+
|
148 |
+
/* Don't let Python.h #define (v)snprintf as macro because they are implemented
|
149 |
+
properly in Visual Studio since 2015. */
|
150 |
+
#if defined(_MSC_VER)
|
151 |
+
# define HAVE_SNPRINTF 1
|
152 |
+
#endif
|
153 |
+
|
154 |
+
/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
|
155 |
+
#if defined(_MSC_VER)
|
156 |
+
# pragma warning(push)
|
157 |
+
// C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
|
158 |
+
# pragma warning(disable : 4505)
|
159 |
+
# if defined(_DEBUG) && !defined(Py_DEBUG)
|
160 |
+
// Workaround for a VS 2022 issue.
|
161 |
+
// NOTE: This workaround knowingly violates the Python.h include order requirement:
|
162 |
+
// https://docs.python.org/3/c-api/intro.html#include-files
|
163 |
+
// See https://github.com/pybind/pybind11/pull/3497 for full context.
|
164 |
+
# include <yvals.h>
|
165 |
+
# if _MSVC_STL_VERSION >= 143
|
166 |
+
# include <crtdefs.h>
|
167 |
+
# endif
|
168 |
+
# define PYBIND11_DEBUG_MARKER
|
169 |
+
# undef _DEBUG
|
170 |
+
# endif
|
171 |
+
#endif
|
172 |
+
|
173 |
+
// https://en.cppreference.com/w/c/chrono/localtime
|
174 |
+
#if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
|
175 |
+
# define __STDC_WANT_LIB_EXT1__
|
176 |
+
#endif
|
177 |
+
|
178 |
+
#ifdef __has_include
|
179 |
+
// std::optional (but including it in c++14 mode isn't allowed)
|
180 |
+
# if defined(PYBIND11_CPP17) && __has_include(<optional>)
|
181 |
+
# define PYBIND11_HAS_OPTIONAL 1
|
182 |
+
# endif
|
183 |
+
// std::experimental::optional (but not allowed in c++11 mode)
|
184 |
+
# if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
|
185 |
+
!__has_include(<optional>))
|
186 |
+
# define PYBIND11_HAS_EXP_OPTIONAL 1
|
187 |
+
# endif
|
188 |
+
// std::variant
|
189 |
+
# if defined(PYBIND11_CPP17) && __has_include(<variant>)
|
190 |
+
# define PYBIND11_HAS_VARIANT 1
|
191 |
+
# endif
|
192 |
+
#elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
|
193 |
+
# define PYBIND11_HAS_OPTIONAL 1
|
194 |
+
# define PYBIND11_HAS_VARIANT 1
|
195 |
+
#endif
|
196 |
+
|
197 |
+
#if defined(PYBIND11_CPP17)
|
198 |
+
# if defined(__has_include)
|
199 |
+
# if __has_include(<string_view>)
|
200 |
+
# define PYBIND11_HAS_STRING_VIEW
|
201 |
+
# endif
|
202 |
+
# elif defined(_MSC_VER)
|
203 |
+
# define PYBIND11_HAS_STRING_VIEW
|
204 |
+
# endif
|
205 |
+
#endif
|
206 |
+
|
207 |
+
#if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
|
208 |
+
# define PYBIND11_HAS_U8STRING
|
209 |
+
#endif
|
210 |
+
|
211 |
+
#include <Python.h>
|
212 |
+
#if PY_VERSION_HEX < 0x03060000
|
213 |
+
# error "PYTHON < 3.6 IS UNSUPPORTED. pybind11 v2.9 was the last to support Python 2 and 3.5."
|
214 |
+
#endif
|
215 |
+
#include <frameobject.h>
|
216 |
+
#include <pythread.h>
|
217 |
+
|
218 |
+
/* Python #defines overrides on all sorts of core functions, which
|
219 |
+
tends to weak havok in C++ codebases that expect these to work
|
220 |
+
like regular functions (potentially with several overloads) */
|
221 |
+
#if defined(isalnum)
|
222 |
+
# undef isalnum
|
223 |
+
# undef isalpha
|
224 |
+
# undef islower
|
225 |
+
# undef isspace
|
226 |
+
# undef isupper
|
227 |
+
# undef tolower
|
228 |
+
# undef toupper
|
229 |
+
#endif
|
230 |
+
|
231 |
+
#if defined(copysign)
|
232 |
+
# undef copysign
|
233 |
+
#endif
|
234 |
+
|
235 |
+
#if defined(_MSC_VER)
|
236 |
+
# if defined(PYBIND11_DEBUG_MARKER)
|
237 |
+
# define _DEBUG
|
238 |
+
# undef PYBIND11_DEBUG_MARKER
|
239 |
+
# endif
|
240 |
+
# pragma warning(pop)
|
241 |
+
#endif
|
242 |
+
|
243 |
+
#include <cstddef>
|
244 |
+
#include <cstring>
|
245 |
+
#include <exception>
|
246 |
+
#include <forward_list>
|
247 |
+
#include <memory>
|
248 |
+
#include <stdexcept>
|
249 |
+
#include <string>
|
250 |
+
#include <type_traits>
|
251 |
+
#include <typeindex>
|
252 |
+
#include <unordered_map>
|
253 |
+
#include <unordered_set>
|
254 |
+
#include <vector>
|
255 |
+
#if defined(__has_include)
|
256 |
+
# if __has_include(<version>)
|
257 |
+
# include <version>
|
258 |
+
# endif
|
259 |
+
#endif
|
260 |
+
|
261 |
+
// #define PYBIND11_STR_LEGACY_PERMISSIVE
|
262 |
+
// If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
|
263 |
+
// (probably surprising and never documented, but this was the
|
264 |
+
// legacy behavior until and including v2.6.x). As a side-effect,
|
265 |
+
// pybind11::isinstance<str>() is true for both pybind11::str and
|
266 |
+
// pybind11::bytes.
|
267 |
+
// If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
|
268 |
+
// pybind11::isinstance<str>() is true only for pybind11::str.
|
269 |
+
// However, for Python 2 only (!), the pybind11::str caster
|
270 |
+
// implicitly decoded bytes to PyUnicodeObject. This was to ease
|
271 |
+
// the transition from the legacy behavior to the non-permissive
|
272 |
+
// behavior.
|
273 |
+
|
274 |
+
/// Compatibility macros for Python 2 / Python 3 versions TODO: remove
|
275 |
+
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
|
276 |
+
#define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
|
277 |
+
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
|
278 |
+
#define PYBIND11_BYTES_CHECK PyBytes_Check
|
279 |
+
#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
|
280 |
+
#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
|
281 |
+
#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
|
282 |
+
#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
|
283 |
+
#define PYBIND11_BYTES_SIZE PyBytes_Size
|
284 |
+
#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
|
285 |
+
#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
|
286 |
+
#define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))
|
287 |
+
#define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))
|
288 |
+
#define PYBIND11_BYTES_NAME "bytes"
|
289 |
+
#define PYBIND11_STRING_NAME "str"
|
290 |
+
#define PYBIND11_SLICE_OBJECT PyObject
|
291 |
+
#define PYBIND11_FROM_STRING PyUnicode_FromString
|
292 |
+
#define PYBIND11_STR_TYPE ::pybind11::str
|
293 |
+
#define PYBIND11_BOOL_ATTR "__bool__"
|
294 |
+
#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
|
295 |
+
#define PYBIND11_BUILTINS_MODULE "builtins"
|
296 |
+
// Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
|
297 |
+
// See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
|
298 |
+
#define PYBIND11_PLUGIN_IMPL(name) \
|
299 |
+
extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name(); \
|
300 |
+
extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
|
301 |
+
|
302 |
+
#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
|
303 |
+
#define PYBIND11_STRINGIFY(x) #x
|
304 |
+
#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
|
305 |
+
#define PYBIND11_CONCAT(first, second) first##second
|
306 |
+
#define PYBIND11_ENSURE_INTERNALS_READY pybind11::detail::get_internals();
|
307 |
+
|
308 |
+
#define PYBIND11_CHECK_PYTHON_VERSION \
|
309 |
+
{ \
|
310 |
+
const char *compiled_ver \
|
311 |
+
= PYBIND11_TOSTRING(PY_MAJOR_VERSION) "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
|
312 |
+
const char *runtime_ver = Py_GetVersion(); \
|
313 |
+
size_t len = std::strlen(compiled_ver); \
|
314 |
+
if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
|
315 |
+
|| (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
|
316 |
+
PyErr_Format(PyExc_ImportError, \
|
317 |
+
"Python version mismatch: module was compiled for Python %s, " \
|
318 |
+
"but the interpreter version is incompatible: %s.", \
|
319 |
+
compiled_ver, \
|
320 |
+
runtime_ver); \
|
321 |
+
return nullptr; \
|
322 |
+
} \
|
323 |
+
}
|
324 |
+
|
325 |
+
#define PYBIND11_CATCH_INIT_EXCEPTIONS \
|
326 |
+
catch (pybind11::error_already_set & e) { \
|
327 |
+
pybind11::raise_from(e, PyExc_ImportError, "initialization failed"); \
|
328 |
+
return nullptr; \
|
329 |
+
} \
|
330 |
+
catch (const std::exception &e) { \
|
331 |
+
PyErr_SetString(PyExc_ImportError, e.what()); \
|
332 |
+
return nullptr; \
|
333 |
+
}
|
334 |
+
|
335 |
+
/** \rst
|
336 |
+
***Deprecated in favor of PYBIND11_MODULE***
|
337 |
+
|
338 |
+
This macro creates the entry point that will be invoked when the Python interpreter
|
339 |
+
imports a plugin library. Please create a `module_` in the function body and return
|
340 |
+
the pointer to its underlying Python object at the end.
|
341 |
+
|
342 |
+
.. code-block:: cpp
|
343 |
+
|
344 |
+
PYBIND11_PLUGIN(example) {
|
345 |
+
pybind11::module_ m("example", "pybind11 example plugin");
|
346 |
+
/// Set up bindings here
|
347 |
+
return m.ptr();
|
348 |
+
}
|
349 |
+
\endrst */
|
350 |
+
#define PYBIND11_PLUGIN(name) \
|
351 |
+
PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
|
352 |
+
static PyObject *pybind11_init(); \
|
353 |
+
PYBIND11_PLUGIN_IMPL(name) { \
|
354 |
+
PYBIND11_CHECK_PYTHON_VERSION \
|
355 |
+
PYBIND11_ENSURE_INTERNALS_READY \
|
356 |
+
try { \
|
357 |
+
return pybind11_init(); \
|
358 |
+
} \
|
359 |
+
PYBIND11_CATCH_INIT_EXCEPTIONS \
|
360 |
+
} \
|
361 |
+
PyObject *pybind11_init()
|
362 |
+
|
363 |
+
/** \rst
|
364 |
+
This macro creates the entry point that will be invoked when the Python interpreter
|
365 |
+
imports an extension module. The module name is given as the fist argument and it
|
366 |
+
should not be in quotes. The second macro argument defines a variable of type
|
367 |
+
`py::module_` which can be used to initialize the module.
|
368 |
+
|
369 |
+
The entry point is marked as "maybe unused" to aid dead-code detection analysis:
|
370 |
+
since the entry point is typically only looked up at runtime and not referenced
|
371 |
+
during translation, it would otherwise appear as unused ("dead") code.
|
372 |
+
|
373 |
+
.. code-block:: cpp
|
374 |
+
|
375 |
+
PYBIND11_MODULE(example, m) {
|
376 |
+
m.doc() = "pybind11 example module";
|
377 |
+
|
378 |
+
// Add bindings here
|
379 |
+
m.def("foo", []() {
|
380 |
+
return "Hello, World!";
|
381 |
+
});
|
382 |
+
}
|
383 |
+
\endrst */
|
384 |
+
#define PYBIND11_MODULE(name, variable) \
|
385 |
+
static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name) \
|
386 |
+
PYBIND11_MAYBE_UNUSED; \
|
387 |
+
PYBIND11_MAYBE_UNUSED \
|
388 |
+
static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
|
389 |
+
PYBIND11_PLUGIN_IMPL(name) { \
|
390 |
+
PYBIND11_CHECK_PYTHON_VERSION \
|
391 |
+
PYBIND11_ENSURE_INTERNALS_READY \
|
392 |
+
auto m = ::pybind11::module_::create_extension_module( \
|
393 |
+
PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
|
394 |
+
try { \
|
395 |
+
PYBIND11_CONCAT(pybind11_init_, name)(m); \
|
396 |
+
return m.ptr(); \
|
397 |
+
} \
|
398 |
+
PYBIND11_CATCH_INIT_EXCEPTIONS \
|
399 |
+
} \
|
400 |
+
void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ & (variable))
|
401 |
+
|
402 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
403 |
+
|
404 |
+
using ssize_t = Py_ssize_t;
|
405 |
+
using size_t = std::size_t;
|
406 |
+
|
407 |
+
template <typename IntType>
|
408 |
+
inline ssize_t ssize_t_cast(const IntType &val) {
|
409 |
+
static_assert(sizeof(IntType) <= sizeof(ssize_t), "Implicit narrowing is not permitted.");
|
410 |
+
return static_cast<ssize_t>(val);
|
411 |
+
}
|
412 |
+
|
413 |
+
/// Approach used to cast a previously unknown C++ instance into a Python object
|
414 |
+
enum class return_value_policy : uint8_t {
|
415 |
+
/** This is the default return value policy, which falls back to the policy
|
416 |
+
return_value_policy::take_ownership when the return value is a pointer.
|
417 |
+
Otherwise, it uses return_value::move or return_value::copy for rvalue
|
418 |
+
and lvalue references, respectively. See below for a description of what
|
419 |
+
all of these different policies do. */
|
420 |
+
automatic = 0,
|
421 |
+
|
422 |
+
/** As above, but use policy return_value_policy::reference when the return
|
423 |
+
value is a pointer. This is the default conversion policy for function
|
424 |
+
arguments when calling Python functions manually from C++ code (i.e. via
|
425 |
+
handle::operator()). You probably won't need to use this. */
|
426 |
+
automatic_reference,
|
427 |
+
|
428 |
+
/** Reference an existing object (i.e. do not create a new copy) and take
|
429 |
+
ownership. Python will call the destructor and delete operator when the
|
430 |
+
object's reference count reaches zero. Undefined behavior ensues when
|
431 |
+
the C++ side does the same.. */
|
432 |
+
take_ownership,
|
433 |
+
|
434 |
+
/** Create a new copy of the returned object, which will be owned by
|
435 |
+
Python. This policy is comparably safe because the lifetimes of the two
|
436 |
+
instances are decoupled. */
|
437 |
+
copy,
|
438 |
+
|
439 |
+
/** Use std::move to move the return value contents into a new instance
|
440 |
+
that will be owned by Python. This policy is comparably safe because the
|
441 |
+
lifetimes of the two instances (move source and destination) are
|
442 |
+
decoupled. */
|
443 |
+
move,
|
444 |
+
|
445 |
+
/** Reference an existing object, but do not take ownership. The C++ side
|
446 |
+
is responsible for managing the object's lifetime and deallocating it
|
447 |
+
when it is no longer used. Warning: undefined behavior will ensue when
|
448 |
+
the C++ side deletes an object that is still referenced and used by
|
449 |
+
Python. */
|
450 |
+
reference,
|
451 |
+
|
452 |
+
/** This policy only applies to methods and properties. It references the
|
453 |
+
object without taking ownership similar to the above
|
454 |
+
return_value_policy::reference policy. In contrast to that policy, the
|
455 |
+
function or property's implicit this argument (called the parent) is
|
456 |
+
considered to be the the owner of the return value (the child).
|
457 |
+
pybind11 then couples the lifetime of the parent to the child via a
|
458 |
+
reference relationship that ensures that the parent cannot be garbage
|
459 |
+
collected while Python is still using the child. More advanced
|
460 |
+
variations of this scheme are also possible using combinations of
|
461 |
+
return_value_policy::reference and the keep_alive call policy */
|
462 |
+
reference_internal
|
463 |
+
};
|
464 |
+
|
465 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
466 |
+
|
467 |
+
inline static constexpr int log2(size_t n, int k = 0) {
|
468 |
+
return (n <= 1) ? k : log2(n >> 1, k + 1);
|
469 |
+
}
|
470 |
+
|
471 |
+
// Returns the size as a multiple of sizeof(void *), rounded up.
|
472 |
+
inline static constexpr size_t size_in_ptrs(size_t s) {
|
473 |
+
return 1 + ((s - 1) >> log2(sizeof(void *)));
|
474 |
+
}
|
475 |
+
|
476 |
+
/**
|
477 |
+
* The space to allocate for simple layout instance holders (see below) in multiple of the size of
|
478 |
+
* a pointer (e.g. 2 means 16 bytes on 64-bit architectures). The default is the minimum required
|
479 |
+
* to holder either a std::unique_ptr or std::shared_ptr (which is almost always
|
480 |
+
* sizeof(std::shared_ptr<T>)).
|
481 |
+
*/
|
482 |
+
constexpr size_t instance_simple_holder_in_ptrs() {
|
483 |
+
static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
|
484 |
+
"pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
|
485 |
+
return size_in_ptrs(sizeof(std::shared_ptr<int>));
|
486 |
+
}
|
487 |
+
|
488 |
+
// Forward declarations
|
489 |
+
struct type_info;
|
490 |
+
struct value_and_holder;
|
491 |
+
|
492 |
+
struct nonsimple_values_and_holders {
|
493 |
+
void **values_and_holders;
|
494 |
+
uint8_t *status;
|
495 |
+
};
|
496 |
+
|
497 |
+
/// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
|
498 |
+
struct instance {
|
499 |
+
PyObject_HEAD
|
500 |
+
/// Storage for pointers and holder; see simple_layout, below, for a description
|
501 |
+
union {
|
502 |
+
void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
|
503 |
+
nonsimple_values_and_holders nonsimple;
|
504 |
+
};
|
505 |
+
/// Weak references
|
506 |
+
PyObject *weakrefs;
|
507 |
+
/// If true, the pointer is owned which means we're free to manage it with a holder.
|
508 |
+
bool owned : 1;
|
509 |
+
/**
|
510 |
+
* An instance has two possible value/holder layouts.
|
511 |
+
*
|
512 |
+
* Simple layout (when this flag is true), means the `simple_value_holder` is set with a
|
513 |
+
* pointer and the holder object governing that pointer, i.e. [val1*][holder]. This layout is
|
514 |
+
* applied whenever there is no python-side multiple inheritance of bound C++ types *and* the
|
515 |
+
* type's holder will fit in the default space (which is large enough to hold either a
|
516 |
+
* std::unique_ptr or std::shared_ptr).
|
517 |
+
*
|
518 |
+
* Non-simple layout applies when using custom holders that require more space than
|
519 |
+
* `shared_ptr` (which is typically the size of two pointers), or when multiple inheritance is
|
520 |
+
* used on the python side. Non-simple layout allocates the required amount of memory to have
|
521 |
+
* multiple bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is
|
522 |
+
* set to a pointer to allocated space of the required space to hold a sequence of value
|
523 |
+
* pointers and holders followed `status`, a set of bit flags (1 byte each), i.e.
|
524 |
+
* [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple
|
525 |
+
* of `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the beginning of
|
526 |
+
* the [bb...] block (but not independently allocated).
|
527 |
+
*
|
528 |
+
* Status bits indicate whether the associated holder is constructed (&
|
529 |
+
* status_holder_constructed) and whether the value pointer is registered (&
|
530 |
+
* status_instance_registered) in `registered_instances`.
|
531 |
+
*/
|
532 |
+
bool simple_layout : 1;
|
533 |
+
/// For simple layout, tracks whether the holder has been constructed
|
534 |
+
bool simple_holder_constructed : 1;
|
535 |
+
/// For simple layout, tracks whether the instance is registered in `registered_instances`
|
536 |
+
bool simple_instance_registered : 1;
|
537 |
+
/// If true, get_internals().patients has an entry for this object
|
538 |
+
bool has_patients : 1;
|
539 |
+
|
540 |
+
/// Initializes all of the above type/values/holders data (but not the instance values
|
541 |
+
/// themselves)
|
542 |
+
void allocate_layout();
|
543 |
+
|
544 |
+
/// Destroys/deallocates all of the above
|
545 |
+
void deallocate_layout();
|
546 |
+
|
547 |
+
/// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
|
548 |
+
/// omitted). Returns a default-constructed (with `.inst = nullptr`) object on failure if
|
549 |
+
/// `throw_if_missing` is false.
|
550 |
+
value_and_holder get_value_and_holder(const type_info *find_type = nullptr,
|
551 |
+
bool throw_if_missing = true);
|
552 |
+
|
553 |
+
/// Bit values for the non-simple status flags
|
554 |
+
static constexpr uint8_t status_holder_constructed = 1;
|
555 |
+
static constexpr uint8_t status_instance_registered = 2;
|
556 |
+
};
|
557 |
+
|
558 |
+
static_assert(std::is_standard_layout<instance>::value,
|
559 |
+
"Internal error: `pybind11::detail::instance` is not standard layout!");
|
560 |
+
|
561 |
+
/// from __cpp_future__ import (convenient aliases from C++14/17)
|
562 |
+
#if defined(PYBIND11_CPP14)
|
563 |
+
using std::conditional_t;
|
564 |
+
using std::enable_if_t;
|
565 |
+
using std::remove_cv_t;
|
566 |
+
using std::remove_reference_t;
|
567 |
+
#else
|
568 |
+
template <bool B, typename T = void>
|
569 |
+
using enable_if_t = typename std::enable_if<B, T>::type;
|
570 |
+
template <bool B, typename T, typename F>
|
571 |
+
using conditional_t = typename std::conditional<B, T, F>::type;
|
572 |
+
template <typename T>
|
573 |
+
using remove_cv_t = typename std::remove_cv<T>::type;
|
574 |
+
template <typename T>
|
575 |
+
using remove_reference_t = typename std::remove_reference<T>::type;
|
576 |
+
#endif
|
577 |
+
|
578 |
+
#if defined(PYBIND11_CPP20)
|
579 |
+
using std::remove_cvref;
|
580 |
+
using std::remove_cvref_t;
|
581 |
+
#else
|
582 |
+
template <class T>
|
583 |
+
struct remove_cvref {
|
584 |
+
using type = remove_cv_t<remove_reference_t<T>>;
|
585 |
+
};
|
586 |
+
template <class T>
|
587 |
+
using remove_cvref_t = typename remove_cvref<T>::type;
|
588 |
+
#endif
|
589 |
+
|
590 |
+
/// Index sequences
|
591 |
+
#if defined(PYBIND11_CPP14)
|
592 |
+
using std::index_sequence;
|
593 |
+
using std::make_index_sequence;
|
594 |
+
#else
|
595 |
+
template <size_t...>
|
596 |
+
struct index_sequence {};
|
597 |
+
template <size_t N, size_t... S>
|
598 |
+
struct make_index_sequence_impl : make_index_sequence_impl<N - 1, N - 1, S...> {};
|
599 |
+
template <size_t... S>
|
600 |
+
struct make_index_sequence_impl<0, S...> {
|
601 |
+
using type = index_sequence<S...>;
|
602 |
+
};
|
603 |
+
template <size_t N>
|
604 |
+
using make_index_sequence = typename make_index_sequence_impl<N>::type;
|
605 |
+
#endif
|
606 |
+
|
607 |
+
/// Make an index sequence of the indices of true arguments
|
608 |
+
template <typename ISeq, size_t, bool...>
|
609 |
+
struct select_indices_impl {
|
610 |
+
using type = ISeq;
|
611 |
+
};
|
612 |
+
template <size_t... IPrev, size_t I, bool B, bool... Bs>
|
613 |
+
struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
|
614 |
+
: select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>,
|
615 |
+
I + 1,
|
616 |
+
Bs...> {};
|
617 |
+
template <bool... Bs>
|
618 |
+
using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
|
619 |
+
|
620 |
+
/// Backports of std::bool_constant and std::negation to accommodate older compilers
|
621 |
+
template <bool B>
|
622 |
+
using bool_constant = std::integral_constant<bool, B>;
|
623 |
+
template <typename T>
|
624 |
+
struct negation : bool_constant<!T::value> {};
|
625 |
+
|
626 |
+
// PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
|
627 |
+
// using the new one (C++14 defect, so generally works on newer compilers, even
|
628 |
+
// if not in C++17 mode)
|
629 |
+
#if defined(__PGIC__) || defined(__INTEL_COMPILER)
|
630 |
+
template <typename...>
|
631 |
+
using void_t = void;
|
632 |
+
#else
|
633 |
+
template <typename...>
|
634 |
+
struct void_t_impl {
|
635 |
+
using type = void;
|
636 |
+
};
|
637 |
+
template <typename... Ts>
|
638 |
+
using void_t = typename void_t_impl<Ts...>::type;
|
639 |
+
#endif
|
640 |
+
|
641 |
+
/// Compile-time all/any/none of that check the boolean value of all template types
|
642 |
+
#if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
|
643 |
+
template <class... Ts>
|
644 |
+
using all_of = bool_constant<(Ts::value && ...)>;
|
645 |
+
template <class... Ts>
|
646 |
+
using any_of = bool_constant<(Ts::value || ...)>;
|
647 |
+
#elif !defined(_MSC_VER)
|
648 |
+
template <bool...>
|
649 |
+
struct bools {};
|
650 |
+
template <class... Ts>
|
651 |
+
using all_of = std::is_same<bools<Ts::value..., true>, bools<true, Ts::value...>>;
|
652 |
+
template <class... Ts>
|
653 |
+
using any_of = negation<all_of<negation<Ts>...>>;
|
654 |
+
#else
|
655 |
+
// MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
|
656 |
+
// at a slight loss of compilation efficiency).
|
657 |
+
template <class... Ts>
|
658 |
+
using all_of = std::conjunction<Ts...>;
|
659 |
+
template <class... Ts>
|
660 |
+
using any_of = std::disjunction<Ts...>;
|
661 |
+
#endif
|
662 |
+
template <class... Ts>
|
663 |
+
using none_of = negation<any_of<Ts...>>;
|
664 |
+
|
665 |
+
template <class T, template <class> class... Predicates>
|
666 |
+
using satisfies_all_of = all_of<Predicates<T>...>;
|
667 |
+
template <class T, template <class> class... Predicates>
|
668 |
+
using satisfies_any_of = any_of<Predicates<T>...>;
|
669 |
+
template <class T, template <class> class... Predicates>
|
670 |
+
using satisfies_none_of = none_of<Predicates<T>...>;
|
671 |
+
|
672 |
+
/// Strip the class from a method type
|
673 |
+
template <typename T>
|
674 |
+
struct remove_class {};
|
675 |
+
template <typename C, typename R, typename... A>
|
676 |
+
struct remove_class<R (C::*)(A...)> {
|
677 |
+
using type = R(A...);
|
678 |
+
};
|
679 |
+
template <typename C, typename R, typename... A>
|
680 |
+
struct remove_class<R (C::*)(A...) const> {
|
681 |
+
using type = R(A...);
|
682 |
+
};
|
683 |
+
|
684 |
+
/// Helper template to strip away type modifiers
|
685 |
+
template <typename T>
|
686 |
+
struct intrinsic_type {
|
687 |
+
using type = T;
|
688 |
+
};
|
689 |
+
template <typename T>
|
690 |
+
struct intrinsic_type<const T> {
|
691 |
+
using type = typename intrinsic_type<T>::type;
|
692 |
+
};
|
693 |
+
template <typename T>
|
694 |
+
struct intrinsic_type<T *> {
|
695 |
+
using type = typename intrinsic_type<T>::type;
|
696 |
+
};
|
697 |
+
template <typename T>
|
698 |
+
struct intrinsic_type<T &> {
|
699 |
+
using type = typename intrinsic_type<T>::type;
|
700 |
+
};
|
701 |
+
template <typename T>
|
702 |
+
struct intrinsic_type<T &&> {
|
703 |
+
using type = typename intrinsic_type<T>::type;
|
704 |
+
};
|
705 |
+
template <typename T, size_t N>
|
706 |
+
struct intrinsic_type<const T[N]> {
|
707 |
+
using type = typename intrinsic_type<T>::type;
|
708 |
+
};
|
709 |
+
template <typename T, size_t N>
|
710 |
+
struct intrinsic_type<T[N]> {
|
711 |
+
using type = typename intrinsic_type<T>::type;
|
712 |
+
};
|
713 |
+
template <typename T>
|
714 |
+
using intrinsic_t = typename intrinsic_type<T>::type;
|
715 |
+
|
716 |
+
/// Helper type to replace 'void' in some expressions
|
717 |
+
struct void_type {};
|
718 |
+
|
719 |
+
/// Helper template which holds a list of types
|
720 |
+
template <typename...>
|
721 |
+
struct type_list {};
|
722 |
+
|
723 |
+
/// Compile-time integer sum
|
724 |
+
#ifdef __cpp_fold_expressions
|
725 |
+
template <typename... Ts>
|
726 |
+
constexpr size_t constexpr_sum(Ts... ns) {
|
727 |
+
return (0 + ... + size_t{ns});
|
728 |
+
}
|
729 |
+
#else
|
730 |
+
constexpr size_t constexpr_sum() { return 0; }
|
731 |
+
template <typename T, typename... Ts>
|
732 |
+
constexpr size_t constexpr_sum(T n, Ts... ns) {
|
733 |
+
return size_t{n} + constexpr_sum(ns...);
|
734 |
+
}
|
735 |
+
#endif
|
736 |
+
|
737 |
+
PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
|
738 |
+
/// Implementation details for constexpr functions
|
739 |
+
constexpr int first(int i) { return i; }
|
740 |
+
template <typename T, typename... Ts>
|
741 |
+
constexpr int first(int i, T v, Ts... vs) {
|
742 |
+
return v ? i : first(i + 1, vs...);
|
743 |
+
}
|
744 |
+
|
745 |
+
constexpr int last(int /*i*/, int result) { return result; }
|
746 |
+
template <typename T, typename... Ts>
|
747 |
+
constexpr int last(int i, int result, T v, Ts... vs) {
|
748 |
+
return last(i + 1, v ? i : result, vs...);
|
749 |
+
}
|
750 |
+
PYBIND11_NAMESPACE_END(constexpr_impl)
|
751 |
+
|
752 |
+
/// Return the index of the first type in Ts which satisfies Predicate<T>.
|
753 |
+
/// Returns sizeof...(Ts) if none match.
|
754 |
+
template <template <typename> class Predicate, typename... Ts>
|
755 |
+
constexpr int constexpr_first() {
|
756 |
+
return constexpr_impl::first(0, Predicate<Ts>::value...);
|
757 |
+
}
|
758 |
+
|
759 |
+
/// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
|
760 |
+
template <template <typename> class Predicate, typename... Ts>
|
761 |
+
constexpr int constexpr_last() {
|
762 |
+
return constexpr_impl::last(0, -1, Predicate<Ts>::value...);
|
763 |
+
}
|
764 |
+
|
765 |
+
/// Return the Nth element from the parameter pack
|
766 |
+
template <size_t N, typename T, typename... Ts>
|
767 |
+
struct pack_element {
|
768 |
+
using type = typename pack_element<N - 1, Ts...>::type;
|
769 |
+
};
|
770 |
+
template <typename T, typename... Ts>
|
771 |
+
struct pack_element<0, T, Ts...> {
|
772 |
+
using type = T;
|
773 |
+
};
|
774 |
+
|
775 |
+
/// Return the one and only type which matches the predicate, or Default if none match.
|
776 |
+
/// If more than one type matches the predicate, fail at compile-time.
|
777 |
+
template <template <typename> class Predicate, typename Default, typename... Ts>
|
778 |
+
struct exactly_one {
|
779 |
+
static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
|
780 |
+
static_assert(found <= 1, "Found more than one type matching the predicate");
|
781 |
+
|
782 |
+
static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
|
783 |
+
using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
|
784 |
+
};
|
785 |
+
template <template <typename> class P, typename Default>
|
786 |
+
struct exactly_one<P, Default> {
|
787 |
+
using type = Default;
|
788 |
+
};
|
789 |
+
|
790 |
+
template <template <typename> class Predicate, typename Default, typename... Ts>
|
791 |
+
using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
|
792 |
+
|
793 |
+
/// Defer the evaluation of type T until types Us are instantiated
|
794 |
+
template <typename T, typename... /*Us*/>
|
795 |
+
struct deferred_type {
|
796 |
+
using type = T;
|
797 |
+
};
|
798 |
+
template <typename T, typename... Us>
|
799 |
+
using deferred_t = typename deferred_type<T, Us...>::type;
|
800 |
+
|
801 |
+
/// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
|
802 |
+
/// unlike `std::is_base_of`)
|
803 |
+
template <typename Base, typename Derived>
|
804 |
+
using is_strict_base_of
|
805 |
+
= bool_constant<std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
|
806 |
+
|
807 |
+
/// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived
|
808 |
+
/// pointer can be converted to a Base pointer) For unions, `is_base_of<T, T>::value` is False, so
|
809 |
+
/// we need to check `is_same` as well.
|
810 |
+
template <typename Base, typename Derived>
|
811 |
+
using is_accessible_base_of
|
812 |
+
= bool_constant<(std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value)
|
813 |
+
&& std::is_convertible<Derived *, Base *>::value>;
|
814 |
+
|
815 |
+
template <template <typename...> class Base>
|
816 |
+
struct is_template_base_of_impl {
|
817 |
+
template <typename... Us>
|
818 |
+
static std::true_type check(Base<Us...> *);
|
819 |
+
static std::false_type check(...);
|
820 |
+
};
|
821 |
+
|
822 |
+
/// Check if a template is the base of a type. For example:
|
823 |
+
/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
|
824 |
+
template <template <typename...> class Base, typename T>
|
825 |
+
// Sadly, all MSVC versions incl. 2022 need the workaround, even in C++20 mode.
|
826 |
+
// See also: https://github.com/pybind/pybind11/pull/3741
|
827 |
+
#if !defined(_MSC_VER)
|
828 |
+
using is_template_base_of
|
829 |
+
= decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));
|
830 |
+
#else
|
831 |
+
struct is_template_base_of
|
832 |
+
: decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)) {
|
833 |
+
};
|
834 |
+
#endif
|
835 |
+
|
836 |
+
/// Check if T is an instantiation of the template `Class`. For example:
|
837 |
+
/// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
|
838 |
+
template <template <typename...> class Class, typename T>
|
839 |
+
struct is_instantiation : std::false_type {};
|
840 |
+
template <template <typename...> class Class, typename... Us>
|
841 |
+
struct is_instantiation<Class, Class<Us...>> : std::true_type {};
|
842 |
+
|
843 |
+
/// Check if T is std::shared_ptr<U> where U can be anything
|
844 |
+
template <typename T>
|
845 |
+
using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
|
846 |
+
|
847 |
+
/// Check if T looks like an input iterator
|
848 |
+
template <typename T, typename = void>
|
849 |
+
struct is_input_iterator : std::false_type {};
|
850 |
+
template <typename T>
|
851 |
+
struct is_input_iterator<T,
|
852 |
+
void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
|
853 |
+
: std::true_type {};
|
854 |
+
|
855 |
+
template <typename T>
|
856 |
+
using is_function_pointer
|
857 |
+
= bool_constant<std::is_pointer<T>::value
|
858 |
+
&& std::is_function<typename std::remove_pointer<T>::type>::value>;
|
859 |
+
|
860 |
+
template <typename F>
|
861 |
+
struct strip_function_object {
|
862 |
+
// If you are encountering an
|
863 |
+
// 'error: name followed by "::" must be a class or namespace name'
|
864 |
+
// with the Intel compiler and a noexcept function here,
|
865 |
+
// try to use noexcept(true) instead of plain noexcept.
|
866 |
+
using type = typename remove_class<decltype(&F::operator())>::type;
|
867 |
+
};
|
868 |
+
|
869 |
+
// Extracts the function signature from a function, function pointer or lambda.
|
870 |
+
template <typename Function, typename F = remove_reference_t<Function>>
|
871 |
+
using function_signature_t = conditional_t<
|
872 |
+
std::is_function<F>::value,
|
873 |
+
F,
|
874 |
+
typename conditional_t<std::is_pointer<F>::value || std::is_member_pointer<F>::value,
|
875 |
+
std::remove_pointer<F>,
|
876 |
+
strip_function_object<F>>::type>;
|
877 |
+
|
878 |
+
/// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
|
879 |
+
/// pointer. Note that this can catch all sorts of other things, too; this is intended to be used
|
880 |
+
/// in a place where passing a lambda makes sense.
|
881 |
+
template <typename T>
|
882 |
+
using is_lambda = satisfies_none_of<remove_reference_t<T>,
|
883 |
+
std::is_function,
|
884 |
+
std::is_pointer,
|
885 |
+
std::is_member_pointer>;
|
886 |
+
|
887 |
+
// [workaround(intel)] Internal error on fold expression
|
888 |
+
/// Apply a function over each element of a parameter pack
|
889 |
+
#if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
|
890 |
+
// Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
|
891 |
+
# define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
|
892 |
+
#else
|
893 |
+
using expand_side_effects = bool[];
|
894 |
+
# define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) \
|
895 |
+
(void) pybind11::detail::expand_side_effects { ((PATTERN), void(), false)..., false }
|
896 |
+
#endif
|
897 |
+
|
898 |
+
PYBIND11_NAMESPACE_END(detail)
|
899 |
+
|
900 |
+
#if defined(_MSC_VER)
|
901 |
+
# pragma warning(push)
|
902 |
+
# pragma warning(disable : 4275)
|
903 |
+
// warning C4275: An exported class was derived from a class that wasn't exported.
|
904 |
+
// Can be ignored when derived from a STL class.
|
905 |
+
#endif
|
906 |
+
/// C++ bindings of builtin Python exceptions
|
907 |
+
class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
|
908 |
+
public:
|
909 |
+
using std::runtime_error::runtime_error;
|
910 |
+
/// Set the error using the Python C API
|
911 |
+
virtual void set_error() const = 0;
|
912 |
+
};
|
913 |
+
#if defined(_MSC_VER)
|
914 |
+
# pragma warning(pop)
|
915 |
+
#endif
|
916 |
+
|
917 |
+
#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
|
918 |
+
class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception { \
|
919 |
+
public: \
|
920 |
+
using builtin_exception::builtin_exception; \
|
921 |
+
name() : name("") {} \
|
922 |
+
void set_error() const override { PyErr_SetString(type, what()); } \
|
923 |
+
};
|
924 |
+
|
925 |
+
PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
|
926 |
+
PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
|
927 |
+
PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
|
928 |
+
PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
|
929 |
+
PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
|
930 |
+
PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
|
931 |
+
PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
|
932 |
+
PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)
|
933 |
+
PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or
|
934 |
+
/// handle::call fail due to a type
|
935 |
+
/// casting error
|
936 |
+
PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
|
937 |
+
|
938 |
+
[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) {
|
939 |
+
assert(!PyErr_Occurred());
|
940 |
+
throw std::runtime_error(reason);
|
941 |
+
}
|
942 |
+
[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) {
|
943 |
+
assert(!PyErr_Occurred());
|
944 |
+
throw std::runtime_error(reason);
|
945 |
+
}
|
946 |
+
|
947 |
+
template <typename T, typename SFINAE = void>
|
948 |
+
struct format_descriptor {};
|
949 |
+
|
950 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
951 |
+
// Returns the index of the given type in the type char array below, and in the list in numpy.h
|
952 |
+
// The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
|
953 |
+
// complex float,double,long double. Note that the long double types only participate when long
|
954 |
+
// double is actually longer than double (it isn't under MSVC).
|
955 |
+
// NB: not only the string below but also complex.h and numpy.h rely on this order.
|
956 |
+
template <typename T, typename SFINAE = void>
|
957 |
+
struct is_fmt_numeric {
|
958 |
+
static constexpr bool value = false;
|
959 |
+
};
|
960 |
+
template <typename T>
|
961 |
+
struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
|
962 |
+
static constexpr bool value = true;
|
963 |
+
static constexpr int index
|
964 |
+
= std::is_same<T, bool>::value
|
965 |
+
? 0
|
966 |
+
: 1
|
967 |
+
+ (std::is_integral<T>::value
|
968 |
+
? detail::log2(sizeof(T)) * 2 + std::is_unsigned<T>::value
|
969 |
+
: 8
|
970 |
+
+ (std::is_same<T, double>::value ? 1
|
971 |
+
: std::is_same<T, long double>::value ? 2
|
972 |
+
: 0));
|
973 |
+
};
|
974 |
+
PYBIND11_NAMESPACE_END(detail)
|
975 |
+
|
976 |
+
template <typename T>
|
977 |
+
struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
|
978 |
+
static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
|
979 |
+
static constexpr const char value[2] = {c, '\0'};
|
980 |
+
static std::string format() { return std::string(1, c); }
|
981 |
+
};
|
982 |
+
|
983 |
+
#if !defined(PYBIND11_CPP17)
|
984 |
+
|
985 |
+
template <typename T>
|
986 |
+
constexpr const char
|
987 |
+
format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
|
988 |
+
|
989 |
+
#endif
|
990 |
+
|
991 |
+
/// RAII wrapper that temporarily clears any Python error state
|
992 |
+
struct error_scope {
|
993 |
+
PyObject *type, *value, *trace;
|
994 |
+
error_scope() { PyErr_Fetch(&type, &value, &trace); }
|
995 |
+
error_scope(const error_scope &) = delete;
|
996 |
+
error_scope &operator=(const error_scope &) = delete;
|
997 |
+
~error_scope() { PyErr_Restore(type, value, trace); }
|
998 |
+
};
|
999 |
+
|
1000 |
+
/// Dummy destructor wrapper that can be used to expose classes with a private destructor
|
1001 |
+
struct nodelete {
|
1002 |
+
template <typename T>
|
1003 |
+
void operator()(T *) {}
|
1004 |
+
};
|
1005 |
+
|
1006 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
1007 |
+
template <typename... Args>
|
1008 |
+
struct overload_cast_impl {
|
1009 |
+
template <typename Return>
|
1010 |
+
constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {
|
1011 |
+
return pf;
|
1012 |
+
}
|
1013 |
+
|
1014 |
+
template <typename Return, typename Class>
|
1015 |
+
constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
|
1016 |
+
-> decltype(pmf) {
|
1017 |
+
return pmf;
|
1018 |
+
}
|
1019 |
+
|
1020 |
+
template <typename Return, typename Class>
|
1021 |
+
constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
|
1022 |
+
-> decltype(pmf) {
|
1023 |
+
return pmf;
|
1024 |
+
}
|
1025 |
+
};
|
1026 |
+
PYBIND11_NAMESPACE_END(detail)
|
1027 |
+
|
1028 |
+
// overload_cast requires variable templates: C++14
|
1029 |
+
#if defined(PYBIND11_CPP14)
|
1030 |
+
# define PYBIND11_OVERLOAD_CAST 1
|
1031 |
+
/// Syntax sugar for resolving overloaded function pointers:
|
1032 |
+
/// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
|
1033 |
+
/// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
|
1034 |
+
template <typename... Args>
|
1035 |
+
# if (defined(_MSC_VER) && _MSC_VER < 1920) /* MSVC 2017 */ \
|
1036 |
+
|| (defined(__clang__) && __clang_major__ == 5)
|
1037 |
+
static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
|
1038 |
+
# else
|
1039 |
+
static constexpr detail::overload_cast_impl<Args...> overload_cast;
|
1040 |
+
# endif
|
1041 |
+
#endif
|
1042 |
+
|
1043 |
+
/// Const member function selector for overload_cast
|
1044 |
+
/// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
|
1045 |
+
/// - sweet: overload_cast<Arg>(&Class::func, const_)
|
1046 |
+
static constexpr auto const_ = std::true_type{};
|
1047 |
+
|
1048 |
+
#if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
|
1049 |
+
template <typename... Args>
|
1050 |
+
struct overload_cast {
|
1051 |
+
static_assert(detail::deferred_t<std::false_type, Args...>::value,
|
1052 |
+
"pybind11::overload_cast<...> requires compiling in C++14 mode");
|
1053 |
+
};
|
1054 |
+
#endif // overload_cast
|
1055 |
+
|
1056 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
1057 |
+
|
1058 |
+
// Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
|
1059 |
+
// any standard container (or C-style array) supporting std::begin/std::end, any singleton
|
1060 |
+
// arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
|
1061 |
+
template <typename T>
|
1062 |
+
class any_container {
|
1063 |
+
std::vector<T> v;
|
1064 |
+
|
1065 |
+
public:
|
1066 |
+
any_container() = default;
|
1067 |
+
|
1068 |
+
// Can construct from a pair of iterators
|
1069 |
+
template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
|
1070 |
+
any_container(It first, It last) : v(first, last) {}
|
1071 |
+
|
1072 |
+
// Implicit conversion constructor from any arbitrary container type
|
1073 |
+
// with values convertible to T
|
1074 |
+
template <typename Container,
|
1075 |
+
typename = enable_if_t<
|
1076 |
+
std::is_convertible<decltype(*std::begin(std::declval<const Container &>())),
|
1077 |
+
T>::value>>
|
1078 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
1079 |
+
any_container(const Container &c) : any_container(std::begin(c), std::end(c)) {}
|
1080 |
+
|
1081 |
+
// initializer_list's aren't deducible, so don't get matched by the above template;
|
1082 |
+
// we need this to explicitly allow implicit conversion from one:
|
1083 |
+
template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
|
1084 |
+
any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) {}
|
1085 |
+
|
1086 |
+
// Avoid copying if given an rvalue vector of the correct type.
|
1087 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
1088 |
+
any_container(std::vector<T> &&v) : v(std::move(v)) {}
|
1089 |
+
|
1090 |
+
// Moves the vector out of an rvalue any_container
|
1091 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
1092 |
+
operator std::vector<T> &&() && { return std::move(v); }
|
1093 |
+
|
1094 |
+
// Dereferencing obtains a reference to the underlying vector
|
1095 |
+
std::vector<T> &operator*() { return v; }
|
1096 |
+
const std::vector<T> &operator*() const { return v; }
|
1097 |
+
|
1098 |
+
// -> lets you call methods on the underlying vector
|
1099 |
+
std::vector<T> *operator->() { return &v; }
|
1100 |
+
const std::vector<T> *operator->() const { return &v; }
|
1101 |
+
};
|
1102 |
+
|
1103 |
+
// Forward-declaration; see detail/class.h
|
1104 |
+
std::string get_fully_qualified_tp_name(PyTypeObject *);
|
1105 |
+
|
1106 |
+
template <typename T>
|
1107 |
+
inline static std::shared_ptr<T>
|
1108 |
+
try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
|
1109 |
+
// Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
|
1110 |
+
// Use at your own risk!
|
1111 |
+
// See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
|
1112 |
+
// the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
|
1113 |
+
#if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
|
1114 |
+
return holder_value_ptr->weak_from_this().lock();
|
1115 |
+
#else
|
1116 |
+
try {
|
1117 |
+
return holder_value_ptr->shared_from_this();
|
1118 |
+
} catch (const std::bad_weak_ptr &) {
|
1119 |
+
return nullptr;
|
1120 |
+
}
|
1121 |
+
#endif
|
1122 |
+
}
|
1123 |
+
|
1124 |
+
// For silencing "unused" compiler warnings in special situations.
|
1125 |
+
template <typename... Args>
|
1126 |
+
#if defined(_MSC_VER) && _MSC_VER < 1920 // MSVC 2017
|
1127 |
+
constexpr
|
1128 |
+
#endif
|
1129 |
+
inline void
|
1130 |
+
silence_unused_warnings(Args &&...) {
|
1131 |
+
}
|
1132 |
+
|
1133 |
+
// MSVC warning C4100: Unreferenced formal parameter
|
1134 |
+
#if defined(_MSC_VER) && _MSC_VER <= 1916
|
1135 |
+
# define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...) \
|
1136 |
+
detail::silence_unused_warnings(__VA_ARGS__)
|
1137 |
+
#else
|
1138 |
+
# define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
|
1139 |
+
#endif
|
1140 |
+
|
1141 |
+
// GCC -Wunused-but-set-parameter All GCC versions (as of July 2021).
|
1142 |
+
#if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
|
1143 |
+
# define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...) \
|
1144 |
+
detail::silence_unused_warnings(__VA_ARGS__)
|
1145 |
+
#else
|
1146 |
+
# define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
|
1147 |
+
#endif
|
1148 |
+
|
1149 |
+
#if defined(_MSC_VER) // All versions (as of July 2021).
|
1150 |
+
|
1151 |
+
// warning C4127: Conditional expression is constant
|
1152 |
+
constexpr inline bool silence_msvc_c4127(bool cond) { return cond; }
|
1153 |
+
|
1154 |
+
# define PYBIND11_SILENCE_MSVC_C4127(...) ::pybind11::detail::silence_msvc_c4127(__VA_ARGS__)
|
1155 |
+
|
1156 |
+
#else
|
1157 |
+
# define PYBIND11_SILENCE_MSVC_C4127(...) __VA_ARGS__
|
1158 |
+
#endif
|
1159 |
+
|
1160 |
+
// Pybind offers detailed error messages by default for all builts that are debug (through the
|
1161 |
+
// negation of ndebug). This can also be manually enabled by users, for any builds, through
|
1162 |
+
// defining PYBIND11_DETAILED_ERROR_MESSAGES.
|
1163 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(NDEBUG)
|
1164 |
+
# define PYBIND11_DETAILED_ERROR_MESSAGES
|
1165 |
+
#endif
|
1166 |
+
|
1167 |
+
PYBIND11_NAMESPACE_END(detail)
|
1168 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
third-party/DPVO/DPViewer/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/DPViewer/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/DPViewer/pybind11/include/pybind11/detail/internals.h
ADDED
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 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 |
+
// forward decl
|
298 |
+
inline void translate_exception(std::exception_ptr);
|
299 |
+
|
300 |
+
template <class T,
|
301 |
+
enable_if_t<std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
|
302 |
+
bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
|
303 |
+
std::exception_ptr nested = exc.nested_ptr();
|
304 |
+
if (nested != nullptr && nested != p) {
|
305 |
+
translate_exception(nested);
|
306 |
+
return true;
|
307 |
+
}
|
308 |
+
return false;
|
309 |
+
}
|
310 |
+
|
311 |
+
template <class T,
|
312 |
+
enable_if_t<!std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
|
313 |
+
bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
|
314 |
+
if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {
|
315 |
+
return handle_nested_exception(*nep, p);
|
316 |
+
}
|
317 |
+
return false;
|
318 |
+
}
|
319 |
+
|
320 |
+
inline bool raise_err(PyObject *exc_type, const char *msg) {
|
321 |
+
if (PyErr_Occurred()) {
|
322 |
+
raise_from(exc_type, msg);
|
323 |
+
return true;
|
324 |
+
}
|
325 |
+
PyErr_SetString(exc_type, msg);
|
326 |
+
return false;
|
327 |
+
}
|
328 |
+
|
329 |
+
inline void translate_exception(std::exception_ptr p) {
|
330 |
+
if (!p) {
|
331 |
+
return;
|
332 |
+
}
|
333 |
+
try {
|
334 |
+
std::rethrow_exception(p);
|
335 |
+
} catch (error_already_set &e) {
|
336 |
+
handle_nested_exception(e, p);
|
337 |
+
e.restore();
|
338 |
+
return;
|
339 |
+
} catch (const builtin_exception &e) {
|
340 |
+
// Could not use template since it's an abstract class.
|
341 |
+
if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {
|
342 |
+
handle_nested_exception(*nep, p);
|
343 |
+
}
|
344 |
+
e.set_error();
|
345 |
+
return;
|
346 |
+
} catch (const std::bad_alloc &e) {
|
347 |
+
handle_nested_exception(e, p);
|
348 |
+
raise_err(PyExc_MemoryError, e.what());
|
349 |
+
return;
|
350 |
+
} catch (const std::domain_error &e) {
|
351 |
+
handle_nested_exception(e, p);
|
352 |
+
raise_err(PyExc_ValueError, e.what());
|
353 |
+
return;
|
354 |
+
} catch (const std::invalid_argument &e) {
|
355 |
+
handle_nested_exception(e, p);
|
356 |
+
raise_err(PyExc_ValueError, e.what());
|
357 |
+
return;
|
358 |
+
} catch (const std::length_error &e) {
|
359 |
+
handle_nested_exception(e, p);
|
360 |
+
raise_err(PyExc_ValueError, e.what());
|
361 |
+
return;
|
362 |
+
} catch (const std::out_of_range &e) {
|
363 |
+
handle_nested_exception(e, p);
|
364 |
+
raise_err(PyExc_IndexError, e.what());
|
365 |
+
return;
|
366 |
+
} catch (const std::range_error &e) {
|
367 |
+
handle_nested_exception(e, p);
|
368 |
+
raise_err(PyExc_ValueError, e.what());
|
369 |
+
return;
|
370 |
+
} catch (const std::overflow_error &e) {
|
371 |
+
handle_nested_exception(e, p);
|
372 |
+
raise_err(PyExc_OverflowError, e.what());
|
373 |
+
return;
|
374 |
+
} catch (const std::exception &e) {
|
375 |
+
handle_nested_exception(e, p);
|
376 |
+
raise_err(PyExc_RuntimeError, e.what());
|
377 |
+
return;
|
378 |
+
} catch (const std::nested_exception &e) {
|
379 |
+
handle_nested_exception(e, p);
|
380 |
+
raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!");
|
381 |
+
return;
|
382 |
+
} catch (...) {
|
383 |
+
raise_err(PyExc_RuntimeError, "Caught an unknown exception!");
|
384 |
+
return;
|
385 |
+
}
|
386 |
+
}
|
387 |
+
|
388 |
+
#if !defined(__GLIBCXX__)
|
389 |
+
inline void translate_local_exception(std::exception_ptr p) {
|
390 |
+
try {
|
391 |
+
if (p) {
|
392 |
+
std::rethrow_exception(p);
|
393 |
+
}
|
394 |
+
} catch (error_already_set &e) {
|
395 |
+
e.restore();
|
396 |
+
return;
|
397 |
+
} catch (const builtin_exception &e) {
|
398 |
+
e.set_error();
|
399 |
+
return;
|
400 |
+
}
|
401 |
+
}
|
402 |
+
#endif
|
403 |
+
|
404 |
+
/// Return a reference to the current `internals` data
|
405 |
+
PYBIND11_NOINLINE internals &get_internals() {
|
406 |
+
auto **&internals_pp = get_internals_pp();
|
407 |
+
if (internals_pp && *internals_pp) {
|
408 |
+
return **internals_pp;
|
409 |
+
}
|
410 |
+
|
411 |
+
// Ensure that the GIL is held since we will need to make Python calls.
|
412 |
+
// Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
|
413 |
+
struct gil_scoped_acquire_local {
|
414 |
+
gil_scoped_acquire_local() : state(PyGILState_Ensure()) {}
|
415 |
+
~gil_scoped_acquire_local() { PyGILState_Release(state); }
|
416 |
+
const PyGILState_STATE state;
|
417 |
+
} gil;
|
418 |
+
error_scope err_scope;
|
419 |
+
|
420 |
+
PYBIND11_STR_TYPE id(PYBIND11_INTERNALS_ID);
|
421 |
+
auto builtins = handle(PyEval_GetBuiltins());
|
422 |
+
if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
|
423 |
+
internals_pp = static_cast<internals **>(capsule(builtins[id]));
|
424 |
+
|
425 |
+
// We loaded builtins through python's builtins, which means that our `error_already_set`
|
426 |
+
// and `builtin_exception` may be different local classes than the ones set up in the
|
427 |
+
// initial exception translator, below, so add another for our local exception classes.
|
428 |
+
//
|
429 |
+
// libstdc++ doesn't require this (types there are identified only by name)
|
430 |
+
// libc++ with CPython doesn't require this (types are explicitly exported)
|
431 |
+
// libc++ with PyPy still need it, awaiting further investigation
|
432 |
+
#if !defined(__GLIBCXX__)
|
433 |
+
(*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
|
434 |
+
#endif
|
435 |
+
} else {
|
436 |
+
if (!internals_pp) {
|
437 |
+
internals_pp = new internals *();
|
438 |
+
}
|
439 |
+
auto *&internals_ptr = *internals_pp;
|
440 |
+
internals_ptr = new internals();
|
441 |
+
#if defined(WITH_THREAD)
|
442 |
+
|
443 |
+
# if PY_VERSION_HEX < 0x03090000
|
444 |
+
PyEval_InitThreads();
|
445 |
+
# endif
|
446 |
+
PyThreadState *tstate = PyThreadState_Get();
|
447 |
+
if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
|
448 |
+
pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
|
449 |
+
}
|
450 |
+
PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
|
451 |
+
|
452 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
453 |
+
if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
|
454 |
+
pybind11_fail("get_internals: could not successfully initialize the "
|
455 |
+
"loader_life_support TSS key!");
|
456 |
+
}
|
457 |
+
# endif
|
458 |
+
internals_ptr->istate = tstate->interp;
|
459 |
+
#endif
|
460 |
+
builtins[id] = capsule(internals_pp);
|
461 |
+
internals_ptr->registered_exception_translators.push_front(&translate_exception);
|
462 |
+
internals_ptr->static_property_type = make_static_property_type();
|
463 |
+
internals_ptr->default_metaclass = make_default_metaclass();
|
464 |
+
internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
|
465 |
+
}
|
466 |
+
return **internals_pp;
|
467 |
+
}
|
468 |
+
|
469 |
+
// the internals struct (above) is shared between all the modules. local_internals are only
|
470 |
+
// for a single module. Any changes made to internals may require an update to
|
471 |
+
// PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
|
472 |
+
// restricted to a single module. Whether a module has local internals or not should not
|
473 |
+
// impact any other modules, because the only things accessing the local internals is the
|
474 |
+
// module that contains them.
|
475 |
+
struct local_internals {
|
476 |
+
type_map<type_info *> registered_types_cpp;
|
477 |
+
std::forward_list<ExceptionTranslator> registered_exception_translators;
|
478 |
+
#if defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
|
479 |
+
|
480 |
+
// For ABI compatibility, we can't store the loader_life_support TLS key in
|
481 |
+
// the `internals` struct directly. Instead, we store it in `shared_data` and
|
482 |
+
// cache a copy in `local_internals`. If we allocated a separate TLS key for
|
483 |
+
// each instance of `local_internals`, we could end up allocating hundreds of
|
484 |
+
// TLS keys if hundreds of different pybind11 modules are loaded (which is a
|
485 |
+
// plausible number).
|
486 |
+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
|
487 |
+
|
488 |
+
// Holds the shared TLS key for the loader_life_support stack.
|
489 |
+
struct shared_loader_life_support_data {
|
490 |
+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
|
491 |
+
shared_loader_life_support_data() {
|
492 |
+
if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
|
493 |
+
pybind11_fail("local_internals: could not successfully initialize the "
|
494 |
+
"loader_life_support TLS key!");
|
495 |
+
}
|
496 |
+
}
|
497 |
+
// We can't help but leak the TLS key, because Python never unloads extension modules.
|
498 |
+
};
|
499 |
+
|
500 |
+
local_internals() {
|
501 |
+
auto &internals = get_internals();
|
502 |
+
// Get or create the `loader_life_support_stack_key`.
|
503 |
+
auto &ptr = internals.shared_data["_life_support"];
|
504 |
+
if (!ptr) {
|
505 |
+
ptr = new shared_loader_life_support_data;
|
506 |
+
}
|
507 |
+
loader_life_support_tls_key
|
508 |
+
= static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
|
509 |
+
}
|
510 |
+
#endif // defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
|
511 |
+
};
|
512 |
+
|
513 |
+
/// Works like `get_internals`, but for things which are locally registered.
|
514 |
+
inline local_internals &get_local_internals() {
|
515 |
+
static local_internals locals;
|
516 |
+
return locals;
|
517 |
+
}
|
518 |
+
|
519 |
+
/// Constructs a std::string with the given arguments, stores it in `internals`, and returns its
|
520 |
+
/// `c_str()`. Such strings objects have a long storage duration -- the internal strings are only
|
521 |
+
/// cleared when the program exits or after interpreter shutdown (when embedding), and so are
|
522 |
+
/// suitable for c-style strings needed by Python internals (such as PyTypeObject's tp_name).
|
523 |
+
template <typename... Args>
|
524 |
+
const char *c_str(Args &&...args) {
|
525 |
+
auto &strings = get_internals().static_strings;
|
526 |
+
strings.emplace_front(std::forward<Args>(args)...);
|
527 |
+
return strings.front().c_str();
|
528 |
+
}
|
529 |
+
|
530 |
+
PYBIND11_NAMESPACE_END(detail)
|
531 |
+
|
532 |
+
/// Returns a named pointer that is shared among all extension modules (using the same
|
533 |
+
/// pybind11 version) running in the current interpreter. Names starting with underscores
|
534 |
+
/// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
|
535 |
+
PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
|
536 |
+
auto &internals = detail::get_internals();
|
537 |
+
auto it = internals.shared_data.find(name);
|
538 |
+
return it != internals.shared_data.end() ? it->second : nullptr;
|
539 |
+
}
|
540 |
+
|
541 |
+
/// Set the shared data that can be later recovered by `get_shared_data()`.
|
542 |
+
PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
|
543 |
+
detail::get_internals().shared_data[name] = data;
|
544 |
+
return data;
|
545 |
+
}
|
546 |
+
|
547 |
+
/// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
|
548 |
+
/// such entry exists. Otherwise, a new object of default-constructible type `T` is
|
549 |
+
/// added to the shared data under the given name and a reference to it is returned.
|
550 |
+
template <typename T>
|
551 |
+
T &get_or_create_shared_data(const std::string &name) {
|
552 |
+
auto &internals = detail::get_internals();
|
553 |
+
auto it = internals.shared_data.find(name);
|
554 |
+
T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
|
555 |
+
if (!ptr) {
|
556 |
+
ptr = new T();
|
557 |
+
internals.shared_data[name] = ptr;
|
558 |
+
}
|
559 |
+
return *ptr;
|
560 |
+
}
|
561 |
+
|
562 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
third-party/DPVO/DPViewer/pybind11/include/pybind11/detail/type_caster_base.h
ADDED
@@ -0,0 +1,1010 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 \""
|
229 |
+
+ std::move(tname) + '"');
|
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(PYBIND11_DETAILED_ERROR_MESSAGES)
|
398 |
+
pybind11_fail("pybind11::detail::instance::get_value_and_holder: `"
|
399 |
+
+ get_fully_qualified_tp_name(find_type->type)
|
400 |
+
+ "' is not a pybind11 base of the given `"
|
401 |
+
+ get_fully_qualified_tp_name(Py_TYPE(this)) + "' instance");
|
402 |
+
#else
|
403 |
+
pybind11_fail(
|
404 |
+
"pybind11::detail::instance::get_value_and_holder: "
|
405 |
+
"type is not a pybind11 base of the given instance "
|
406 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for type details)");
|
407 |
+
#endif
|
408 |
+
}
|
409 |
+
|
410 |
+
PYBIND11_NOINLINE void instance::allocate_layout() {
|
411 |
+
const auto &tinfo = all_type_info(Py_TYPE(this));
|
412 |
+
|
413 |
+
const size_t n_types = tinfo.size();
|
414 |
+
|
415 |
+
if (n_types == 0) {
|
416 |
+
pybind11_fail(
|
417 |
+
"instance allocation failed: new instance has no pybind11-registered base types");
|
418 |
+
}
|
419 |
+
|
420 |
+
simple_layout
|
421 |
+
= n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
|
422 |
+
|
423 |
+
// Simple path: no python-side multiple inheritance, and a small-enough holder
|
424 |
+
if (simple_layout) {
|
425 |
+
simple_value_holder[0] = nullptr;
|
426 |
+
simple_holder_constructed = false;
|
427 |
+
simple_instance_registered = false;
|
428 |
+
} else { // multiple base types or a too-large holder
|
429 |
+
// Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
|
430 |
+
// [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
|
431 |
+
// values that tracks whether each associated holder has been initialized. Each [block] is
|
432 |
+
// padded, if necessary, to an integer multiple of sizeof(void *).
|
433 |
+
size_t space = 0;
|
434 |
+
for (auto *t : tinfo) {
|
435 |
+
space += 1; // value pointer
|
436 |
+
space += t->holder_size_in_ptrs; // holder instance
|
437 |
+
}
|
438 |
+
size_t flags_at = space;
|
439 |
+
space += size_in_ptrs(n_types); // status bytes (holder_constructed and
|
440 |
+
// instance_registered)
|
441 |
+
|
442 |
+
// Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
|
443 |
+
// in particular, need to be 0). Use Python's memory allocation
|
444 |
+
// functions: Python is using pymalloc, which is designed to be
|
445 |
+
// efficient for small allocations like the one we're doing here;
|
446 |
+
// for larger allocations they are just wrappers around malloc.
|
447 |
+
// TODO: is this still true for pure Python 3.6?
|
448 |
+
nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
|
449 |
+
if (!nonsimple.values_and_holders) {
|
450 |
+
throw std::bad_alloc();
|
451 |
+
}
|
452 |
+
nonsimple.status
|
453 |
+
= reinterpret_cast<std::uint8_t *>(&nonsimple.values_and_holders[flags_at]);
|
454 |
+
}
|
455 |
+
owned = true;
|
456 |
+
}
|
457 |
+
|
458 |
+
// NOLINTNEXTLINE(readability-make-member-function-const)
|
459 |
+
PYBIND11_NOINLINE void instance::deallocate_layout() {
|
460 |
+
if (!simple_layout) {
|
461 |
+
PyMem_Free(nonsimple.values_and_holders);
|
462 |
+
}
|
463 |
+
}
|
464 |
+
|
465 |
+
PYBIND11_NOINLINE bool isinstance_generic(handle obj, const std::type_info &tp) {
|
466 |
+
handle type = detail::get_type_handle(tp, false);
|
467 |
+
if (!type) {
|
468 |
+
return false;
|
469 |
+
}
|
470 |
+
return isinstance(obj, type);
|
471 |
+
}
|
472 |
+
|
473 |
+
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type) {
|
474 |
+
auto &instances = get_internals().registered_instances;
|
475 |
+
auto range = instances.equal_range(ptr);
|
476 |
+
for (auto it = range.first; it != range.second; ++it) {
|
477 |
+
for (const auto &vh : values_and_holders(it->second)) {
|
478 |
+
if (vh.type == type) {
|
479 |
+
return handle((PyObject *) it->second);
|
480 |
+
}
|
481 |
+
}
|
482 |
+
}
|
483 |
+
return handle();
|
484 |
+
}
|
485 |
+
|
486 |
+
inline PyThreadState *get_thread_state_unchecked() {
|
487 |
+
#if defined(PYPY_VERSION)
|
488 |
+
return PyThreadState_GET();
|
489 |
+
#else
|
490 |
+
return _PyThreadState_UncheckedGet();
|
491 |
+
#endif
|
492 |
+
}
|
493 |
+
|
494 |
+
// Forward declarations
|
495 |
+
void keep_alive_impl(handle nurse, handle patient);
|
496 |
+
inline PyObject *make_new_instance(PyTypeObject *type);
|
497 |
+
|
498 |
+
class type_caster_generic {
|
499 |
+
public:
|
500 |
+
PYBIND11_NOINLINE explicit type_caster_generic(const std::type_info &type_info)
|
501 |
+
: typeinfo(get_type_info(type_info)), cpptype(&type_info) {}
|
502 |
+
|
503 |
+
explicit type_caster_generic(const type_info *typeinfo)
|
504 |
+
: typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) {}
|
505 |
+
|
506 |
+
bool load(handle src, bool convert) { return load_impl<type_caster_generic>(src, convert); }
|
507 |
+
|
508 |
+
PYBIND11_NOINLINE static handle cast(const void *_src,
|
509 |
+
return_value_policy policy,
|
510 |
+
handle parent,
|
511 |
+
const detail::type_info *tinfo,
|
512 |
+
void *(*copy_constructor)(const void *),
|
513 |
+
void *(*move_constructor)(const void *),
|
514 |
+
const void *existing_holder = nullptr) {
|
515 |
+
if (!tinfo) { // no type info: error will be set already
|
516 |
+
return handle();
|
517 |
+
}
|
518 |
+
|
519 |
+
void *src = const_cast<void *>(_src);
|
520 |
+
if (src == nullptr) {
|
521 |
+
return none().release();
|
522 |
+
}
|
523 |
+
|
524 |
+
if (handle registered_inst = find_registered_python_instance(src, tinfo)) {
|
525 |
+
return registered_inst;
|
526 |
+
}
|
527 |
+
|
528 |
+
auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
|
529 |
+
auto *wrapper = reinterpret_cast<instance *>(inst.ptr());
|
530 |
+
wrapper->owned = false;
|
531 |
+
void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
|
532 |
+
|
533 |
+
switch (policy) {
|
534 |
+
case return_value_policy::automatic:
|
535 |
+
case return_value_policy::take_ownership:
|
536 |
+
valueptr = src;
|
537 |
+
wrapper->owned = true;
|
538 |
+
break;
|
539 |
+
|
540 |
+
case return_value_policy::automatic_reference:
|
541 |
+
case return_value_policy::reference:
|
542 |
+
valueptr = src;
|
543 |
+
wrapper->owned = false;
|
544 |
+
break;
|
545 |
+
|
546 |
+
case return_value_policy::copy:
|
547 |
+
if (copy_constructor) {
|
548 |
+
valueptr = copy_constructor(src);
|
549 |
+
} else {
|
550 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
551 |
+
std::string type_name(tinfo->cpptype->name());
|
552 |
+
detail::clean_type_id(type_name);
|
553 |
+
throw cast_error("return_value_policy = copy, but type " + type_name
|
554 |
+
+ " is non-copyable!");
|
555 |
+
#else
|
556 |
+
throw cast_error("return_value_policy = copy, but type is "
|
557 |
+
"non-copyable! (#define PYBIND11_DETAILED_ERROR_MESSAGES or "
|
558 |
+
"compile in debug mode for details)");
|
559 |
+
#endif
|
560 |
+
}
|
561 |
+
wrapper->owned = true;
|
562 |
+
break;
|
563 |
+
|
564 |
+
case return_value_policy::move:
|
565 |
+
if (move_constructor) {
|
566 |
+
valueptr = move_constructor(src);
|
567 |
+
} else if (copy_constructor) {
|
568 |
+
valueptr = copy_constructor(src);
|
569 |
+
} else {
|
570 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
571 |
+
std::string type_name(tinfo->cpptype->name());
|
572 |
+
detail::clean_type_id(type_name);
|
573 |
+
throw cast_error("return_value_policy = move, but type " + type_name
|
574 |
+
+ " is neither movable nor copyable!");
|
575 |
+
#else
|
576 |
+
throw cast_error("return_value_policy = move, but type is neither "
|
577 |
+
"movable nor copyable! "
|
578 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in "
|
579 |
+
"debug mode for details)");
|
580 |
+
#endif
|
581 |
+
}
|
582 |
+
wrapper->owned = true;
|
583 |
+
break;
|
584 |
+
|
585 |
+
case return_value_policy::reference_internal:
|
586 |
+
valueptr = src;
|
587 |
+
wrapper->owned = false;
|
588 |
+
keep_alive_impl(inst, parent);
|
589 |
+
break;
|
590 |
+
|
591 |
+
default:
|
592 |
+
throw cast_error("unhandled return_value_policy: should not happen!");
|
593 |
+
}
|
594 |
+
|
595 |
+
tinfo->init_instance(wrapper, existing_holder);
|
596 |
+
|
597 |
+
return inst.release();
|
598 |
+
}
|
599 |
+
|
600 |
+
// Base methods for generic caster; there are overridden in copyable_holder_caster
|
601 |
+
void load_value(value_and_holder &&v_h) {
|
602 |
+
auto *&vptr = v_h.value_ptr();
|
603 |
+
// Lazy allocation for unallocated values:
|
604 |
+
if (vptr == nullptr) {
|
605 |
+
const auto *type = v_h.type ? v_h.type : typeinfo;
|
606 |
+
if (type->operator_new) {
|
607 |
+
vptr = type->operator_new(type->type_size);
|
608 |
+
} else {
|
609 |
+
#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
|
610 |
+
if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
|
611 |
+
vptr = ::operator new(type->type_size, std::align_val_t(type->type_align));
|
612 |
+
} else {
|
613 |
+
vptr = ::operator new(type->type_size);
|
614 |
+
}
|
615 |
+
#else
|
616 |
+
vptr = ::operator new(type->type_size);
|
617 |
+
#endif
|
618 |
+
}
|
619 |
+
}
|
620 |
+
value = vptr;
|
621 |
+
}
|
622 |
+
bool try_implicit_casts(handle src, bool convert) {
|
623 |
+
for (const auto &cast : typeinfo->implicit_casts) {
|
624 |
+
type_caster_generic sub_caster(*cast.first);
|
625 |
+
if (sub_caster.load(src, convert)) {
|
626 |
+
value = cast.second(sub_caster.value);
|
627 |
+
return true;
|
628 |
+
}
|
629 |
+
}
|
630 |
+
return false;
|
631 |
+
}
|
632 |
+
bool try_direct_conversions(handle src) {
|
633 |
+
for (auto &converter : *typeinfo->direct_conversions) {
|
634 |
+
if (converter(src.ptr(), value)) {
|
635 |
+
return true;
|
636 |
+
}
|
637 |
+
}
|
638 |
+
return false;
|
639 |
+
}
|
640 |
+
void check_holder_compat() {}
|
641 |
+
|
642 |
+
PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
|
643 |
+
auto caster = type_caster_generic(ti);
|
644 |
+
if (caster.load(src, false)) {
|
645 |
+
return caster.value;
|
646 |
+
}
|
647 |
+
return nullptr;
|
648 |
+
}
|
649 |
+
|
650 |
+
/// Try to load with foreign typeinfo, if available. Used when there is no
|
651 |
+
/// native typeinfo, or when the native one wasn't able to produce a value.
|
652 |
+
PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
|
653 |
+
constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
|
654 |
+
const auto pytype = type::handle_of(src);
|
655 |
+
if (!hasattr(pytype, local_key)) {
|
656 |
+
return false;
|
657 |
+
}
|
658 |
+
|
659 |
+
type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
|
660 |
+
// Only consider this foreign loader if actually foreign and is a loader of the correct cpp
|
661 |
+
// type
|
662 |
+
if (foreign_typeinfo->module_local_load == &local_load
|
663 |
+
|| (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype))) {
|
664 |
+
return false;
|
665 |
+
}
|
666 |
+
|
667 |
+
if (auto *result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
|
668 |
+
value = result;
|
669 |
+
return true;
|
670 |
+
}
|
671 |
+
return false;
|
672 |
+
}
|
673 |
+
|
674 |
+
// Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
|
675 |
+
// bits of code between here and copyable_holder_caster where the two classes need different
|
676 |
+
// logic (without having to resort to virtual inheritance).
|
677 |
+
template <typename ThisT>
|
678 |
+
PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
|
679 |
+
if (!src) {
|
680 |
+
return false;
|
681 |
+
}
|
682 |
+
if (!typeinfo) {
|
683 |
+
return try_load_foreign_module_local(src);
|
684 |
+
}
|
685 |
+
|
686 |
+
auto &this_ = static_cast<ThisT &>(*this);
|
687 |
+
this_.check_holder_compat();
|
688 |
+
|
689 |
+
PyTypeObject *srctype = Py_TYPE(src.ptr());
|
690 |
+
|
691 |
+
// Case 1: If src is an exact type match for the target type then we can reinterpret_cast
|
692 |
+
// the instance's value pointer to the target type:
|
693 |
+
if (srctype == typeinfo->type) {
|
694 |
+
this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
|
695 |
+
return true;
|
696 |
+
}
|
697 |
+
// Case 2: We have a derived class
|
698 |
+
if (PyType_IsSubtype(srctype, typeinfo->type)) {
|
699 |
+
const auto &bases = all_type_info(srctype);
|
700 |
+
bool no_cpp_mi = typeinfo->simple_type;
|
701 |
+
|
702 |
+
// Case 2a: the python type is a Python-inherited derived class that inherits from just
|
703 |
+
// one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
|
704 |
+
// the right type and we can use reinterpret_cast.
|
705 |
+
// (This is essentially the same as case 2b, but because not using multiple inheritance
|
706 |
+
// is extremely common, we handle it specially to avoid the loop iterator and type
|
707 |
+
// pointer lookup overhead)
|
708 |
+
if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
|
709 |
+
this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
|
710 |
+
return true;
|
711 |
+
}
|
712 |
+
// Case 2b: the python type inherits from multiple C++ bases. Check the bases to see
|
713 |
+
// if we can find an exact match (or, for a simple C++ type, an inherited match); if
|
714 |
+
// so, we can safely reinterpret_cast to the relevant pointer.
|
715 |
+
if (bases.size() > 1) {
|
716 |
+
for (auto *base : bases) {
|
717 |
+
if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type)
|
718 |
+
: base->type == typeinfo->type) {
|
719 |
+
this_.load_value(
|
720 |
+
reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
|
721 |
+
return true;
|
722 |
+
}
|
723 |
+
}
|
724 |
+
}
|
725 |
+
|
726 |
+
// Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type
|
727 |
+
// match in the registered bases, above, so try implicit casting (needed for proper C++
|
728 |
+
// casting when MI is involved).
|
729 |
+
if (this_.try_implicit_casts(src, convert)) {
|
730 |
+
return true;
|
731 |
+
}
|
732 |
+
}
|
733 |
+
|
734 |
+
// Perform an implicit conversion
|
735 |
+
if (convert) {
|
736 |
+
for (const auto &converter : typeinfo->implicit_conversions) {
|
737 |
+
auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
|
738 |
+
if (load_impl<ThisT>(temp, false)) {
|
739 |
+
loader_life_support::add_patient(temp);
|
740 |
+
return true;
|
741 |
+
}
|
742 |
+
}
|
743 |
+
if (this_.try_direct_conversions(src)) {
|
744 |
+
return true;
|
745 |
+
}
|
746 |
+
}
|
747 |
+
|
748 |
+
// Failed to match local typeinfo. Try again with global.
|
749 |
+
if (typeinfo->module_local) {
|
750 |
+
if (auto *gtype = get_global_type_info(*typeinfo->cpptype)) {
|
751 |
+
typeinfo = gtype;
|
752 |
+
return load(src, false);
|
753 |
+
}
|
754 |
+
}
|
755 |
+
|
756 |
+
// Global typeinfo has precedence over foreign module_local
|
757 |
+
if (try_load_foreign_module_local(src)) {
|
758 |
+
return true;
|
759 |
+
}
|
760 |
+
|
761 |
+
// Custom converters didn't take None, now we convert None to nullptr.
|
762 |
+
if (src.is_none()) {
|
763 |
+
// Defer accepting None to other overloads (if we aren't in convert mode):
|
764 |
+
if (!convert) {
|
765 |
+
return false;
|
766 |
+
}
|
767 |
+
value = nullptr;
|
768 |
+
return true;
|
769 |
+
}
|
770 |
+
|
771 |
+
return false;
|
772 |
+
}
|
773 |
+
|
774 |
+
// Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
|
775 |
+
// isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
|
776 |
+
// with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
|
777 |
+
PYBIND11_NOINLINE static std::pair<const void *, const type_info *>
|
778 |
+
src_and_type(const void *src,
|
779 |
+
const std::type_info &cast_type,
|
780 |
+
const std::type_info *rtti_type = nullptr) {
|
781 |
+
if (auto *tpi = get_type_info(cast_type)) {
|
782 |
+
return {src, const_cast<const type_info *>(tpi)};
|
783 |
+
}
|
784 |
+
|
785 |
+
// Not found, set error:
|
786 |
+
std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
|
787 |
+
detail::clean_type_id(tname);
|
788 |
+
std::string msg = "Unregistered type : " + tname;
|
789 |
+
PyErr_SetString(PyExc_TypeError, msg.c_str());
|
790 |
+
return {nullptr, nullptr};
|
791 |
+
}
|
792 |
+
|
793 |
+
const type_info *typeinfo = nullptr;
|
794 |
+
const std::type_info *cpptype = nullptr;
|
795 |
+
void *value = nullptr;
|
796 |
+
};
|
797 |
+
|
798 |
+
/**
|
799 |
+
* Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
|
800 |
+
* needs to provide `operator T*()` and `operator T&()` operators.
|
801 |
+
*
|
802 |
+
* If the type supports moving the value away via an `operator T&&() &&` method, it should use
|
803 |
+
* `movable_cast_op_type` instead.
|
804 |
+
*/
|
805 |
+
template <typename T>
|
806 |
+
using cast_op_type = conditional_t<std::is_pointer<remove_reference_t<T>>::value,
|
807 |
+
typename std::add_pointer<intrinsic_t<T>>::type,
|
808 |
+
typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
|
809 |
+
|
810 |
+
/**
|
811 |
+
* Determine suitable casting operator for a type caster with a movable value. Such a type caster
|
812 |
+
* needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
|
813 |
+
* called in appropriate contexts where the value can be moved rather than copied.
|
814 |
+
*
|
815 |
+
* These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
|
816 |
+
*/
|
817 |
+
template <typename T>
|
818 |
+
using movable_cast_op_type
|
819 |
+
= conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
|
820 |
+
typename std::add_pointer<intrinsic_t<T>>::type,
|
821 |
+
conditional_t<std::is_rvalue_reference<T>::value,
|
822 |
+
typename std::add_rvalue_reference<intrinsic_t<T>>::type,
|
823 |
+
typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
|
824 |
+
|
825 |
+
// std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
|
826 |
+
// T is non-copyable, but code containing such a copy constructor fails to actually compile.
|
827 |
+
template <typename T, typename SFINAE = void>
|
828 |
+
struct is_copy_constructible : std::is_copy_constructible<T> {};
|
829 |
+
|
830 |
+
// Specialization for types that appear to be copy constructible but also look like stl containers
|
831 |
+
// (we specifically check for: has `value_type` and `reference` with `reference = value_type&`): if
|
832 |
+
// so, copy constructability depends on whether the value_type is copy constructible.
|
833 |
+
template <typename Container>
|
834 |
+
struct is_copy_constructible<
|
835 |
+
Container,
|
836 |
+
enable_if_t<
|
837 |
+
all_of<std::is_copy_constructible<Container>,
|
838 |
+
std::is_same<typename Container::value_type &, typename Container::reference>,
|
839 |
+
// Avoid infinite recursion
|
840 |
+
negation<std::is_same<Container, typename Container::value_type>>>::value>>
|
841 |
+
: is_copy_constructible<typename Container::value_type> {};
|
842 |
+
|
843 |
+
// Likewise for std::pair
|
844 |
+
// (after C++17 it is mandatory that the copy constructor not exist when the two types aren't
|
845 |
+
// themselves copy constructible, but this can not be relied upon when T1 or T2 are themselves
|
846 |
+
// containers).
|
847 |
+
template <typename T1, typename T2>
|
848 |
+
struct is_copy_constructible<std::pair<T1, T2>>
|
849 |
+
: all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
|
850 |
+
|
851 |
+
// The same problems arise with std::is_copy_assignable, so we use the same workaround.
|
852 |
+
template <typename T, typename SFINAE = void>
|
853 |
+
struct is_copy_assignable : std::is_copy_assignable<T> {};
|
854 |
+
template <typename Container>
|
855 |
+
struct is_copy_assignable<Container,
|
856 |
+
enable_if_t<all_of<std::is_copy_assignable<Container>,
|
857 |
+
std::is_same<typename Container::value_type &,
|
858 |
+
typename Container::reference>>::value>>
|
859 |
+
: is_copy_assignable<typename Container::value_type> {};
|
860 |
+
template <typename T1, typename T2>
|
861 |
+
struct is_copy_assignable<std::pair<T1, T2>>
|
862 |
+
: all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
|
863 |
+
|
864 |
+
PYBIND11_NAMESPACE_END(detail)
|
865 |
+
|
866 |
+
// polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed
|
867 |
+
// to by `src` actually is an instance of some class derived from `itype`.
|
868 |
+
// If so, it sets `tinfo` to point to the std::type_info representing that derived
|
869 |
+
// type, and returns a pointer to the start of the most-derived object of that type
|
870 |
+
// (in which `src` is a subobject; this will be the same address as `src` in most
|
871 |
+
// single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`
|
872 |
+
// and leaves `tinfo` at its default value of nullptr.
|
873 |
+
//
|
874 |
+
// The default polymorphic_type_hook just returns src. A specialization for polymorphic
|
875 |
+
// types determines the runtime type of the passed object and adjusts the this-pointer
|
876 |
+
// appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear
|
877 |
+
// to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is
|
878 |
+
// registered with pybind11, and this Animal is in fact a Dog).
|
879 |
+
//
|
880 |
+
// You may specialize polymorphic_type_hook yourself for types that want to appear
|
881 |
+
// polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern
|
882 |
+
// in performance-sensitive applications, used most notably in LLVM.)
|
883 |
+
//
|
884 |
+
// polymorphic_type_hook_base allows users to specialize polymorphic_type_hook with
|
885 |
+
// std::enable_if. User provided specializations will always have higher priority than
|
886 |
+
// the default implementation and specialization provided in polymorphic_type_hook_base.
|
887 |
+
template <typename itype, typename SFINAE = void>
|
888 |
+
struct polymorphic_type_hook_base {
|
889 |
+
static const void *get(const itype *src, const std::type_info *&) { return src; }
|
890 |
+
};
|
891 |
+
template <typename itype>
|
892 |
+
struct polymorphic_type_hook_base<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>> {
|
893 |
+
static const void *get(const itype *src, const std::type_info *&type) {
|
894 |
+
type = src ? &typeid(*src) : nullptr;
|
895 |
+
return dynamic_cast<const void *>(src);
|
896 |
+
}
|
897 |
+
};
|
898 |
+
template <typename itype, typename SFINAE = void>
|
899 |
+
struct polymorphic_type_hook : public polymorphic_type_hook_base<itype> {};
|
900 |
+
|
901 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
902 |
+
|
903 |
+
/// Generic type caster for objects stored on the heap
|
904 |
+
template <typename type>
|
905 |
+
class type_caster_base : public type_caster_generic {
|
906 |
+
using itype = intrinsic_t<type>;
|
907 |
+
|
908 |
+
public:
|
909 |
+
static constexpr auto name = const_name<type>();
|
910 |
+
|
911 |
+
type_caster_base() : type_caster_base(typeid(type)) {}
|
912 |
+
explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) {}
|
913 |
+
|
914 |
+
static handle cast(const itype &src, return_value_policy policy, handle parent) {
|
915 |
+
if (policy == return_value_policy::automatic
|
916 |
+
|| policy == return_value_policy::automatic_reference) {
|
917 |
+
policy = return_value_policy::copy;
|
918 |
+
}
|
919 |
+
return cast(&src, policy, parent);
|
920 |
+
}
|
921 |
+
|
922 |
+
static handle cast(itype &&src, return_value_policy, handle parent) {
|
923 |
+
return cast(&src, return_value_policy::move, parent);
|
924 |
+
}
|
925 |
+
|
926 |
+
// Returns a (pointer, type_info) pair taking care of necessary type lookup for a
|
927 |
+
// polymorphic type (using RTTI by default, but can be overridden by specializing
|
928 |
+
// polymorphic_type_hook). If the instance isn't derived, returns the base version.
|
929 |
+
static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
|
930 |
+
const auto &cast_type = typeid(itype);
|
931 |
+
const std::type_info *instance_type = nullptr;
|
932 |
+
const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
|
933 |
+
if (instance_type && !same_type(cast_type, *instance_type)) {
|
934 |
+
// This is a base pointer to a derived type. If the derived type is registered
|
935 |
+
// with pybind11, we want to make the full derived object available.
|
936 |
+
// In the typical case where itype is polymorphic, we get the correct
|
937 |
+
// derived pointer (which may be != base pointer) by a dynamic_cast to
|
938 |
+
// most derived type. If itype is not polymorphic, we won't get here
|
939 |
+
// except via a user-provided specialization of polymorphic_type_hook,
|
940 |
+
// and the user has promised that no this-pointer adjustment is
|
941 |
+
// required in that case, so it's OK to use static_cast.
|
942 |
+
if (const auto *tpi = get_type_info(*instance_type)) {
|
943 |
+
return {vsrc, tpi};
|
944 |
+
}
|
945 |
+
}
|
946 |
+
// Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer,
|
947 |
+
// so don't do a cast
|
948 |
+
return type_caster_generic::src_and_type(src, cast_type, instance_type);
|
949 |
+
}
|
950 |
+
|
951 |
+
static handle cast(const itype *src, return_value_policy policy, handle parent) {
|
952 |
+
auto st = src_and_type(src);
|
953 |
+
return type_caster_generic::cast(st.first,
|
954 |
+
policy,
|
955 |
+
parent,
|
956 |
+
st.second,
|
957 |
+
make_copy_constructor(src),
|
958 |
+
make_move_constructor(src));
|
959 |
+
}
|
960 |
+
|
961 |
+
static handle cast_holder(const itype *src, const void *holder) {
|
962 |
+
auto st = src_and_type(src);
|
963 |
+
return type_caster_generic::cast(st.first,
|
964 |
+
return_value_policy::take_ownership,
|
965 |
+
{},
|
966 |
+
st.second,
|
967 |
+
nullptr,
|
968 |
+
nullptr,
|
969 |
+
holder);
|
970 |
+
}
|
971 |
+
|
972 |
+
template <typename T>
|
973 |
+
using cast_op_type = detail::cast_op_type<T>;
|
974 |
+
|
975 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
976 |
+
operator itype *() { return (type *) value; }
|
977 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
978 |
+
operator itype &() {
|
979 |
+
if (!value) {
|
980 |
+
throw reference_cast_error();
|
981 |
+
}
|
982 |
+
return *((itype *) value);
|
983 |
+
}
|
984 |
+
|
985 |
+
protected:
|
986 |
+
using Constructor = void *(*) (const void *);
|
987 |
+
|
988 |
+
/* Only enabled when the types are {copy,move}-constructible *and* when the type
|
989 |
+
does not have a private operator new implementation. A comma operator is used in the
|
990 |
+
decltype argument to apply SFINAE to the public copy/move constructors.*/
|
991 |
+
template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
|
992 |
+
static auto make_copy_constructor(const T *)
|
993 |
+
-> decltype(new T(std::declval<const T>()), Constructor{}) {
|
994 |
+
return [](const void *arg) -> void * { return new T(*reinterpret_cast<const T *>(arg)); };
|
995 |
+
}
|
996 |
+
|
997 |
+
template <typename T, typename = enable_if_t<std::is_move_constructible<T>::value>>
|
998 |
+
static auto make_move_constructor(const T *)
|
999 |
+
-> decltype(new T(std::declval<T &&>()), Constructor{}) {
|
1000 |
+
return [](const void *arg) -> void * {
|
1001 |
+
return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
|
1002 |
+
};
|
1003 |
+
}
|
1004 |
+
|
1005 |
+
static Constructor make_copy_constructor(...) { return nullptr; }
|
1006 |
+
static Constructor make_move_constructor(...) { return nullptr; }
|
1007 |
+
};
|
1008 |
+
|
1009 |
+
PYBIND11_NAMESPACE_END(detail)
|
1010 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
third-party/DPVO/DPViewer/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/DPViewer/pybind11/include/pybind11/eigen.h
ADDED
@@ -0,0 +1,702 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# pragma warning(disable : 5054) // https://github.com/pybind/pybind11/pull/3741
|
29 |
+
// C5054: operator '&': deprecated between enumerations of different types
|
30 |
+
#endif
|
31 |
+
|
32 |
+
#include <Eigen/Core>
|
33 |
+
#include <Eigen/SparseCore>
|
34 |
+
|
35 |
+
#if defined(_MSC_VER)
|
36 |
+
# pragma warning(pop)
|
37 |
+
#endif
|
38 |
+
|
39 |
+
// Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
|
40 |
+
// move constructors that break things. We could detect this an explicitly copy, but an extra copy
|
41 |
+
// of matrices seems highly undesirable.
|
42 |
+
static_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),
|
43 |
+
"Eigen support in pybind11 requires Eigen >= 3.2.7");
|
44 |
+
|
45 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
46 |
+
|
47 |
+
// Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
|
48 |
+
using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
|
49 |
+
template <typename MatrixType>
|
50 |
+
using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;
|
51 |
+
template <typename MatrixType>
|
52 |
+
using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
|
53 |
+
|
54 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
55 |
+
|
56 |
+
#if EIGEN_VERSION_AT_LEAST(3, 3, 0)
|
57 |
+
using EigenIndex = Eigen::Index;
|
58 |
+
template <typename Scalar, int Flags, typename StorageIndex>
|
59 |
+
using EigenMapSparseMatrix = Eigen::Map<Eigen::SparseMatrix<Scalar, Flags, StorageIndex>>;
|
60 |
+
#else
|
61 |
+
using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
|
62 |
+
template <typename Scalar, int Flags, typename StorageIndex>
|
63 |
+
using EigenMapSparseMatrix = Eigen::MappedSparseMatrix<Scalar, Flags, StorageIndex>;
|
64 |
+
#endif
|
65 |
+
|
66 |
+
// Matches Eigen::Map, Eigen::Ref, blocks, etc:
|
67 |
+
template <typename T>
|
68 |
+
using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>,
|
69 |
+
std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
|
70 |
+
template <typename T>
|
71 |
+
using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
|
72 |
+
template <typename T>
|
73 |
+
using is_eigen_dense_plain
|
74 |
+
= all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>;
|
75 |
+
template <typename T>
|
76 |
+
using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>;
|
77 |
+
// Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This
|
78 |
+
// basically covers anything that can be assigned to a dense matrix but that don't have a typical
|
79 |
+
// matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and
|
80 |
+
// SelfAdjointView fall into this category.
|
81 |
+
template <typename T>
|
82 |
+
using is_eigen_other
|
83 |
+
= all_of<is_template_base_of<Eigen::EigenBase, T>,
|
84 |
+
negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>>;
|
85 |
+
|
86 |
+
// Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
|
87 |
+
template <bool EigenRowMajor>
|
88 |
+
struct EigenConformable {
|
89 |
+
bool conformable = false;
|
90 |
+
EigenIndex rows = 0, cols = 0;
|
91 |
+
EigenDStride stride{0, 0}; // Only valid if negativestrides is false!
|
92 |
+
bool negativestrides = false; // If true, do not use stride!
|
93 |
+
|
94 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
95 |
+
EigenConformable(bool fits = false) : conformable{fits} {}
|
96 |
+
// Matrix type:
|
97 |
+
EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)
|
98 |
+
: conformable{true}, rows{r}, cols{c},
|
99 |
+
// TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.
|
100 |
+
// http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
|
101 |
+
stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)
|
102 |
+
: (cstride > 0 ? cstride : 0) /* outer stride */,
|
103 |
+
EigenRowMajor ? (cstride > 0 ? cstride : 0)
|
104 |
+
: (rstride > 0 ? rstride : 0) /* inner stride */},
|
105 |
+
negativestrides{rstride < 0 || cstride < 0} {}
|
106 |
+
// Vector type:
|
107 |
+
EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)
|
108 |
+
: EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}
|
109 |
+
|
110 |
+
template <typename props>
|
111 |
+
bool stride_compatible() const {
|
112 |
+
// To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
|
113 |
+
// matching strides, or a dimension size of 1 (in which case the stride value is
|
114 |
+
// irrelevant)
|
115 |
+
return !negativestrides
|
116 |
+
&& (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()
|
117 |
+
|| (EigenRowMajor ? cols : rows) == 1)
|
118 |
+
&& (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()
|
119 |
+
|| (EigenRowMajor ? rows : cols) == 1);
|
120 |
+
}
|
121 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
122 |
+
operator bool() const { return conformable; }
|
123 |
+
};
|
124 |
+
|
125 |
+
template <typename Type>
|
126 |
+
struct eigen_extract_stride {
|
127 |
+
using type = Type;
|
128 |
+
};
|
129 |
+
template <typename PlainObjectType, int MapOptions, typename StrideType>
|
130 |
+
struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> {
|
131 |
+
using type = StrideType;
|
132 |
+
};
|
133 |
+
template <typename PlainObjectType, int Options, typename StrideType>
|
134 |
+
struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> {
|
135 |
+
using type = StrideType;
|
136 |
+
};
|
137 |
+
|
138 |
+
// Helper struct for extracting information from an Eigen type
|
139 |
+
template <typename Type_>
|
140 |
+
struct EigenProps {
|
141 |
+
using Type = Type_;
|
142 |
+
using Scalar = typename Type::Scalar;
|
143 |
+
using StrideType = typename eigen_extract_stride<Type>::type;
|
144 |
+
static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,
|
145 |
+
size = Type::SizeAtCompileTime;
|
146 |
+
static constexpr bool row_major = Type::IsRowMajor,
|
147 |
+
vector
|
148 |
+
= Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
|
149 |
+
fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,
|
150 |
+
fixed = size != Eigen::Dynamic, // Fully-fixed size
|
151 |
+
dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
|
152 |
+
|
153 |
+
template <EigenIndex i, EigenIndex ifzero>
|
154 |
+
using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
|
155 |
+
static constexpr EigenIndex inner_stride
|
156 |
+
= if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,
|
157 |
+
outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,
|
158 |
+
vector ? size
|
159 |
+
: row_major ? cols
|
160 |
+
: rows > ::value;
|
161 |
+
static constexpr bool dynamic_stride
|
162 |
+
= inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
|
163 |
+
static constexpr bool requires_row_major
|
164 |
+
= !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
|
165 |
+
static constexpr bool requires_col_major
|
166 |
+
= !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
|
167 |
+
|
168 |
+
// Takes an input array and determines whether we can make it fit into the Eigen type. If
|
169 |
+
// the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
|
170 |
+
// (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
|
171 |
+
static EigenConformable<row_major> conformable(const array &a) {
|
172 |
+
const auto dims = a.ndim();
|
173 |
+
if (dims < 1 || dims > 2) {
|
174 |
+
return false;
|
175 |
+
}
|
176 |
+
|
177 |
+
if (dims == 2) { // Matrix type: require exact match (or dynamic)
|
178 |
+
|
179 |
+
EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),
|
180 |
+
np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),
|
181 |
+
np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));
|
182 |
+
if ((PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && np_rows != rows)
|
183 |
+
|| (PYBIND11_SILENCE_MSVC_C4127(fixed_cols) && np_cols != cols)) {
|
184 |
+
return false;
|
185 |
+
}
|
186 |
+
|
187 |
+
return {np_rows, np_cols, np_rstride, np_cstride};
|
188 |
+
}
|
189 |
+
|
190 |
+
// Otherwise we're storing an n-vector. Only one of the strides will be used, but
|
191 |
+
// whichever is used, we want the (single) numpy stride value.
|
192 |
+
const EigenIndex n = a.shape(0),
|
193 |
+
stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));
|
194 |
+
|
195 |
+
if (vector) { // Eigen type is a compile-time vector
|
196 |
+
if (PYBIND11_SILENCE_MSVC_C4127(fixed) && size != n) {
|
197 |
+
return false; // Vector size mismatch
|
198 |
+
}
|
199 |
+
return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
|
200 |
+
}
|
201 |
+
if (fixed) {
|
202 |
+
// The type has a fixed size, but is not a vector: abort
|
203 |
+
return false;
|
204 |
+
}
|
205 |
+
if (fixed_cols) {
|
206 |
+
// Since this isn't a vector, cols must be != 1. We allow this only if it exactly
|
207 |
+
// equals the number of elements (rows is Dynamic, and so 1 row is allowed).
|
208 |
+
if (cols != n) {
|
209 |
+
return false;
|
210 |
+
}
|
211 |
+
return {1, n, stride};
|
212 |
+
} // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
|
213 |
+
if (PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && rows != n) {
|
214 |
+
return false;
|
215 |
+
}
|
216 |
+
return {n, 1, stride};
|
217 |
+
}
|
218 |
+
|
219 |
+
static constexpr bool show_writeable
|
220 |
+
= is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;
|
221 |
+
static constexpr bool show_order = is_eigen_dense_map<Type>::value;
|
222 |
+
static constexpr bool show_c_contiguous = show_order && requires_row_major;
|
223 |
+
static constexpr bool show_f_contiguous
|
224 |
+
= !show_c_contiguous && show_order && requires_col_major;
|
225 |
+
|
226 |
+
static constexpr auto descriptor
|
227 |
+
= const_name("numpy.ndarray[") + npy_format_descriptor<Scalar>::name + const_name("[")
|
228 |
+
+ const_name<fixed_rows>(const_name<(size_t) rows>(), const_name("m")) + const_name(", ")
|
229 |
+
+ const_name<fixed_cols>(const_name<(size_t) cols>(), const_name("n")) + const_name("]")
|
230 |
+
+
|
231 |
+
// For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to
|
232 |
+
// be satisfied: writeable=True (for a mutable reference), and, depending on the map's
|
233 |
+
// stride options, possibly f_contiguous or c_contiguous. We include them in the
|
234 |
+
// descriptor output to provide some hint as to why a TypeError is occurring (otherwise
|
235 |
+
// it can be confusing to see that a function accepts a 'numpy.ndarray[float64[3,2]]' and
|
236 |
+
// an error message that you *gave* a numpy.ndarray of the right type and dimensions.
|
237 |
+
const_name<show_writeable>(", flags.writeable", "")
|
238 |
+
+ const_name<show_c_contiguous>(", flags.c_contiguous", "")
|
239 |
+
+ const_name<show_f_contiguous>(", flags.f_contiguous", "") + const_name("]");
|
240 |
+
};
|
241 |
+
|
242 |
+
// Casts an Eigen type to numpy array. If given a base, the numpy array references the src data,
|
243 |
+
// otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array.
|
244 |
+
template <typename props>
|
245 |
+
handle
|
246 |
+
eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
|
247 |
+
constexpr ssize_t elem_size = sizeof(typename props::Scalar);
|
248 |
+
array a;
|
249 |
+
if (props::vector) {
|
250 |
+
a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);
|
251 |
+
} else {
|
252 |
+
a = array({src.rows(), src.cols()},
|
253 |
+
{elem_size * src.rowStride(), elem_size * src.colStride()},
|
254 |
+
src.data(),
|
255 |
+
base);
|
256 |
+
}
|
257 |
+
|
258 |
+
if (!writeable) {
|
259 |
+
array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
|
260 |
+
}
|
261 |
+
|
262 |
+
return a.release();
|
263 |
+
}
|
264 |
+
|
265 |
+
// Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
|
266 |
+
// reference the Eigen object's data with `base` as the python-registered base class (if omitted,
|
267 |
+
// the base will be set to None, and lifetime management is up to the caller). The numpy array is
|
268 |
+
// non-writeable if the given type is const.
|
269 |
+
template <typename props, typename Type>
|
270 |
+
handle eigen_ref_array(Type &src, handle parent = none()) {
|
271 |
+
// none here is to get past array's should-we-copy detection, which currently always
|
272 |
+
// copies when there is no base. Setting the base to None should be harmless.
|
273 |
+
return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
|
274 |
+
}
|
275 |
+
|
276 |
+
// Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a
|
277 |
+
// numpy array that references the encapsulated data with a python-side reference to the capsule to
|
278 |
+
// tie its destruction to that of any dependent python objects. Const-ness is determined by
|
279 |
+
// whether or not the Type of the pointer given is const.
|
280 |
+
template <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>>
|
281 |
+
handle eigen_encapsulate(Type *src) {
|
282 |
+
capsule base(src, [](void *o) { delete static_cast<Type *>(o); });
|
283 |
+
return eigen_ref_array<props>(*src, base);
|
284 |
+
}
|
285 |
+
|
286 |
+
// Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
|
287 |
+
// types.
|
288 |
+
template <typename Type>
|
289 |
+
struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {
|
290 |
+
using Scalar = typename Type::Scalar;
|
291 |
+
using props = EigenProps<Type>;
|
292 |
+
|
293 |
+
bool load(handle src, bool convert) {
|
294 |
+
// If we're in no-convert mode, only load if given an array of the correct type
|
295 |
+
if (!convert && !isinstance<array_t<Scalar>>(src)) {
|
296 |
+
return false;
|
297 |
+
}
|
298 |
+
|
299 |
+
// Coerce into an array, but don't do type conversion yet; the copy below handles it.
|
300 |
+
auto buf = array::ensure(src);
|
301 |
+
|
302 |
+
if (!buf) {
|
303 |
+
return false;
|
304 |
+
}
|
305 |
+
|
306 |
+
auto dims = buf.ndim();
|
307 |
+
if (dims < 1 || dims > 2) {
|
308 |
+
return false;
|
309 |
+
}
|
310 |
+
|
311 |
+
auto fits = props::conformable(buf);
|
312 |
+
if (!fits) {
|
313 |
+
return false;
|
314 |
+
}
|
315 |
+
|
316 |
+
// Allocate the new type, then build a numpy reference into it
|
317 |
+
value = Type(fits.rows, fits.cols);
|
318 |
+
auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value));
|
319 |
+
if (dims == 1) {
|
320 |
+
ref = ref.squeeze();
|
321 |
+
} else if (ref.ndim() == 1) {
|
322 |
+
buf = buf.squeeze();
|
323 |
+
}
|
324 |
+
|
325 |
+
int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());
|
326 |
+
|
327 |
+
if (result < 0) { // Copy failed!
|
328 |
+
PyErr_Clear();
|
329 |
+
return false;
|
330 |
+
}
|
331 |
+
|
332 |
+
return true;
|
333 |
+
}
|
334 |
+
|
335 |
+
private:
|
336 |
+
// Cast implementation
|
337 |
+
template <typename CType>
|
338 |
+
static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
|
339 |
+
switch (policy) {
|
340 |
+
case return_value_policy::take_ownership:
|
341 |
+
case return_value_policy::automatic:
|
342 |
+
return eigen_encapsulate<props>(src);
|
343 |
+
case return_value_policy::move:
|
344 |
+
return eigen_encapsulate<props>(new CType(std::move(*src)));
|
345 |
+
case return_value_policy::copy:
|
346 |
+
return eigen_array_cast<props>(*src);
|
347 |
+
case return_value_policy::reference:
|
348 |
+
case return_value_policy::automatic_reference:
|
349 |
+
return eigen_ref_array<props>(*src);
|
350 |
+
case return_value_policy::reference_internal:
|
351 |
+
return eigen_ref_array<props>(*src, parent);
|
352 |
+
default:
|
353 |
+
throw cast_error("unhandled return_value_policy: should not happen!");
|
354 |
+
};
|
355 |
+
}
|
356 |
+
|
357 |
+
public:
|
358 |
+
// Normal returned non-reference, non-const value:
|
359 |
+
static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
|
360 |
+
return cast_impl(&src, return_value_policy::move, parent);
|
361 |
+
}
|
362 |
+
// If you return a non-reference const, we mark the numpy array readonly:
|
363 |
+
static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
|
364 |
+
return cast_impl(&src, return_value_policy::move, parent);
|
365 |
+
}
|
366 |
+
// lvalue reference return; default (automatic) becomes copy
|
367 |
+
static handle cast(Type &src, return_value_policy policy, handle parent) {
|
368 |
+
if (policy == return_value_policy::automatic
|
369 |
+
|| policy == return_value_policy::automatic_reference) {
|
370 |
+
policy = return_value_policy::copy;
|
371 |
+
}
|
372 |
+
return cast_impl(&src, policy, parent);
|
373 |
+
}
|
374 |
+
// const lvalue reference return; default (automatic) becomes copy
|
375 |
+
static handle cast(const Type &src, return_value_policy policy, handle parent) {
|
376 |
+
if (policy == return_value_policy::automatic
|
377 |
+
|| policy == return_value_policy::automatic_reference) {
|
378 |
+
policy = return_value_policy::copy;
|
379 |
+
}
|
380 |
+
return cast(&src, policy, parent);
|
381 |
+
}
|
382 |
+
// non-const pointer return
|
383 |
+
static handle cast(Type *src, return_value_policy policy, handle parent) {
|
384 |
+
return cast_impl(src, policy, parent);
|
385 |
+
}
|
386 |
+
// const pointer return
|
387 |
+
static handle cast(const Type *src, return_value_policy policy, handle parent) {
|
388 |
+
return cast_impl(src, policy, parent);
|
389 |
+
}
|
390 |
+
|
391 |
+
static constexpr auto name = props::descriptor;
|
392 |
+
|
393 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
394 |
+
operator Type *() { return &value; }
|
395 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
396 |
+
operator Type &() { return value; }
|
397 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
398 |
+
operator Type &&() && { return std::move(value); }
|
399 |
+
template <typename T>
|
400 |
+
using cast_op_type = movable_cast_op_type<T>;
|
401 |
+
|
402 |
+
private:
|
403 |
+
Type value;
|
404 |
+
};
|
405 |
+
|
406 |
+
// Base class for casting reference/map/block/etc. objects back to python.
|
407 |
+
template <typename MapType>
|
408 |
+
struct eigen_map_caster {
|
409 |
+
private:
|
410 |
+
using props = EigenProps<MapType>;
|
411 |
+
|
412 |
+
public:
|
413 |
+
// Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
|
414 |
+
// to stay around), but we'll allow it under the assumption that you know what you're doing
|
415 |
+
// (and have an appropriate keep_alive in place). We return a numpy array pointing directly at
|
416 |
+
// the ref's data (The numpy array ends up read-only if the ref was to a const matrix type.)
|
417 |
+
// Note that this means you need to ensure you don't destroy the object in some other way (e.g.
|
418 |
+
// with an appropriate keep_alive, or with a reference to a statically allocated matrix).
|
419 |
+
static handle cast(const MapType &src, return_value_policy policy, handle parent) {
|
420 |
+
switch (policy) {
|
421 |
+
case return_value_policy::copy:
|
422 |
+
return eigen_array_cast<props>(src);
|
423 |
+
case return_value_policy::reference_internal:
|
424 |
+
return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value);
|
425 |
+
case return_value_policy::reference:
|
426 |
+
case return_value_policy::automatic:
|
427 |
+
case return_value_policy::automatic_reference:
|
428 |
+
return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value);
|
429 |
+
default:
|
430 |
+
// move, take_ownership don't make any sense for a ref/map:
|
431 |
+
pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type");
|
432 |
+
}
|
433 |
+
}
|
434 |
+
|
435 |
+
static constexpr auto name = props::descriptor;
|
436 |
+
|
437 |
+
// Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
|
438 |
+
// types but not bound arguments). We still provide them (with an explicitly delete) so that
|
439 |
+
// you end up here if you try anyway.
|
440 |
+
bool load(handle, bool) = delete;
|
441 |
+
operator MapType() = delete;
|
442 |
+
template <typename>
|
443 |
+
using cast_op_type = MapType;
|
444 |
+
};
|
445 |
+
|
446 |
+
// We can return any map-like object (but can only load Refs, specialized next):
|
447 |
+
template <typename Type>
|
448 |
+
struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> : eigen_map_caster<Type> {};
|
449 |
+
|
450 |
+
// Loader for Ref<...> arguments. See the documentation for info on how to make this work without
|
451 |
+
// copying (it requires some extra effort in many cases).
|
452 |
+
template <typename PlainObjectType, typename StrideType>
|
453 |
+
struct type_caster<
|
454 |
+
Eigen::Ref<PlainObjectType, 0, StrideType>,
|
455 |
+
enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>>
|
456 |
+
: public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
|
457 |
+
private:
|
458 |
+
using Type = Eigen::Ref<PlainObjectType, 0, StrideType>;
|
459 |
+
using props = EigenProps<Type>;
|
460 |
+
using Scalar = typename props::Scalar;
|
461 |
+
using MapType = Eigen::Map<PlainObjectType, 0, StrideType>;
|
462 |
+
using Array
|
463 |
+
= array_t<Scalar,
|
464 |
+
array::forcecast
|
465 |
+
| ((props::row_major ? props::inner_stride : props::outer_stride) == 1
|
466 |
+
? array::c_style
|
467 |
+
: (props::row_major ? props::outer_stride : props::inner_stride) == 1
|
468 |
+
? array::f_style
|
469 |
+
: 0)>;
|
470 |
+
static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
|
471 |
+
// Delay construction (these have no default constructor)
|
472 |
+
std::unique_ptr<MapType> map;
|
473 |
+
std::unique_ptr<Type> ref;
|
474 |
+
// Our array. When possible, this is just a numpy array pointing to the source data, but
|
475 |
+
// sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an
|
476 |
+
// incompatible layout, or is an array of a type that needs to be converted). Using a numpy
|
477 |
+
// temporary (rather than an Eigen temporary) saves an extra copy when we need both type
|
478 |
+
// conversion and storage order conversion. (Note that we refuse to use this temporary copy
|
479 |
+
// when loading an argument for a Ref<M> with M non-const, i.e. a read-write reference).
|
480 |
+
Array copy_or_ref;
|
481 |
+
|
482 |
+
public:
|
483 |
+
bool load(handle src, bool convert) {
|
484 |
+
// First check whether what we have is already an array of the right type. If not, we
|
485 |
+
// can't avoid a copy (because the copy is also going to do type conversion).
|
486 |
+
bool need_copy = !isinstance<Array>(src);
|
487 |
+
|
488 |
+
EigenConformable<props::row_major> fits;
|
489 |
+
if (!need_copy) {
|
490 |
+
// We don't need a converting copy, but we also need to check whether the strides are
|
491 |
+
// compatible with the Ref's stride requirements
|
492 |
+
auto aref = reinterpret_borrow<Array>(src);
|
493 |
+
|
494 |
+
if (aref && (!need_writeable || aref.writeable())) {
|
495 |
+
fits = props::conformable(aref);
|
496 |
+
if (!fits) {
|
497 |
+
return false; // Incompatible dimensions
|
498 |
+
}
|
499 |
+
if (!fits.template stride_compatible<props>()) {
|
500 |
+
need_copy = true;
|
501 |
+
} else {
|
502 |
+
copy_or_ref = std::move(aref);
|
503 |
+
}
|
504 |
+
} else {
|
505 |
+
need_copy = true;
|
506 |
+
}
|
507 |
+
}
|
508 |
+
|
509 |
+
if (need_copy) {
|
510 |
+
// We need to copy: If we need a mutable reference, or we're not supposed to convert
|
511 |
+
// (either because we're in the no-convert overload pass, or because we're explicitly
|
512 |
+
// instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
|
513 |
+
if (!convert || need_writeable) {
|
514 |
+
return false;
|
515 |
+
}
|
516 |
+
|
517 |
+
Array copy = Array::ensure(src);
|
518 |
+
if (!copy) {
|
519 |
+
return false;
|
520 |
+
}
|
521 |
+
fits = props::conformable(copy);
|
522 |
+
if (!fits || !fits.template stride_compatible<props>()) {
|
523 |
+
return false;
|
524 |
+
}
|
525 |
+
copy_or_ref = std::move(copy);
|
526 |
+
loader_life_support::add_patient(copy_or_ref);
|
527 |
+
}
|
528 |
+
|
529 |
+
ref.reset();
|
530 |
+
map.reset(new MapType(data(copy_or_ref),
|
531 |
+
fits.rows,
|
532 |
+
fits.cols,
|
533 |
+
make_stride(fits.stride.outer(), fits.stride.inner())));
|
534 |
+
ref.reset(new Type(*map));
|
535 |
+
|
536 |
+
return true;
|
537 |
+
}
|
538 |
+
|
539 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
540 |
+
operator Type *() { return ref.get(); }
|
541 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
542 |
+
operator Type &() { return *ref; }
|
543 |
+
template <typename _T>
|
544 |
+
using cast_op_type = pybind11::detail::cast_op_type<_T>;
|
545 |
+
|
546 |
+
private:
|
547 |
+
template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0>
|
548 |
+
Scalar *data(Array &a) {
|
549 |
+
return a.mutable_data();
|
550 |
+
}
|
551 |
+
|
552 |
+
template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0>
|
553 |
+
const Scalar *data(Array &a) {
|
554 |
+
return a.data();
|
555 |
+
}
|
556 |
+
|
557 |
+
// Attempt to figure out a constructor of `Stride` that will work.
|
558 |
+
// If both strides are fixed, use a default constructor:
|
559 |
+
template <typename S>
|
560 |
+
using stride_ctor_default = bool_constant<S::InnerStrideAtCompileTime != Eigen::Dynamic
|
561 |
+
&& S::OuterStrideAtCompileTime != Eigen::Dynamic
|
562 |
+
&& std::is_default_constructible<S>::value>;
|
563 |
+
// Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
|
564 |
+
// Eigen::Stride, and use it:
|
565 |
+
template <typename S>
|
566 |
+
using stride_ctor_dual
|
567 |
+
= bool_constant<!stride_ctor_default<S>::value
|
568 |
+
&& std::is_constructible<S, EigenIndex, EigenIndex>::value>;
|
569 |
+
// Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
|
570 |
+
// it (passing whichever stride is dynamic).
|
571 |
+
template <typename S>
|
572 |
+
using stride_ctor_outer
|
573 |
+
= bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
|
574 |
+
&& S::OuterStrideAtCompileTime == Eigen::Dynamic
|
575 |
+
&& S::InnerStrideAtCompileTime != Eigen::Dynamic
|
576 |
+
&& std::is_constructible<S, EigenIndex>::value>;
|
577 |
+
template <typename S>
|
578 |
+
using stride_ctor_inner
|
579 |
+
= bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
|
580 |
+
&& S::InnerStrideAtCompileTime == Eigen::Dynamic
|
581 |
+
&& S::OuterStrideAtCompileTime != Eigen::Dynamic
|
582 |
+
&& std::is_constructible<S, EigenIndex>::value>;
|
583 |
+
|
584 |
+
template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0>
|
585 |
+
static S make_stride(EigenIndex, EigenIndex) {
|
586 |
+
return S();
|
587 |
+
}
|
588 |
+
template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0>
|
589 |
+
static S make_stride(EigenIndex outer, EigenIndex inner) {
|
590 |
+
return S(outer, inner);
|
591 |
+
}
|
592 |
+
template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0>
|
593 |
+
static S make_stride(EigenIndex outer, EigenIndex) {
|
594 |
+
return S(outer);
|
595 |
+
}
|
596 |
+
template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0>
|
597 |
+
static S make_stride(EigenIndex, EigenIndex inner) {
|
598 |
+
return S(inner);
|
599 |
+
}
|
600 |
+
};
|
601 |
+
|
602 |
+
// type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
|
603 |
+
// EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
|
604 |
+
// load() is not supported, but we can cast them into the python domain by first copying to a
|
605 |
+
// regular Eigen::Matrix, then casting that.
|
606 |
+
template <typename Type>
|
607 |
+
struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {
|
608 |
+
protected:
|
609 |
+
using Matrix
|
610 |
+
= Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;
|
611 |
+
using props = EigenProps<Matrix>;
|
612 |
+
|
613 |
+
public:
|
614 |
+
static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
|
615 |
+
handle h = eigen_encapsulate<props>(new Matrix(src));
|
616 |
+
return h;
|
617 |
+
}
|
618 |
+
static handle cast(const Type *src, return_value_policy policy, handle parent) {
|
619 |
+
return cast(*src, policy, parent);
|
620 |
+
}
|
621 |
+
|
622 |
+
static constexpr auto name = props::descriptor;
|
623 |
+
|
624 |
+
// Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
|
625 |
+
// types but not bound arguments). We still provide them (with an explicitly delete) so that
|
626 |
+
// you end up here if you try anyway.
|
627 |
+
bool load(handle, bool) = delete;
|
628 |
+
operator Type() = delete;
|
629 |
+
template <typename>
|
630 |
+
using cast_op_type = Type;
|
631 |
+
};
|
632 |
+
|
633 |
+
template <typename Type>
|
634 |
+
struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
|
635 |
+
using Scalar = typename Type::Scalar;
|
636 |
+
using StorageIndex = remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())>;
|
637 |
+
using Index = typename Type::Index;
|
638 |
+
static constexpr bool rowMajor = Type::IsRowMajor;
|
639 |
+
|
640 |
+
bool load(handle src, bool) {
|
641 |
+
if (!src) {
|
642 |
+
return false;
|
643 |
+
}
|
644 |
+
|
645 |
+
auto obj = reinterpret_borrow<object>(src);
|
646 |
+
object sparse_module = module_::import("scipy.sparse");
|
647 |
+
object matrix_type = sparse_module.attr(rowMajor ? "csr_matrix" : "csc_matrix");
|
648 |
+
|
649 |
+
if (!type::handle_of(obj).is(matrix_type)) {
|
650 |
+
try {
|
651 |
+
obj = matrix_type(obj);
|
652 |
+
} catch (const error_already_set &) {
|
653 |
+
return false;
|
654 |
+
}
|
655 |
+
}
|
656 |
+
|
657 |
+
auto values = array_t<Scalar>((object) obj.attr("data"));
|
658 |
+
auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices"));
|
659 |
+
auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr"));
|
660 |
+
auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
|
661 |
+
auto nnz = obj.attr("nnz").cast<Index>();
|
662 |
+
|
663 |
+
if (!values || !innerIndices || !outerIndices) {
|
664 |
+
return false;
|
665 |
+
}
|
666 |
+
|
667 |
+
value = EigenMapSparseMatrix<Scalar,
|
668 |
+
Type::Flags &(Eigen::RowMajor | Eigen::ColMajor),
|
669 |
+
StorageIndex>(shape[0].cast<Index>(),
|
670 |
+
shape[1].cast<Index>(),
|
671 |
+
std::move(nnz),
|
672 |
+
outerIndices.mutable_data(),
|
673 |
+
innerIndices.mutable_data(),
|
674 |
+
values.mutable_data());
|
675 |
+
|
676 |
+
return true;
|
677 |
+
}
|
678 |
+
|
679 |
+
static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
|
680 |
+
const_cast<Type &>(src).makeCompressed();
|
681 |
+
|
682 |
+
object matrix_type
|
683 |
+
= module_::import("scipy.sparse").attr(rowMajor ? "csr_matrix" : "csc_matrix");
|
684 |
+
|
685 |
+
array data(src.nonZeros(), src.valuePtr());
|
686 |
+
array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
|
687 |
+
array innerIndices(src.nonZeros(), src.innerIndexPtr());
|
688 |
+
|
689 |
+
return matrix_type(std::make_tuple(
|
690 |
+
std::move(data), std::move(innerIndices), std::move(outerIndices)),
|
691 |
+
std::make_pair(src.rows(), src.cols()))
|
692 |
+
.release();
|
693 |
+
}
|
694 |
+
|
695 |
+
PYBIND11_TYPE_CASTER(Type,
|
696 |
+
const_name<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[",
|
697 |
+
"scipy.sparse.csc_matrix[")
|
698 |
+
+ npy_format_descriptor<Scalar>::name + const_name("]"));
|
699 |
+
};
|
700 |
+
|
701 |
+
PYBIND11_NAMESPACE_END(detail)
|
702 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|