Techt3o commited on
Commit
e308799
·
verified ·
1 Parent(s): 99f38ca

01d8bd0107e497e4664fcf53385f67d7f99c3d0fe471e9abffe4910b0cb08633

Browse files
Files changed (50) hide show
  1. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/Doxyfile +23 -0
  2. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/Makefile +192 -0
  3. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/custom.rst +91 -0
  4. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/eigen.rst +310 -0
  5. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/functional.rst +109 -0
  6. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/index.rst +43 -0
  7. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/overview.rst +171 -0
  8. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/stl.rst +251 -0
  9. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/strings.rst +305 -0
  10. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/classes.rst +1261 -0
  11. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/embedding.rst +261 -0
  12. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/exceptions.rst +310 -0
  13. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/functions.rst +567 -0
  14. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/misc.rst +337 -0
  15. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/pycpp/index.rst +13 -0
  16. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/pycpp/numpy.rst +438 -0
  17. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/pycpp/object.rst +251 -0
  18. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/pycpp/utilities.rst +155 -0
  19. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/smart_ptrs.rst +173 -0
  20. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/basics.rst +308 -0
  21. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/benchmark.py +92 -0
  22. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/benchmark.rst +95 -0
  23. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/changelog.rst +1881 -0
  24. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/classes.rst +532 -0
  25. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/cmake/index.rst +8 -0
  26. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/compiling.rst +655 -0
  27. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/conf.py +382 -0
  28. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/faq.rst +343 -0
  29. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/index.rst +48 -0
  30. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/installing.rst +105 -0
  31. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/limitations.rst +72 -0
  32. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/pybind11-logo.png +0 -0
  33. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/pybind11_vs_boost_python1.png +0 -0
  34. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/pybind11_vs_boost_python1.svg +427 -0
  35. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/pybind11_vs_boost_python2.png +0 -0
  36. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/pybind11_vs_boost_python2.svg +427 -0
  37. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/reference.rst +127 -0
  38. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/release.rst +94 -0
  39. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/requirements.txt +8 -0
  40. third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/upgrade.rst +537 -0
  41. third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/attr.h +552 -0
  42. third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/buffer_info.h +144 -0
  43. third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/cast.h +1408 -0
  44. third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/chrono.h +213 -0
  45. third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/common.h +2 -0
  46. third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/complex.h +65 -0
  47. third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/detail/class.h +707 -0
  48. third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/detail/common.h +932 -0
  49. third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/detail/descr.h +100 -0
  50. third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/detail/init.h +342 -0
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/Doxyfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = DOXYGEN_SHOULD_SKIP_THIS \
22
+ PY_MAJOR_VERSION=3 \
23
+ PYBIND11_NOINLINE
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/Makefile ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Makefile for Sphinx documentation
2
+ #
3
+
4
+ # You can set these variables from the command line.
5
+ SPHINXOPTS =
6
+ SPHINXBUILD = sphinx-build
7
+ PAPER =
8
+ BUILDDIR = .build
9
+
10
+ # User-friendly check for sphinx-build
11
+ ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
12
+ $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
13
+ endif
14
+
15
+ # Internal variables.
16
+ PAPEROPT_a4 = -D latex_paper_size=a4
17
+ PAPEROPT_letter = -D latex_paper_size=letter
18
+ ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
19
+ # the i18n builder cannot share the environment and doctrees with the others
20
+ I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
21
+
22
+ .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext
23
+
24
+ help:
25
+ @echo "Please use \`make <target>' where <target> is one of"
26
+ @echo " html to make standalone HTML files"
27
+ @echo " dirhtml to make HTML files named index.html in directories"
28
+ @echo " singlehtml to make a single large HTML file"
29
+ @echo " pickle to make pickle files"
30
+ @echo " json to make JSON files"
31
+ @echo " htmlhelp to make HTML files and a HTML help project"
32
+ @echo " qthelp to make HTML files and a qthelp project"
33
+ @echo " applehelp to make an Apple Help Book"
34
+ @echo " devhelp to make HTML files and a Devhelp project"
35
+ @echo " epub to make an epub"
36
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
37
+ @echo " latexpdf to make LaTeX files and run them through pdflatex"
38
+ @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
39
+ @echo " text to make text files"
40
+ @echo " man to make manual pages"
41
+ @echo " texinfo to make Texinfo files"
42
+ @echo " info to make Texinfo files and run them through makeinfo"
43
+ @echo " gettext to make PO message catalogs"
44
+ @echo " changes to make an overview of all changed/added/deprecated items"
45
+ @echo " xml to make Docutils-native XML files"
46
+ @echo " pseudoxml to make pseudoxml-XML files for display purposes"
47
+ @echo " linkcheck to check all external links for integrity"
48
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
49
+ @echo " coverage to run coverage check of the documentation (if enabled)"
50
+
51
+ clean:
52
+ rm -rf $(BUILDDIR)/*
53
+
54
+ html:
55
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
56
+ @echo
57
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
58
+
59
+ dirhtml:
60
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
61
+ @echo
62
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
63
+
64
+ singlehtml:
65
+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
66
+ @echo
67
+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
68
+
69
+ pickle:
70
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
71
+ @echo
72
+ @echo "Build finished; now you can process the pickle files."
73
+
74
+ json:
75
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
76
+ @echo
77
+ @echo "Build finished; now you can process the JSON files."
78
+
79
+ htmlhelp:
80
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
81
+ @echo
82
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
83
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
84
+
85
+ qthelp:
86
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
87
+ @echo
88
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
89
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
90
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pybind11.qhcp"
91
+ @echo "To view the help file:"
92
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pybind11.qhc"
93
+
94
+ applehelp:
95
+ $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
96
+ @echo
97
+ @echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
98
+ @echo "N.B. You won't be able to view it unless you put it in" \
99
+ "~/Library/Documentation/Help or install it in your application" \
100
+ "bundle."
101
+
102
+ devhelp:
103
+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
104
+ @echo
105
+ @echo "Build finished."
106
+ @echo "To view the help file:"
107
+ @echo "# mkdir -p $$HOME/.local/share/devhelp/pybind11"
108
+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pybind11"
109
+ @echo "# devhelp"
110
+
111
+ epub:
112
+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
113
+ @echo
114
+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
115
+
116
+ latex:
117
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
118
+ @echo
119
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
120
+ @echo "Run \`make' in that directory to run these through (pdf)latex" \
121
+ "(use \`make latexpdf' here to do that automatically)."
122
+
123
+ latexpdf:
124
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
125
+ @echo "Running LaTeX files through pdflatex..."
126
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf
127
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
128
+
129
+ latexpdfja:
130
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
131
+ @echo "Running LaTeX files through platex and dvipdfmx..."
132
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
133
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
134
+
135
+ text:
136
+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
137
+ @echo
138
+ @echo "Build finished. The text files are in $(BUILDDIR)/text."
139
+
140
+ man:
141
+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
142
+ @echo
143
+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
144
+
145
+ texinfo:
146
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
147
+ @echo
148
+ @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
149
+ @echo "Run \`make' in that directory to run these through makeinfo" \
150
+ "(use \`make info' here to do that automatically)."
151
+
152
+ info:
153
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
154
+ @echo "Running Texinfo files through makeinfo..."
155
+ make -C $(BUILDDIR)/texinfo info
156
+ @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
157
+
158
+ gettext:
159
+ $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
160
+ @echo
161
+ @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
162
+
163
+ changes:
164
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
165
+ @echo
166
+ @echo "The overview file is in $(BUILDDIR)/changes."
167
+
168
+ linkcheck:
169
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
170
+ @echo
171
+ @echo "Link check complete; look for any errors in the above output " \
172
+ "or in $(BUILDDIR)/linkcheck/output.txt."
173
+
174
+ doctest:
175
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
176
+ @echo "Testing of doctests in the sources finished, look at the " \
177
+ "results in $(BUILDDIR)/doctest/output.txt."
178
+
179
+ coverage:
180
+ $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
181
+ @echo "Testing of coverage in the sources finished, look at the " \
182
+ "results in $(BUILDDIR)/coverage/python.txt."
183
+
184
+ xml:
185
+ $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
186
+ @echo
187
+ @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
188
+
189
+ pseudoxml:
190
+ $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
191
+ @echo
192
+ @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/custom.rst ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Custom type casters
2
+ ===================
3
+
4
+ In very rare cases, applications may require custom type casters that cannot be
5
+ expressed using the abstractions provided by pybind11, thus requiring raw
6
+ Python C API calls. This is fairly advanced usage and should only be pursued by
7
+ experts who are familiar with the intricacies of Python reference counting.
8
+
9
+ The following snippets demonstrate how this works for a very simple ``inty``
10
+ type that that should be convertible from Python types that provide a
11
+ ``__int__(self)`` method.
12
+
13
+ .. code-block:: cpp
14
+
15
+ struct inty { long long_value; };
16
+
17
+ void print(inty s) {
18
+ std::cout << s.long_value << std::endl;
19
+ }
20
+
21
+ The following Python snippet demonstrates the intended usage from the Python side:
22
+
23
+ .. code-block:: python
24
+
25
+ class A:
26
+ def __int__(self):
27
+ return 123
28
+
29
+ from example import print
30
+ print(A())
31
+
32
+ To register the necessary conversion routines, it is necessary to add an
33
+ instantiation of the ``pybind11::detail::type_caster<T>`` template.
34
+ Although this is an implementation detail, adding an instantiation of this
35
+ type is explicitly allowed.
36
+
37
+ .. code-block:: cpp
38
+
39
+ namespace pybind11 { namespace detail {
40
+ template <> struct type_caster<inty> {
41
+ public:
42
+ /**
43
+ * This macro establishes the name 'inty' in
44
+ * function signatures and declares a local variable
45
+ * 'value' of type inty
46
+ */
47
+ PYBIND11_TYPE_CASTER(inty, _("inty"));
48
+
49
+ /**
50
+ * Conversion part 1 (Python->C++): convert a PyObject into a inty
51
+ * instance or return false upon failure. The second argument
52
+ * indicates whether implicit conversions should be applied.
53
+ */
54
+ bool load(handle src, bool) {
55
+ /* Extract PyObject from handle */
56
+ PyObject *source = src.ptr();
57
+ /* Try converting into a Python integer value */
58
+ PyObject *tmp = PyNumber_Long(source);
59
+ if (!tmp)
60
+ return false;
61
+ /* Now try to convert into a C++ int */
62
+ value.long_value = PyLong_AsLong(tmp);
63
+ Py_DECREF(tmp);
64
+ /* Ensure return code was OK (to avoid out-of-range errors etc) */
65
+ return !(value.long_value == -1 && !PyErr_Occurred());
66
+ }
67
+
68
+ /**
69
+ * Conversion part 2 (C++ -> Python): convert an inty instance into
70
+ * a Python object. The second and third arguments are used to
71
+ * indicate the return value policy and parent object (for
72
+ * ``return_value_policy::reference_internal``) and are generally
73
+ * ignored by implicit casters.
74
+ */
75
+ static handle cast(inty src, return_value_policy /* policy */, handle /* parent */) {
76
+ return PyLong_FromLong(src.long_value);
77
+ }
78
+ };
79
+ }} // namespace pybind11::detail
80
+
81
+ .. note::
82
+
83
+ A ``type_caster<T>`` defined with ``PYBIND11_TYPE_CASTER(T, ...)`` requires
84
+ that ``T`` is default-constructible (``value`` is first default constructed
85
+ and then ``load()`` assigns to it).
86
+
87
+ .. warning::
88
+
89
+ When using custom type casters, it's important to declare them consistently
90
+ in every compilation unit of the Python extension module. Otherwise,
91
+ undefined behavior can ensue.
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/eigen.rst ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Eigen
2
+ #####
3
+
4
+ `Eigen <http://eigen.tuxfamily.org>`_ is C++ header-based library for dense and
5
+ sparse linear algebra. Due to its popularity and widespread adoption, pybind11
6
+ provides transparent conversion and limited mapping support between Eigen and
7
+ Scientific Python linear algebra data types.
8
+
9
+ To enable the built-in Eigen support you must include the optional header file
10
+ :file:`pybind11/eigen.h`.
11
+
12
+ Pass-by-value
13
+ =============
14
+
15
+ When binding a function with ordinary Eigen dense object arguments (for
16
+ example, ``Eigen::MatrixXd``), pybind11 will accept any input value that is
17
+ already (or convertible to) a ``numpy.ndarray`` with dimensions compatible with
18
+ the Eigen type, copy its values into a temporary Eigen variable of the
19
+ appropriate type, then call the function with this temporary variable.
20
+
21
+ Sparse matrices are similarly copied to or from
22
+ ``scipy.sparse.csr_matrix``/``scipy.sparse.csc_matrix`` objects.
23
+
24
+ Pass-by-reference
25
+ =================
26
+
27
+ One major limitation of the above is that every data conversion implicitly
28
+ involves a copy, which can be both expensive (for large matrices) and disallows
29
+ binding functions that change their (Matrix) arguments. Pybind11 allows you to
30
+ work around this by using Eigen's ``Eigen::Ref<MatrixType>`` class much as you
31
+ would when writing a function taking a generic type in Eigen itself (subject to
32
+ some limitations discussed below).
33
+
34
+ When calling a bound function accepting a ``Eigen::Ref<const MatrixType>``
35
+ type, pybind11 will attempt to avoid copying by using an ``Eigen::Map`` object
36
+ that maps into the source ``numpy.ndarray`` data: this requires both that the
37
+ data types are the same (e.g. ``dtype='float64'`` and ``MatrixType::Scalar`` is
38
+ ``double``); and that the storage is layout compatible. The latter limitation
39
+ is discussed in detail in the section below, and requires careful
40
+ consideration: by default, numpy matrices and Eigen matrices are *not* storage
41
+ compatible.
42
+
43
+ If the numpy matrix cannot be used as is (either because its types differ, e.g.
44
+ passing an array of integers to an Eigen parameter requiring doubles, or
45
+ because the storage is incompatible), pybind11 makes a temporary copy and
46
+ passes the copy instead.
47
+
48
+ When a bound function parameter is instead ``Eigen::Ref<MatrixType>`` (note the
49
+ lack of ``const``), pybind11 will only allow the function to be called if it
50
+ can be mapped *and* if the numpy array is writeable (that is
51
+ ``a.flags.writeable`` is true). Any access (including modification) made to
52
+ the passed variable will be transparently carried out directly on the
53
+ ``numpy.ndarray``.
54
+
55
+ This means you can can write code such as the following and have it work as
56
+ expected:
57
+
58
+ .. code-block:: cpp
59
+
60
+ void scale_by_2(Eigen::Ref<Eigen::VectorXd> v) {
61
+ v *= 2;
62
+ }
63
+
64
+ Note, however, that you will likely run into limitations due to numpy and
65
+ Eigen's difference default storage order for data; see the below section on
66
+ :ref:`storage_orders` for details on how to bind code that won't run into such
67
+ limitations.
68
+
69
+ .. note::
70
+
71
+ Passing by reference is not supported for sparse types.
72
+
73
+ Returning values to Python
74
+ ==========================
75
+
76
+ When returning an ordinary dense Eigen matrix type to numpy (e.g.
77
+ ``Eigen::MatrixXd`` or ``Eigen::RowVectorXf``) pybind11 keeps the matrix and
78
+ returns a numpy array that directly references the Eigen matrix: no copy of the
79
+ data is performed. The numpy array will have ``array.flags.owndata`` set to
80
+ ``False`` to indicate that it does not own the data, and the lifetime of the
81
+ stored Eigen matrix will be tied to the returned ``array``.
82
+
83
+ If you bind a function with a non-reference, ``const`` return type (e.g.
84
+ ``const Eigen::MatrixXd``), the same thing happens except that pybind11 also
85
+ sets the numpy array's ``writeable`` flag to false.
86
+
87
+ If you return an lvalue reference or pointer, the usual pybind11 rules apply,
88
+ as dictated by the binding function's return value policy (see the
89
+ documentation on :ref:`return_value_policies` for full details). That means,
90
+ without an explicit return value policy, lvalue references will be copied and
91
+ pointers will be managed by pybind11. In order to avoid copying, you should
92
+ explicitly specify an appropriate return value policy, as in the following
93
+ example:
94
+
95
+ .. code-block:: cpp
96
+
97
+ class MyClass {
98
+ Eigen::MatrixXd big_mat = Eigen::MatrixXd::Zero(10000, 10000);
99
+ public:
100
+ Eigen::MatrixXd &getMatrix() { return big_mat; }
101
+ const Eigen::MatrixXd &viewMatrix() { return big_mat; }
102
+ };
103
+
104
+ // Later, in binding code:
105
+ py::class_<MyClass>(m, "MyClass")
106
+ .def(py::init<>())
107
+ .def("copy_matrix", &MyClass::getMatrix) // Makes a copy!
108
+ .def("get_matrix", &MyClass::getMatrix, py::return_value_policy::reference_internal)
109
+ .def("view_matrix", &MyClass::viewMatrix, py::return_value_policy::reference_internal)
110
+ ;
111
+
112
+ .. code-block:: python
113
+
114
+ a = MyClass()
115
+ m = a.get_matrix() # flags.writeable = True, flags.owndata = False
116
+ v = a.view_matrix() # flags.writeable = False, flags.owndata = False
117
+ c = a.copy_matrix() # flags.writeable = True, flags.owndata = True
118
+ # m[5,6] and v[5,6] refer to the same element, c[5,6] does not.
119
+
120
+ Note in this example that ``py::return_value_policy::reference_internal`` is
121
+ used to tie the life of the MyClass object to the life of the returned arrays.
122
+
123
+ You may also return an ``Eigen::Ref``, ``Eigen::Map`` or other map-like Eigen
124
+ object (for example, the return value of ``matrix.block()`` and related
125
+ methods) that map into a dense Eigen type. When doing so, the default
126
+ behaviour of pybind11 is to simply reference the returned data: you must take
127
+ care to ensure that this data remains valid! You may ask pybind11 to
128
+ explicitly *copy* such a return value by using the
129
+ ``py::return_value_policy::copy`` policy when binding the function. You may
130
+ also use ``py::return_value_policy::reference_internal`` or a
131
+ ``py::keep_alive`` to ensure the data stays valid as long as the returned numpy
132
+ array does.
133
+
134
+ When returning such a reference of map, pybind11 additionally respects the
135
+ readonly-status of the returned value, marking the numpy array as non-writeable
136
+ if the reference or map was itself read-only.
137
+
138
+ .. note::
139
+
140
+ Sparse types are always copied when returned.
141
+
142
+ .. _storage_orders:
143
+
144
+ Storage orders
145
+ ==============
146
+
147
+ Passing arguments via ``Eigen::Ref`` has some limitations that you must be
148
+ aware of in order to effectively pass matrices by reference. First and
149
+ foremost is that the default ``Eigen::Ref<MatrixType>`` class requires
150
+ contiguous storage along columns (for column-major types, the default in Eigen)
151
+ or rows if ``MatrixType`` is specifically an ``Eigen::RowMajor`` storage type.
152
+ The former, Eigen's default, is incompatible with ``numpy``'s default row-major
153
+ storage, and so you will not be able to pass numpy arrays to Eigen by reference
154
+ without making one of two changes.
155
+
156
+ (Note that this does not apply to vectors (or column or row matrices): for such
157
+ types the "row-major" and "column-major" distinction is meaningless).
158
+
159
+ The first approach is to change the use of ``Eigen::Ref<MatrixType>`` to the
160
+ more general ``Eigen::Ref<MatrixType, 0, Eigen::Stride<Eigen::Dynamic,
161
+ Eigen::Dynamic>>`` (or similar type with a fully dynamic stride type in the
162
+ third template argument). Since this is a rather cumbersome type, pybind11
163
+ provides a ``py::EigenDRef<MatrixType>`` type alias for your convenience (along
164
+ with EigenDMap for the equivalent Map, and EigenDStride for just the stride
165
+ type).
166
+
167
+ This type allows Eigen to map into any arbitrary storage order. This is not
168
+ the default in Eigen for performance reasons: contiguous storage allows
169
+ vectorization that cannot be done when storage is not known to be contiguous at
170
+ compile time. The default ``Eigen::Ref`` stride type allows non-contiguous
171
+ storage along the outer dimension (that is, the rows of a column-major matrix
172
+ or columns of a row-major matrix), but not along the inner dimension.
173
+
174
+ This type, however, has the added benefit of also being able to map numpy array
175
+ slices. For example, the following (contrived) example uses Eigen with a numpy
176
+ slice to multiply by 2 all coefficients that are both on even rows (0, 2, 4,
177
+ ...) and in columns 2, 5, or 8:
178
+
179
+ .. code-block:: cpp
180
+
181
+ m.def("scale", [](py::EigenDRef<Eigen::MatrixXd> m, double c) { m *= c; });
182
+
183
+ .. code-block:: python
184
+
185
+ # a = np.array(...)
186
+ scale_by_2(myarray[0::2, 2:9:3])
187
+
188
+ The second approach to avoid copying is more intrusive: rearranging the
189
+ underlying data types to not run into the non-contiguous storage problem in the
190
+ first place. In particular, that means using matrices with ``Eigen::RowMajor``
191
+ storage, where appropriate, such as:
192
+
193
+ .. code-block:: cpp
194
+
195
+ using RowMatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
196
+ // Use RowMatrixXd instead of MatrixXd
197
+
198
+ Now bound functions accepting ``Eigen::Ref<RowMatrixXd>`` arguments will be
199
+ callable with numpy's (default) arrays without involving a copying.
200
+
201
+ You can, alternatively, change the storage order that numpy arrays use by
202
+ adding the ``order='F'`` option when creating an array:
203
+
204
+ .. code-block:: python
205
+
206
+ myarray = np.array(source, order='F')
207
+
208
+ Such an object will be passable to a bound function accepting an
209
+ ``Eigen::Ref<MatrixXd>`` (or similar column-major Eigen type).
210
+
211
+ One major caveat with this approach, however, is that it is not entirely as
212
+ easy as simply flipping all Eigen or numpy usage from one to the other: some
213
+ operations may alter the storage order of a numpy array. For example, ``a2 =
214
+ array.transpose()`` results in ``a2`` being a view of ``array`` that references
215
+ the same data, but in the opposite storage order!
216
+
217
+ While this approach allows fully optimized vectorized calculations in Eigen, it
218
+ cannot be used with array slices, unlike the first approach.
219
+
220
+ When *returning* a matrix to Python (either a regular matrix, a reference via
221
+ ``Eigen::Ref<>``, or a map/block into a matrix), no special storage
222
+ consideration is required: the created numpy array will have the required
223
+ stride that allows numpy to properly interpret the array, whatever its storage
224
+ order.
225
+
226
+ Failing rather than copying
227
+ ===========================
228
+
229
+ The default behaviour when binding ``Eigen::Ref<const MatrixType>`` Eigen
230
+ references is to copy matrix values when passed a numpy array that does not
231
+ conform to the element type of ``MatrixType`` or does not have a compatible
232
+ stride layout. If you want to explicitly avoid copying in such a case, you
233
+ should bind arguments using the ``py::arg().noconvert()`` annotation (as
234
+ described in the :ref:`nonconverting_arguments` documentation).
235
+
236
+ The following example shows an example of arguments that don't allow data
237
+ copying to take place:
238
+
239
+ .. code-block:: cpp
240
+
241
+ // The method and function to be bound:
242
+ class MyClass {
243
+ // ...
244
+ double some_method(const Eigen::Ref<const MatrixXd> &matrix) { /* ... */ }
245
+ };
246
+ float some_function(const Eigen::Ref<const MatrixXf> &big,
247
+ const Eigen::Ref<const MatrixXf> &small) {
248
+ // ...
249
+ }
250
+
251
+ // The associated binding code:
252
+ using namespace pybind11::literals; // for "arg"_a
253
+ py::class_<MyClass>(m, "MyClass")
254
+ // ... other class definitions
255
+ .def("some_method", &MyClass::some_method, py::arg().noconvert());
256
+
257
+ m.def("some_function", &some_function,
258
+ "big"_a.noconvert(), // <- Don't allow copying for this arg
259
+ "small"_a // <- This one can be copied if needed
260
+ );
261
+
262
+ With the above binding code, attempting to call the the ``some_method(m)``
263
+ method on a ``MyClass`` object, or attempting to call ``some_function(m, m2)``
264
+ will raise a ``RuntimeError`` rather than making a temporary copy of the array.
265
+ It will, however, allow the ``m2`` argument to be copied into a temporary if
266
+ necessary.
267
+
268
+ Note that explicitly specifying ``.noconvert()`` is not required for *mutable*
269
+ Eigen references (e.g. ``Eigen::Ref<MatrixXd>`` without ``const`` on the
270
+ ``MatrixXd``): mutable references will never be called with a temporary copy.
271
+
272
+ Vectors versus column/row matrices
273
+ ==================================
274
+
275
+ Eigen and numpy have fundamentally different notions of a vector. In Eigen, a
276
+ vector is simply a matrix with the number of columns or rows set to 1 at
277
+ compile time (for a column vector or row vector, respectively). NumPy, in
278
+ contrast, has comparable 2-dimensional 1xN and Nx1 arrays, but *also* has
279
+ 1-dimensional arrays of size N.
280
+
281
+ When passing a 2-dimensional 1xN or Nx1 array to Eigen, the Eigen type must
282
+ have matching dimensions: That is, you cannot pass a 2-dimensional Nx1 numpy
283
+ array to an Eigen value expecting a row vector, or a 1xN numpy array as a
284
+ column vector argument.
285
+
286
+ On the other hand, pybind11 allows you to pass 1-dimensional arrays of length N
287
+ as Eigen parameters. If the Eigen type can hold a column vector of length N it
288
+ will be passed as such a column vector. If not, but the Eigen type constraints
289
+ will accept a row vector, it will be passed as a row vector. (The column
290
+ vector takes precedence when both are supported, for example, when passing a
291
+ 1D numpy array to a MatrixXd argument). Note that the type need not be
292
+ explicitly a vector: it is permitted to pass a 1D numpy array of size 5 to an
293
+ Eigen ``Matrix<double, Dynamic, 5>``: you would end up with a 1x5 Eigen matrix.
294
+ Passing the same to an ``Eigen::MatrixXd`` would result in a 5x1 Eigen matrix.
295
+
296
+ When returning an Eigen vector to numpy, the conversion is ambiguous: a row
297
+ vector of length 4 could be returned as either a 1D array of length 4, or as a
298
+ 2D array of size 1x4. When encountering such a situation, pybind11 compromises
299
+ by considering the returned Eigen type: if it is a compile-time vector--that
300
+ is, the type has either the number of rows or columns set to 1 at compile
301
+ time--pybind11 converts to a 1D numpy array when returning the value. For
302
+ instances that are a vector only at run-time (e.g. ``MatrixXd``,
303
+ ``Matrix<float, Dynamic, 4>``), pybind11 returns the vector as a 2D array to
304
+ numpy. If this isn't want you want, you can use ``array.reshape(...)`` to get
305
+ a view of the same data in the desired dimensions.
306
+
307
+ .. seealso::
308
+
309
+ The file :file:`tests/test_eigen.cpp` contains a complete example that
310
+ shows how to pass Eigen sparse and dense data types in more detail.
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/functional.rst ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Functional
2
+ ##########
3
+
4
+ The following features must be enabled by including :file:`pybind11/functional.h`.
5
+
6
+
7
+ Callbacks and passing anonymous functions
8
+ =========================================
9
+
10
+ The C++11 standard brought lambda functions and the generic polymorphic
11
+ function wrapper ``std::function<>`` to the C++ programming language, which
12
+ enable powerful new ways of working with functions. Lambda functions come in
13
+ two flavors: stateless lambda function resemble classic function pointers that
14
+ link to an anonymous piece of code, while stateful lambda functions
15
+ additionally depend on captured variables that are stored in an anonymous
16
+ *lambda closure object*.
17
+
18
+ Here is a simple example of a C++ function that takes an arbitrary function
19
+ (stateful or stateless) with signature ``int -> int`` as an argument and runs
20
+ it with the value 10.
21
+
22
+ .. code-block:: cpp
23
+
24
+ int func_arg(const std::function<int(int)> &f) {
25
+ return f(10);
26
+ }
27
+
28
+ The example below is more involved: it takes a function of signature ``int -> int``
29
+ and returns another function of the same kind. The return value is a stateful
30
+ lambda function, which stores the value ``f`` in the capture object and adds 1 to
31
+ its return value upon execution.
32
+
33
+ .. code-block:: cpp
34
+
35
+ std::function<int(int)> func_ret(const std::function<int(int)> &f) {
36
+ return [f](int i) {
37
+ return f(i) + 1;
38
+ };
39
+ }
40
+
41
+ This example demonstrates using python named parameters in C++ callbacks which
42
+ requires using ``py::cpp_function`` as a wrapper. Usage is similar to defining
43
+ methods of classes:
44
+
45
+ .. code-block:: cpp
46
+
47
+ py::cpp_function func_cpp() {
48
+ return py::cpp_function([](int i) { return i+1; },
49
+ py::arg("number"));
50
+ }
51
+
52
+ After including the extra header file :file:`pybind11/functional.h`, it is almost
53
+ trivial to generate binding code for all of these functions.
54
+
55
+ .. code-block:: cpp
56
+
57
+ #include <pybind11/functional.h>
58
+
59
+ PYBIND11_MODULE(example, m) {
60
+ m.def("func_arg", &func_arg);
61
+ m.def("func_ret", &func_ret);
62
+ m.def("func_cpp", &func_cpp);
63
+ }
64
+
65
+ The following interactive session shows how to call them from Python.
66
+
67
+ .. code-block:: pycon
68
+
69
+ $ python
70
+ >>> import example
71
+ >>> def square(i):
72
+ ... return i * i
73
+ ...
74
+ >>> example.func_arg(square)
75
+ 100L
76
+ >>> square_plus_1 = example.func_ret(square)
77
+ >>> square_plus_1(4)
78
+ 17L
79
+ >>> plus_1 = func_cpp()
80
+ >>> plus_1(number=43)
81
+ 44L
82
+
83
+ .. warning::
84
+
85
+ Keep in mind that passing a function from C++ to Python (or vice versa)
86
+ will instantiate a piece of wrapper code that translates function
87
+ invocations between the two languages. Naturally, this translation
88
+ increases the computational cost of each function call somewhat. A
89
+ problematic situation can arise when a function is copied back and forth
90
+ between Python and C++ many times in a row, in which case the underlying
91
+ wrappers will accumulate correspondingly. The resulting long sequence of
92
+ C++ -> Python -> C++ -> ... roundtrips can significantly decrease
93
+ performance.
94
+
95
+ There is one exception: pybind11 detects case where a stateless function
96
+ (i.e. a function pointer or a lambda function without captured variables)
97
+ is passed as an argument to another C++ function exposed in Python. In this
98
+ case, there is no overhead. Pybind11 will extract the underlying C++
99
+ function pointer from the wrapped function to sidestep a potential C++ ->
100
+ Python -> C++ roundtrip. This is demonstrated in :file:`tests/test_callbacks.cpp`.
101
+
102
+ .. note::
103
+
104
+ This functionality is very useful when generating bindings for callbacks in
105
+ C++ libraries (e.g. GUI libraries, asynchronous networking libraries, etc.).
106
+
107
+ The file :file:`tests/test_callbacks.cpp` contains a complete example
108
+ that demonstrates how to work with callbacks and anonymous functions in
109
+ more detail.
third-party/DPVO/Pangolin/components/pango_python/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/Pangolin/components/pango_python/pybind11/docs/advanced/cast/overview.rst ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.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``, but this requires
171
+ Python 3.6 (for ``__fspath__`` support).
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/stl.rst ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Additionally, on Windows, MSVC 2017 is required because ``boost::variant``
91
+ falls back to the old non-variadic implementation on MSVC 2015.
92
+
93
+ .. _opaque:
94
+
95
+ Making opaque types
96
+ ===================
97
+
98
+ pybind11 heavily relies on a template matching mechanism to convert parameters
99
+ and return values that are constructed from STL data types such as vectors,
100
+ linked lists, hash tables, etc. This even works in a recursive manner, for
101
+ instance to deal with lists of hash maps of pairs of elementary and custom
102
+ types, etc.
103
+
104
+ However, a fundamental limitation of this approach is that internal conversions
105
+ between Python and C++ types involve a copy operation that prevents
106
+ pass-by-reference semantics. What does this mean?
107
+
108
+ Suppose we bind the following function
109
+
110
+ .. code-block:: cpp
111
+
112
+ void append_1(std::vector<int> &v) {
113
+ v.push_back(1);
114
+ }
115
+
116
+ and call it from Python, the following happens:
117
+
118
+ .. code-block:: pycon
119
+
120
+ >>> v = [5, 6]
121
+ >>> append_1(v)
122
+ >>> print(v)
123
+ [5, 6]
124
+
125
+ As you can see, when passing STL data structures by reference, modifications
126
+ are not propagated back the Python side. A similar situation arises when
127
+ exposing STL data structures using the ``def_readwrite`` or ``def_readonly``
128
+ functions:
129
+
130
+ .. code-block:: cpp
131
+
132
+ /* ... definition ... */
133
+
134
+ class MyClass {
135
+ std::vector<int> contents;
136
+ };
137
+
138
+ /* ... binding code ... */
139
+
140
+ py::class_<MyClass>(m, "MyClass")
141
+ .def(py::init<>())
142
+ .def_readwrite("contents", &MyClass::contents);
143
+
144
+ In this case, properties can be read and written in their entirety. However, an
145
+ ``append`` operation involving such a list type has no effect:
146
+
147
+ .. code-block:: pycon
148
+
149
+ >>> m = MyClass()
150
+ >>> m.contents = [5, 6]
151
+ >>> print(m.contents)
152
+ [5, 6]
153
+ >>> m.contents.append(7)
154
+ >>> print(m.contents)
155
+ [5, 6]
156
+
157
+ Finally, the involved copy operations can be costly when dealing with very
158
+ large lists. To deal with all of the above situations, pybind11 provides a
159
+ macro named ``PYBIND11_MAKE_OPAQUE(T)`` that disables the template-based
160
+ conversion machinery of types, thus rendering them *opaque*. The contents of
161
+ opaque objects are never inspected or extracted, hence they *can* be passed by
162
+ reference. For instance, to turn ``std::vector<int>`` into an opaque type, add
163
+ the declaration
164
+
165
+ .. code-block:: cpp
166
+
167
+ PYBIND11_MAKE_OPAQUE(std::vector<int>);
168
+
169
+ before any binding code (e.g. invocations to ``class_::def()``, etc.). This
170
+ macro must be specified at the top level (and outside of any namespaces), since
171
+ it adds a template instantiation of ``type_caster``. If your binding code consists of
172
+ multiple compilation units, it must be present in every file (typically via a
173
+ common header) preceding any usage of ``std::vector<int>``. Opaque types must
174
+ also have a corresponding ``class_`` declaration to associate them with a name
175
+ in Python, and to define a set of available operations, e.g.:
176
+
177
+ .. code-block:: cpp
178
+
179
+ py::class_<std::vector<int>>(m, "IntVector")
180
+ .def(py::init<>())
181
+ .def("clear", &std::vector<int>::clear)
182
+ .def("pop_back", &std::vector<int>::pop_back)
183
+ .def("__len__", [](const std::vector<int> &v) { return v.size(); })
184
+ .def("__iter__", [](std::vector<int> &v) {
185
+ return py::make_iterator(v.begin(), v.end());
186
+ }, py::keep_alive<0, 1>()) /* Keep vector alive while iterator is used */
187
+ // ....
188
+
189
+ .. seealso::
190
+
191
+ The file :file:`tests/test_opaque_types.cpp` contains a complete
192
+ example that demonstrates how to create and expose opaque types using
193
+ pybind11 in more detail.
194
+
195
+ .. _stl_bind:
196
+
197
+ Binding STL containers
198
+ ======================
199
+
200
+ The ability to expose STL containers as native Python objects is a fairly
201
+ common request, hence pybind11 also provides an optional header file named
202
+ :file:`pybind11/stl_bind.h` that does exactly this. The mapped containers try
203
+ to match the behavior of their native Python counterparts as much as possible.
204
+
205
+ The following example showcases usage of :file:`pybind11/stl_bind.h`:
206
+
207
+ .. code-block:: cpp
208
+
209
+ // Don't forget this
210
+ #include <pybind11/stl_bind.h>
211
+
212
+ PYBIND11_MAKE_OPAQUE(std::vector<int>);
213
+ PYBIND11_MAKE_OPAQUE(std::map<std::string, double>);
214
+
215
+ // ...
216
+
217
+ // later in binding code:
218
+ py::bind_vector<std::vector<int>>(m, "VectorInt");
219
+ py::bind_map<std::map<std::string, double>>(m, "MapStringDouble");
220
+
221
+ When binding STL containers pybind11 considers the types of the container's
222
+ elements to decide whether the container should be confined to the local module
223
+ (via the :ref:`module_local` feature). If the container element types are
224
+ anything other than already-bound custom types bound without
225
+ ``py::module_local()`` the container binding will have ``py::module_local()``
226
+ applied. This includes converting types such as numeric types, strings, Eigen
227
+ types; and types that have not yet been bound at the time of the stl container
228
+ binding. This module-local binding is designed to avoid potential conflicts
229
+ between module bindings (for example, from two separate modules each attempting
230
+ to bind ``std::vector<int>`` as a python type).
231
+
232
+ It is possible to override this behavior to force a definition to be either
233
+ module-local or global. To do so, you can pass the attributes
234
+ ``py::module_local()`` (to make the binding module-local) or
235
+ ``py::module_local(false)`` (to make the binding global) into the
236
+ ``py::bind_vector`` or ``py::bind_map`` arguments:
237
+
238
+ .. code-block:: cpp
239
+
240
+ py::bind_vector<std::vector<int>>(m, "VectorInt", py::module_local(false));
241
+
242
+ Note, however, that such a global binding would make it impossible to load this
243
+ module at the same time as any other pybind module that also attempts to bind
244
+ the same container type (``std::vector<int>`` in the above example).
245
+
246
+ See :ref:`module_local` for more details on module-local bindings.
247
+
248
+ .. seealso::
249
+
250
+ The file :file:`tests/test_stl_binders.cpp` shows how to use the
251
+ convenience STL container wrappers.
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/cast/strings.rst ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Strings, bytes and Unicode conversions
2
+ ######################################
3
+
4
+ .. note::
5
+
6
+ This section discusses string handling in terms of Python 3 strings. For
7
+ Python 2.7, replace all occurrences of ``str`` with ``unicode`` and
8
+ ``bytes`` with ``str``. Python 2.7 users may find it best to use ``from
9
+ __future__ import unicode_literals`` to avoid unintentionally using ``str``
10
+ instead of ``unicode``.
11
+
12
+ Passing Python strings to C++
13
+ =============================
14
+
15
+ When a Python ``str`` is passed from Python to a C++ function that accepts
16
+ ``std::string`` or ``char *`` as arguments, pybind11 will encode the Python
17
+ string to UTF-8. All Python ``str`` can be encoded in UTF-8, so this operation
18
+ does not fail.
19
+
20
+ The C++ language is encoding agnostic. It is the responsibility of the
21
+ programmer to track encodings. It's often easiest to simply `use UTF-8
22
+ everywhere <http://utf8everywhere.org/>`_.
23
+
24
+ .. code-block:: c++
25
+
26
+ m.def("utf8_test",
27
+ [](const std::string &s) {
28
+ cout << "utf-8 is icing on the cake.\n";
29
+ cout << s;
30
+ }
31
+ );
32
+ m.def("utf8_charptr",
33
+ [](const char *s) {
34
+ cout << "My favorite food is\n";
35
+ cout << s;
36
+ }
37
+ );
38
+
39
+ .. code-block:: python
40
+
41
+ >>> utf8_test('🎂')
42
+ utf-8 is icing on the cake.
43
+ 🎂
44
+
45
+ >>> utf8_charptr('🍕')
46
+ My favorite food is
47
+ 🍕
48
+
49
+ .. note::
50
+
51
+ Some terminal emulators do not support UTF-8 or emoji fonts and may not
52
+ display the example above correctly.
53
+
54
+ The results are the same whether the C++ function accepts arguments by value or
55
+ reference, and whether or not ``const`` is used.
56
+
57
+ Passing bytes to C++
58
+ --------------------
59
+
60
+ A Python ``bytes`` object will be passed to C++ functions that accept
61
+ ``std::string`` or ``char*`` *without* conversion. On Python 3, in order to
62
+ make a function *only* accept ``bytes`` (and not ``str``), declare it as taking
63
+ a ``py::bytes`` argument.
64
+
65
+
66
+ Returning C++ strings to Python
67
+ ===============================
68
+
69
+ When a C++ function returns a ``std::string`` or ``char*`` to a Python caller,
70
+ **pybind11 will assume that the string is valid UTF-8** and will decode it to a
71
+ native Python ``str``, using the same API as Python uses to perform
72
+ ``bytes.decode('utf-8')``. If this implicit conversion fails, pybind11 will
73
+ raise a ``UnicodeDecodeError``.
74
+
75
+ .. code-block:: c++
76
+
77
+ m.def("std_string_return",
78
+ []() {
79
+ return std::string("This string needs to be UTF-8 encoded");
80
+ }
81
+ );
82
+
83
+ .. code-block:: python
84
+
85
+ >>> isinstance(example.std_string_return(), str)
86
+ True
87
+
88
+
89
+ Because UTF-8 is inclusive of pure ASCII, there is never any issue with
90
+ returning a pure ASCII string to Python. If there is any possibility that the
91
+ string is not pure ASCII, it is necessary to ensure the encoding is valid
92
+ UTF-8.
93
+
94
+ .. warning::
95
+
96
+ Implicit conversion assumes that a returned ``char *`` is null-terminated.
97
+ If there is no null terminator a buffer overrun will occur.
98
+
99
+ Explicit conversions
100
+ --------------------
101
+
102
+ If some C++ code constructs a ``std::string`` that is not a UTF-8 string, one
103
+ can perform a explicit conversion and return a ``py::str`` object. Explicit
104
+ conversion has the same overhead as implicit conversion.
105
+
106
+ .. code-block:: c++
107
+
108
+ // This uses the Python C API to convert Latin-1 to Unicode
109
+ m.def("str_output",
110
+ []() {
111
+ std::string s = "Send your r\xe9sum\xe9 to Alice in HR"; // Latin-1
112
+ py::str py_s = PyUnicode_DecodeLatin1(s.data(), s.length());
113
+ return py_s;
114
+ }
115
+ );
116
+
117
+ .. code-block:: python
118
+
119
+ >>> str_output()
120
+ 'Send your résumé to Alice in HR'
121
+
122
+ The `Python C API
123
+ <https://docs.python.org/3/c-api/unicode.html#built-in-codecs>`_ provides
124
+ several built-in codecs.
125
+
126
+
127
+ One could also use a third party encoding library such as libiconv to transcode
128
+ to UTF-8.
129
+
130
+ Return C++ strings without conversion
131
+ -------------------------------------
132
+
133
+ If the data in a C++ ``std::string`` does not represent text and should be
134
+ returned to Python as ``bytes``, then one can return the data as a
135
+ ``py::bytes`` object.
136
+
137
+ .. code-block:: c++
138
+
139
+ m.def("return_bytes",
140
+ []() {
141
+ std::string s("\xba\xd0\xba\xd0"); // Not valid UTF-8
142
+ return py::bytes(s); // Return the data without transcoding
143
+ }
144
+ );
145
+
146
+ .. code-block:: python
147
+
148
+ >>> example.return_bytes()
149
+ b'\xba\xd0\xba\xd0'
150
+
151
+
152
+ Note the asymmetry: pybind11 will convert ``bytes`` to ``std::string`` without
153
+ encoding, but cannot convert ``std::string`` back to ``bytes`` implicitly.
154
+
155
+ .. code-block:: c++
156
+
157
+ m.def("asymmetry",
158
+ [](std::string s) { // Accepts str or bytes from Python
159
+ return s; // Looks harmless, but implicitly converts to str
160
+ }
161
+ );
162
+
163
+ .. code-block:: python
164
+
165
+ >>> isinstance(example.asymmetry(b"have some bytes"), str)
166
+ True
167
+
168
+ >>> example.asymmetry(b"\xba\xd0\xba\xd0") # invalid utf-8 as bytes
169
+ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 0: invalid start byte
170
+
171
+
172
+ Wide character strings
173
+ ======================
174
+
175
+ When a Python ``str`` is passed to a C++ function expecting ``std::wstring``,
176
+ ``wchar_t*``, ``std::u16string`` or ``std::u32string``, the ``str`` will be
177
+ encoded to UTF-16 or UTF-32 depending on how the C++ compiler implements each
178
+ type, in the platform's native endianness. When strings of these types are
179
+ returned, they are assumed to contain valid UTF-16 or UTF-32, and will be
180
+ decoded to Python ``str``.
181
+
182
+ .. code-block:: c++
183
+
184
+ #define UNICODE
185
+ #include <windows.h>
186
+
187
+ m.def("set_window_text",
188
+ [](HWND hwnd, std::wstring s) {
189
+ // Call SetWindowText with null-terminated UTF-16 string
190
+ ::SetWindowText(hwnd, s.c_str());
191
+ }
192
+ );
193
+ m.def("get_window_text",
194
+ [](HWND hwnd) {
195
+ const int buffer_size = ::GetWindowTextLength(hwnd) + 1;
196
+ auto buffer = std::make_unique< wchar_t[] >(buffer_size);
197
+
198
+ ::GetWindowText(hwnd, buffer.data(), buffer_size);
199
+
200
+ std::wstring text(buffer.get());
201
+
202
+ // wstring will be converted to Python str
203
+ return text;
204
+ }
205
+ );
206
+
207
+ .. warning::
208
+
209
+ Wide character strings may not work as described on Python 2.7 or Python
210
+ 3.3 compiled with ``--enable-unicode=ucs2``.
211
+
212
+ Strings in multibyte encodings such as Shift-JIS must transcoded to a
213
+ UTF-8/16/32 before being returned to Python.
214
+
215
+
216
+ Character literals
217
+ ==================
218
+
219
+ C++ functions that accept character literals as input will receive the first
220
+ character of a Python ``str`` as their input. If the string is longer than one
221
+ Unicode character, trailing characters will be ignored.
222
+
223
+ When a character literal is returned from C++ (such as a ``char`` or a
224
+ ``wchar_t``), it will be converted to a ``str`` that represents the single
225
+ character.
226
+
227
+ .. code-block:: c++
228
+
229
+ m.def("pass_char", [](char c) { return c; });
230
+ m.def("pass_wchar", [](wchar_t w) { return w; });
231
+
232
+ .. code-block:: python
233
+
234
+ >>> example.pass_char('A')
235
+ 'A'
236
+
237
+ While C++ will cast integers to character types (``char c = 0x65;``), pybind11
238
+ does not convert Python integers to characters implicitly. The Python function
239
+ ``chr()`` can be used to convert integers to characters.
240
+
241
+ .. code-block:: python
242
+
243
+ >>> example.pass_char(0x65)
244
+ TypeError
245
+
246
+ >>> example.pass_char(chr(0x65))
247
+ 'A'
248
+
249
+ If the desire is to work with an 8-bit integer, use ``int8_t`` or ``uint8_t``
250
+ as the argument type.
251
+
252
+ Grapheme clusters
253
+ -----------------
254
+
255
+ A single grapheme may be represented by two or more Unicode characters. For
256
+ example 'é' is usually represented as U+00E9 but can also be expressed as the
257
+ combining character sequence U+0065 U+0301 (that is, the letter 'e' followed by
258
+ a combining acute accent). The combining character will be lost if the
259
+ two-character sequence is passed as an argument, even though it renders as a
260
+ single grapheme.
261
+
262
+ .. code-block:: python
263
+
264
+ >>> example.pass_wchar('é')
265
+ 'é'
266
+
267
+ >>> combining_e_acute = 'e' + '\u0301'
268
+
269
+ >>> combining_e_acute
270
+ 'é'
271
+
272
+ >>> combining_e_acute == 'é'
273
+ False
274
+
275
+ >>> example.pass_wchar(combining_e_acute)
276
+ 'e'
277
+
278
+ Normalizing combining characters before passing the character literal to C++
279
+ may resolve *some* of these issues:
280
+
281
+ .. code-block:: python
282
+
283
+ >>> example.pass_wchar(unicodedata.normalize('NFC', combining_e_acute))
284
+ 'é'
285
+
286
+ In some languages (Thai for example), there are `graphemes that cannot be
287
+ expressed as a single Unicode code point
288
+ <http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries>`_, so there is
289
+ no way to capture them in a C++ character type.
290
+
291
+
292
+ C++17 string views
293
+ ==================
294
+
295
+ C++17 string views are automatically supported when compiling in C++17 mode.
296
+ They follow the same rules for encoding and decoding as the corresponding STL
297
+ string type (for example, a ``std::u16string_view`` argument will be passed
298
+ UTF-16-encoded data, and a returned ``std::string_view`` will be decoded as
299
+ UTF-8).
300
+
301
+ References
302
+ ==========
303
+
304
+ * `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/>`_
305
+ * `C++ - Using STL Strings at Win32 API Boundaries <https://msdn.microsoft.com/en-ca/magazine/mt238407.aspx>`_
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/classes.rst ADDED
@@ -0,0 +1,1261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 to
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
+ u'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
+ u'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
+ def bark(self):
165
+ return "yap!"
166
+
167
+ Note that a direct ``__init__`` constructor *should be called*, and ``super()``
168
+ should not be used. For simple cases of linear inheritance, ``super()``
169
+ may work, but once you begin mixing Python and C++ multiple inheritance,
170
+ things will fall apart due to differences between Python's MRO and C++'s
171
+ mechanisms.
172
+
173
+ Please take a look at the :ref:`macro_notes` before using this feature.
174
+
175
+ .. note::
176
+
177
+ When the overridden type returns a reference or pointer to a type that
178
+ pybind11 converts from Python (for example, numeric values, std::string,
179
+ and other built-in value-converting types), there are some limitations to
180
+ be aware of:
181
+
182
+ - because in these cases there is no C++ variable to reference (the value
183
+ is stored in the referenced Python variable), pybind11 provides one in
184
+ the PYBIND11_OVERRIDE macros (when needed) with static storage duration.
185
+ Note that this means that invoking the overridden method on *any*
186
+ instance will change the referenced value stored in *all* instances of
187
+ that type.
188
+
189
+ - Attempts to modify a non-const reference will not have the desired
190
+ effect: it will change only the static cache variable, but this change
191
+ will not propagate to underlying Python instance, and the change will be
192
+ replaced the next time the override is invoked.
193
+
194
+ .. warning::
195
+
196
+ The :c:macro:`PYBIND11_OVERRIDE` and accompanying macros used to be called
197
+ ``PYBIND11_OVERLOAD`` up until pybind11 v2.5.0, and :func:`get_override`
198
+ used to be called ``get_overload``. This naming was corrected and the older
199
+ macro and function names may soon be deprecated, in order to reduce
200
+ confusion with overloaded functions and methods and ``py::overload_cast``
201
+ (see :ref:`classes`).
202
+
203
+ .. seealso::
204
+
205
+ The file :file:`tests/test_virtual_functions.cpp` contains a complete
206
+ example that demonstrates how to override virtual functions using pybind11
207
+ in more detail.
208
+
209
+ .. _virtual_and_inheritance:
210
+
211
+ Combining virtual functions and inheritance
212
+ ===========================================
213
+
214
+ When combining virtual methods with inheritance, you need to be sure to provide
215
+ an override for each method for which you want to allow overrides from derived
216
+ python classes. For example, suppose we extend the above ``Animal``/``Dog``
217
+ example as follows:
218
+
219
+ .. code-block:: cpp
220
+
221
+ class Animal {
222
+ public:
223
+ virtual std::string go(int n_times) = 0;
224
+ virtual std::string name() { return "unknown"; }
225
+ };
226
+ class Dog : public Animal {
227
+ public:
228
+ std::string go(int n_times) override {
229
+ std::string result;
230
+ for (int i=0; i<n_times; ++i)
231
+ result += bark() + " ";
232
+ return result;
233
+ }
234
+ virtual std::string bark() { return "woof!"; }
235
+ };
236
+
237
+ then the trampoline class for ``Animal`` must, as described in the previous
238
+ section, override ``go()`` and ``name()``, but in order to allow python code to
239
+ inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that
240
+ overrides both the added ``bark()`` method *and* the ``go()`` and ``name()``
241
+ methods inherited from ``Animal`` (even though ``Dog`` doesn't directly
242
+ override the ``name()`` method):
243
+
244
+ .. code-block:: cpp
245
+
246
+ class PyAnimal : public Animal {
247
+ public:
248
+ using Animal::Animal; // Inherit constructors
249
+ std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Animal, go, n_times); }
250
+ std::string name() override { PYBIND11_OVERRIDE(std::string, Animal, name, ); }
251
+ };
252
+ class PyDog : public Dog {
253
+ public:
254
+ using Dog::Dog; // Inherit constructors
255
+ std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, Dog, go, n_times); }
256
+ std::string name() override { PYBIND11_OVERRIDE(std::string, Dog, name, ); }
257
+ std::string bark() override { PYBIND11_OVERRIDE(std::string, Dog, bark, ); }
258
+ };
259
+
260
+ .. note::
261
+
262
+ Note the trailing commas in the ``PYBIND11_OVERRIDE`` calls to ``name()``
263
+ and ``bark()``. These are needed to portably implement a trampoline for a
264
+ function that does not take any arguments. For functions that take
265
+ a nonzero number of arguments, the trailing comma must be omitted.
266
+
267
+ A registered class derived from a pybind11-registered class with virtual
268
+ methods requires a similar trampoline class, *even if* it doesn't explicitly
269
+ declare or override any virtual methods itself:
270
+
271
+ .. code-block:: cpp
272
+
273
+ class Husky : public Dog {};
274
+ class PyHusky : public Husky {
275
+ public:
276
+ using Husky::Husky; // Inherit constructors
277
+ std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Husky, go, n_times); }
278
+ std::string name() override { PYBIND11_OVERRIDE(std::string, Husky, name, ); }
279
+ std::string bark() override { PYBIND11_OVERRIDE(std::string, Husky, bark, ); }
280
+ };
281
+
282
+ There is, however, a technique that can be used to avoid this duplication
283
+ (which can be especially helpful for a base class with several virtual
284
+ methods). The technique involves using template trampoline classes, as
285
+ follows:
286
+
287
+ .. code-block:: cpp
288
+
289
+ template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
290
+ public:
291
+ using AnimalBase::AnimalBase; // Inherit constructors
292
+ std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, AnimalBase, go, n_times); }
293
+ std::string name() override { PYBIND11_OVERRIDE(std::string, AnimalBase, name, ); }
294
+ };
295
+ template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
296
+ public:
297
+ using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
298
+ // Override PyAnimal's pure virtual go() with a non-pure one:
299
+ std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, DogBase, go, n_times); }
300
+ std::string bark() override { PYBIND11_OVERRIDE(std::string, DogBase, bark, ); }
301
+ };
302
+
303
+ This technique has the advantage of requiring just one trampoline method to be
304
+ declared per virtual method and pure virtual method override. It does,
305
+ however, require the compiler to generate at least as many methods (and
306
+ possibly more, if both pure virtual and overridden pure virtual methods are
307
+ exposed, as above).
308
+
309
+ The classes are then registered with pybind11 using:
310
+
311
+ .. code-block:: cpp
312
+
313
+ py::class_<Animal, PyAnimal<>> animal(m, "Animal");
314
+ py::class_<Dog, Animal, PyDog<>> dog(m, "Dog");
315
+ py::class_<Husky, Dog, PyDog<Husky>> husky(m, "Husky");
316
+ // ... add animal, dog, husky definitions
317
+
318
+ Note that ``Husky`` did not require a dedicated trampoline template class at
319
+ all, since it neither declares any new virtual methods nor provides any pure
320
+ virtual method implementations.
321
+
322
+ With either the repeated-virtuals or templated trampoline methods in place, you
323
+ can now create a python class that inherits from ``Dog``:
324
+
325
+ .. code-block:: python
326
+
327
+ class ShihTzu(Dog):
328
+ def bark(self):
329
+ return "yip!"
330
+
331
+ .. seealso::
332
+
333
+ See the file :file:`tests/test_virtual_functions.cpp` for complete examples
334
+ using both the duplication and templated trampoline approaches.
335
+
336
+ .. _extended_aliases:
337
+
338
+ Extended trampoline class functionality
339
+ =======================================
340
+
341
+ .. _extended_class_functionality_forced_trampoline:
342
+
343
+ Forced trampoline class initialisation
344
+ --------------------------------------
345
+ The trampoline classes described in the previous sections are, by default, only
346
+ initialized when needed. More specifically, they are initialized when a python
347
+ class actually inherits from a registered type (instead of merely creating an
348
+ instance of the registered type), or when a registered constructor is only
349
+ valid for the trampoline class but not the registered class. This is primarily
350
+ for performance reasons: when the trampoline class is not needed for anything
351
+ except virtual method dispatching, not initializing the trampoline class
352
+ improves performance by avoiding needing to do a run-time check to see if the
353
+ inheriting python instance has an overridden method.
354
+
355
+ Sometimes, however, it is useful to always initialize a trampoline class as an
356
+ intermediate class that does more than just handle virtual method dispatching.
357
+ For example, such a class might perform extra class initialization, extra
358
+ destruction operations, and might define new members and methods to enable a
359
+ more python-like interface to a class.
360
+
361
+ In order to tell pybind11 that it should *always* initialize the trampoline
362
+ class when creating new instances of a type, the class constructors should be
363
+ declared using ``py::init_alias<Args, ...>()`` instead of the usual
364
+ ``py::init<Args, ...>()``. This forces construction via the trampoline class,
365
+ ensuring member initialization and (eventual) destruction.
366
+
367
+ .. seealso::
368
+
369
+ See the file :file:`tests/test_virtual_functions.cpp` for complete examples
370
+ showing both normal and forced trampoline instantiation.
371
+
372
+ Different method signatures
373
+ ---------------------------
374
+ The macro's introduced in :ref:`overriding_virtuals` cover most of the standard
375
+ use cases when exposing C++ classes to Python. Sometimes it is hard or unwieldy
376
+ to create a direct one-on-one mapping between the arguments and method return
377
+ type.
378
+
379
+ An example would be when the C++ signature contains output arguments using
380
+ references (See also :ref:`faq_reference_arguments`). Another way of solving
381
+ this is to use the method body of the trampoline class to do conversions to the
382
+ input and return of the Python method.
383
+
384
+ The main building block to do so is the :func:`get_override`, this function
385
+ allows retrieving a method implemented in Python from within the trampoline's
386
+ methods. Consider for example a C++ method which has the signature
387
+ ``bool myMethod(int32_t& value)``, where the return indicates whether
388
+ something should be done with the ``value``. This can be made convenient on the
389
+ Python side by allowing the Python function to return ``None`` or an ``int``:
390
+
391
+ .. code-block:: cpp
392
+
393
+ bool MyClass::myMethod(int32_t& value)
394
+ {
395
+ pybind11::gil_scoped_acquire gil; // Acquire the GIL while in this scope.
396
+ // Try to look up the overridden method on the Python side.
397
+ pybind11::function override = pybind11::get_override(this, "myMethod");
398
+ if (override) { // method is found
399
+ auto obj = override(value); // Call the Python function.
400
+ if (py::isinstance<py::int_>(obj)) { // check if it returned a Python integer type
401
+ value = obj.cast<int32_t>(); // Cast it and assign it to the value.
402
+ return true; // Return true; value should be used.
403
+ } else {
404
+ return false; // Python returned none, return false.
405
+ }
406
+ }
407
+ return false; // Alternatively return MyClass::myMethod(value);
408
+ }
409
+
410
+
411
+ .. _custom_constructors:
412
+
413
+ Custom constructors
414
+ ===================
415
+
416
+ The syntax for binding constructors was previously introduced, but it only
417
+ works when a constructor of the appropriate arguments actually exists on the
418
+ C++ side. To extend this to more general cases, pybind11 makes it possible
419
+ to bind factory functions as constructors. For example, suppose you have a
420
+ class like this:
421
+
422
+ .. code-block:: cpp
423
+
424
+ class Example {
425
+ private:
426
+ Example(int); // private constructor
427
+ public:
428
+ // Factory function:
429
+ static Example create(int a) { return Example(a); }
430
+ };
431
+
432
+ py::class_<Example>(m, "Example")
433
+ .def(py::init(&Example::create));
434
+
435
+ While it is possible to create a straightforward binding of the static
436
+ ``create`` method, it may sometimes be preferable to expose it as a constructor
437
+ on the Python side. This can be accomplished by calling ``.def(py::init(...))``
438
+ with the function reference returning the new instance passed as an argument.
439
+ It is also possible to use this approach to bind a function returning a new
440
+ instance by raw pointer or by the holder (e.g. ``std::unique_ptr``).
441
+
442
+ The following example shows the different approaches:
443
+
444
+ .. code-block:: cpp
445
+
446
+ class Example {
447
+ private:
448
+ Example(int); // private constructor
449
+ public:
450
+ // Factory function - returned by value:
451
+ static Example create(int a) { return Example(a); }
452
+
453
+ // These constructors are publicly callable:
454
+ Example(double);
455
+ Example(int, int);
456
+ Example(std::string);
457
+ };
458
+
459
+ py::class_<Example>(m, "Example")
460
+ // Bind the factory function as a constructor:
461
+ .def(py::init(&Example::create))
462
+ // Bind a lambda function returning a pointer wrapped in a holder:
463
+ .def(py::init([](std::string arg) {
464
+ return std::unique_ptr<Example>(new Example(arg));
465
+ }))
466
+ // Return a raw pointer:
467
+ .def(py::init([](int a, int b) { return new Example(a, b); }))
468
+ // You can mix the above with regular C++ constructor bindings as well:
469
+ .def(py::init<double>())
470
+ ;
471
+
472
+ When the constructor is invoked from Python, pybind11 will call the factory
473
+ function and store the resulting C++ instance in the Python instance.
474
+
475
+ When combining factory functions constructors with :ref:`virtual function
476
+ trampolines <overriding_virtuals>` there are two approaches. The first is to
477
+ add a constructor to the alias class that takes a base value by
478
+ rvalue-reference. If such a constructor is available, it will be used to
479
+ construct an alias instance from the value returned by the factory function.
480
+ The second option is to provide two factory functions to ``py::init()``: the
481
+ first will be invoked when no alias class is required (i.e. when the class is
482
+ being used but not inherited from in Python), and the second will be invoked
483
+ when an alias is required.
484
+
485
+ You can also specify a single factory function that always returns an alias
486
+ instance: this will result in behaviour similar to ``py::init_alias<...>()``,
487
+ as described in the :ref:`extended trampoline class documentation
488
+ <extended_aliases>`.
489
+
490
+ The following example shows the different factory approaches for a class with
491
+ an alias:
492
+
493
+ .. code-block:: cpp
494
+
495
+ #include <pybind11/factory.h>
496
+ class Example {
497
+ public:
498
+ // ...
499
+ virtual ~Example() = default;
500
+ };
501
+ class PyExample : public Example {
502
+ public:
503
+ using Example::Example;
504
+ PyExample(Example &&base) : Example(std::move(base)) {}
505
+ };
506
+ py::class_<Example, PyExample>(m, "Example")
507
+ // Returns an Example pointer. If a PyExample is needed, the Example
508
+ // instance will be moved via the extra constructor in PyExample, above.
509
+ .def(py::init([]() { return new Example(); }))
510
+ // Two callbacks:
511
+ .def(py::init([]() { return new Example(); } /* no alias needed */,
512
+ []() { return new PyExample(); } /* alias needed */))
513
+ // *Always* returns an alias instance (like py::init_alias<>())
514
+ .def(py::init([]() { return new PyExample(); }))
515
+ ;
516
+
517
+ Brace initialization
518
+ --------------------
519
+
520
+ ``pybind11::init<>`` internally uses C++11 brace initialization to call the
521
+ constructor of the target class. This means that it can be used to bind
522
+ *implicit* constructors as well:
523
+
524
+ .. code-block:: cpp
525
+
526
+ struct Aggregate {
527
+ int a;
528
+ std::string b;
529
+ };
530
+
531
+ py::class_<Aggregate>(m, "Aggregate")
532
+ .def(py::init<int, const std::string &>());
533
+
534
+ .. note::
535
+
536
+ Note that brace initialization preferentially invokes constructor overloads
537
+ taking a ``std::initializer_list``. In the rare event that this causes an
538
+ issue, you can work around it by using ``py::init(...)`` with a lambda
539
+ function that constructs the new object as desired.
540
+
541
+ .. _classes_with_non_public_destructors:
542
+
543
+ Non-public destructors
544
+ ======================
545
+
546
+ If a class has a private or protected destructor (as might e.g. be the case in
547
+ a singleton pattern), a compile error will occur when creating bindings via
548
+ pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
549
+ is responsible for managing the lifetime of instances will reference the
550
+ destructor even if no deallocations ever take place. In order to expose classes
551
+ with private or protected destructors, it is possible to override the holder
552
+ type via a holder type argument to ``class_``. Pybind11 provides a helper class
553
+ ``py::nodelete`` that disables any destructor invocations. In this case, it is
554
+ crucial that instances are deallocated on the C++ side to avoid memory leaks.
555
+
556
+ .. code-block:: cpp
557
+
558
+ /* ... definition ... */
559
+
560
+ class MyClass {
561
+ private:
562
+ ~MyClass() { }
563
+ };
564
+
565
+ /* ... binding code ... */
566
+
567
+ py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
568
+ .def(py::init<>())
569
+
570
+ .. _destructors_that_call_python:
571
+
572
+ Destructors that call Python
573
+ ============================
574
+
575
+ If a Python function is invoked from a C++ destructor, an exception may be thrown
576
+ of type :class:`error_already_set`. If this error is thrown out of a class destructor,
577
+ ``std::terminate()`` will be called, terminating the process. Class destructors
578
+ must catch all exceptions of type :class:`error_already_set` to discard the Python
579
+ exception using :func:`error_already_set::discard_as_unraisable`.
580
+
581
+ Every Python function should be treated as *possibly throwing*. When a Python generator
582
+ stops yielding items, Python will throw a ``StopIteration`` exception, which can pass
583
+ though C++ destructors if the generator's stack frame holds the last reference to C++
584
+ objects.
585
+
586
+ For more information, see :ref:`the documentation on exceptions <unraisable_exceptions>`.
587
+
588
+ .. code-block:: cpp
589
+
590
+ class MyClass {
591
+ public:
592
+ ~MyClass() {
593
+ try {
594
+ py::print("Even printing is dangerous in a destructor");
595
+ py::exec("raise ValueError('This is an unraisable exception')");
596
+ } catch (py::error_already_set &e) {
597
+ // error_context should be information about where/why the occurred,
598
+ // e.g. use __func__ to get the name of the current function
599
+ e.discard_as_unraisable(__func__);
600
+ }
601
+ }
602
+ };
603
+
604
+ .. note::
605
+
606
+ pybind11 does not support C++ destructors marked ``noexcept(false)``.
607
+
608
+ .. versionadded:: 2.6
609
+
610
+ .. _implicit_conversions:
611
+
612
+ Implicit conversions
613
+ ====================
614
+
615
+ Suppose that instances of two types ``A`` and ``B`` are used in a project, and
616
+ that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
617
+ could be a fixed and an arbitrary precision number type).
618
+
619
+ .. code-block:: cpp
620
+
621
+ py::class_<A>(m, "A")
622
+ /// ... members ...
623
+
624
+ py::class_<B>(m, "B")
625
+ .def(py::init<A>())
626
+ /// ... members ...
627
+
628
+ m.def("func",
629
+ [](const B &) { /* .... */ }
630
+ );
631
+
632
+ To invoke the function ``func`` using a variable ``a`` containing an ``A``
633
+ instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
634
+ will automatically apply an implicit type conversion, which makes it possible
635
+ to directly write ``func(a)``.
636
+
637
+ In this situation (i.e. where ``B`` has a constructor that converts from
638
+ ``A``), the following statement enables similar implicit conversions on the
639
+ Python side:
640
+
641
+ .. code-block:: cpp
642
+
643
+ py::implicitly_convertible<A, B>();
644
+
645
+ .. note::
646
+
647
+ Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom
648
+ data type that is exposed to Python via pybind11.
649
+
650
+ To prevent runaway recursion, implicit conversions are non-reentrant: an
651
+ implicit conversion invoked as part of another implicit conversion of the
652
+ same type (i.e. from ``A`` to ``B``) will fail.
653
+
654
+ .. _static_properties:
655
+
656
+ Static properties
657
+ =================
658
+
659
+ The section on :ref:`properties` discussed the creation of instance properties
660
+ that are implemented in terms of C++ getters and setters.
661
+
662
+ Static properties can also be created in a similar way to expose getters and
663
+ setters of static class attributes. Note that the implicit ``self`` argument
664
+ also exists in this case and is used to pass the Python ``type`` subclass
665
+ instance. This parameter will often not be needed by the C++ side, and the
666
+ following example illustrates how to instantiate a lambda getter function
667
+ that ignores it:
668
+
669
+ .. code-block:: cpp
670
+
671
+ py::class_<Foo>(m, "Foo")
672
+ .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
673
+
674
+ Operator overloading
675
+ ====================
676
+
677
+ Suppose that we're given the following ``Vector2`` class with a vector addition
678
+ and scalar multiplication operation, all implemented using overloaded operators
679
+ in C++.
680
+
681
+ .. code-block:: cpp
682
+
683
+ class Vector2 {
684
+ public:
685
+ Vector2(float x, float y) : x(x), y(y) { }
686
+
687
+ Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
688
+ Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
689
+ Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
690
+ Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
691
+
692
+ friend Vector2 operator*(float f, const Vector2 &v) {
693
+ return Vector2(f * v.x, f * v.y);
694
+ }
695
+
696
+ std::string toString() const {
697
+ return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
698
+ }
699
+ private:
700
+ float x, y;
701
+ };
702
+
703
+ The following snippet shows how the above operators can be conveniently exposed
704
+ to Python.
705
+
706
+ .. code-block:: cpp
707
+
708
+ #include <pybind11/operators.h>
709
+
710
+ PYBIND11_MODULE(example, m) {
711
+ py::class_<Vector2>(m, "Vector2")
712
+ .def(py::init<float, float>())
713
+ .def(py::self + py::self)
714
+ .def(py::self += py::self)
715
+ .def(py::self *= float())
716
+ .def(float() * py::self)
717
+ .def(py::self * float())
718
+ .def(-py::self)
719
+ .def("__repr__", &Vector2::toString);
720
+ }
721
+
722
+ Note that a line like
723
+
724
+ .. code-block:: cpp
725
+
726
+ .def(py::self * float())
727
+
728
+ is really just short hand notation for
729
+
730
+ .. code-block:: cpp
731
+
732
+ .def("__mul__", [](const Vector2 &a, float b) {
733
+ return a * b;
734
+ }, py::is_operator())
735
+
736
+ This can be useful for exposing additional operators that don't exist on the
737
+ C++ side, or to perform other types of customization. The ``py::is_operator``
738
+ flag marker is needed to inform pybind11 that this is an operator, which
739
+ returns ``NotImplemented`` when invoked with incompatible arguments rather than
740
+ throwing a type error.
741
+
742
+ .. note::
743
+
744
+ To use the more convenient ``py::self`` notation, the additional
745
+ header file :file:`pybind11/operators.h` must be included.
746
+
747
+ .. seealso::
748
+
749
+ The file :file:`tests/test_operator_overloading.cpp` contains a
750
+ complete example that demonstrates how to work with overloaded operators in
751
+ more detail.
752
+
753
+ .. _pickling:
754
+
755
+ Pickling support
756
+ ================
757
+
758
+ Python's ``pickle`` module provides a powerful facility to serialize and
759
+ de-serialize a Python object graph into a binary data stream. To pickle and
760
+ unpickle C++ classes using pybind11, a ``py::pickle()`` definition must be
761
+ provided. Suppose the class in question has the following signature:
762
+
763
+ .. code-block:: cpp
764
+
765
+ class Pickleable {
766
+ public:
767
+ Pickleable(const std::string &value) : m_value(value) { }
768
+ const std::string &value() const { return m_value; }
769
+
770
+ void setExtra(int extra) { m_extra = extra; }
771
+ int extra() const { return m_extra; }
772
+ private:
773
+ std::string m_value;
774
+ int m_extra = 0;
775
+ };
776
+
777
+ Pickling support in Python is enabled by defining the ``__setstate__`` and
778
+ ``__getstate__`` methods [#f3]_. For pybind11 classes, use ``py::pickle()``
779
+ to bind these two functions:
780
+
781
+ .. code-block:: cpp
782
+
783
+ py::class_<Pickleable>(m, "Pickleable")
784
+ .def(py::init<std::string>())
785
+ .def("value", &Pickleable::value)
786
+ .def("extra", &Pickleable::extra)
787
+ .def("setExtra", &Pickleable::setExtra)
788
+ .def(py::pickle(
789
+ [](const Pickleable &p) { // __getstate__
790
+ /* Return a tuple that fully encodes the state of the object */
791
+ return py::make_tuple(p.value(), p.extra());
792
+ },
793
+ [](py::tuple t) { // __setstate__
794
+ if (t.size() != 2)
795
+ throw std::runtime_error("Invalid state!");
796
+
797
+ /* Create a new C++ instance */
798
+ Pickleable p(t[0].cast<std::string>());
799
+
800
+ /* Assign any additional state */
801
+ p.setExtra(t[1].cast<int>());
802
+
803
+ return p;
804
+ }
805
+ ));
806
+
807
+ The ``__setstate__`` part of the ``py::pickle()`` definition follows the same
808
+ rules as the single-argument version of ``py::init()``. The return type can be
809
+ a value, pointer or holder type. See :ref:`custom_constructors` for details.
810
+
811
+ An instance can now be pickled as follows:
812
+
813
+ .. code-block:: python
814
+
815
+ try:
816
+ import cPickle as pickle # Use cPickle on Python 2.7
817
+ except ImportError:
818
+ import pickle
819
+
820
+ p = Pickleable("test_value")
821
+ p.setExtra(15)
822
+ data = pickle.dumps(p, 2)
823
+
824
+
825
+ .. note::
826
+ Note that only the cPickle module is supported on Python 2.7.
827
+
828
+ The second argument to ``dumps`` is also crucial: it selects the pickle
829
+ protocol version 2, since the older version 1 is not supported. Newer
830
+ versions are also fine—for instance, specify ``-1`` to always use the
831
+ latest available version. Beware: failure to follow these instructions
832
+ will cause important pybind11 memory allocation routines to be skipped
833
+ during unpickling, which will likely lead to memory corruption and/or
834
+ segmentation faults.
835
+
836
+ .. seealso::
837
+
838
+ The file :file:`tests/test_pickling.cpp` contains a complete example
839
+ that demonstrates how to pickle and unpickle types using pybind11 in more
840
+ detail.
841
+
842
+ .. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
843
+
844
+ Deepcopy support
845
+ ================
846
+
847
+ Python normally uses references in assignments. Sometimes a real copy is needed
848
+ to prevent changing all copies. The ``copy`` module [#f5]_ provides these
849
+ capabilities.
850
+
851
+ On Python 3, a class with pickle support is automatically also (deep)copy
852
+ compatible. However, performance can be improved by adding custom
853
+ ``__copy__`` and ``__deepcopy__`` methods. With Python 2.7, these custom methods
854
+ are mandatory for (deep)copy compatibility, because pybind11 only supports
855
+ cPickle.
856
+
857
+ For simple classes (deep)copy can be enabled by using the copy constructor,
858
+ which should look as follows:
859
+
860
+ .. code-block:: cpp
861
+
862
+ py::class_<Copyable>(m, "Copyable")
863
+ .def("__copy__", [](const Copyable &self) {
864
+ return Copyable(self);
865
+ })
866
+ .def("__deepcopy__", [](const Copyable &self, py::dict) {
867
+ return Copyable(self);
868
+ }, "memo"_a);
869
+
870
+ .. note::
871
+
872
+ Dynamic attributes will not be copied in this example.
873
+
874
+ .. [#f5] https://docs.python.org/3/library/copy.html
875
+
876
+ Multiple Inheritance
877
+ ====================
878
+
879
+ pybind11 can create bindings for types that derive from multiple base types
880
+ (aka. *multiple inheritance*). To do so, specify all bases in the template
881
+ arguments of the ``class_`` declaration:
882
+
883
+ .. code-block:: cpp
884
+
885
+ py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
886
+ ...
887
+
888
+ The base types can be specified in arbitrary order, and they can even be
889
+ interspersed with alias types and holder types (discussed earlier in this
890
+ document)---pybind11 will automatically find out which is which. The only
891
+ requirement is that the first template argument is the type to be declared.
892
+
893
+ It is also permitted to inherit multiply from exported C++ classes in Python,
894
+ as well as inheriting from multiple Python and/or pybind11-exported classes.
895
+
896
+ There is one caveat regarding the implementation of this feature:
897
+
898
+ When only one base type is specified for a C++ type that actually has multiple
899
+ bases, pybind11 will assume that it does not participate in multiple
900
+ inheritance, which can lead to undefined behavior. In such cases, add the tag
901
+ ``multiple_inheritance`` to the class constructor:
902
+
903
+ .. code-block:: cpp
904
+
905
+ py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
906
+
907
+ The tag is redundant and does not need to be specified when multiple base types
908
+ are listed.
909
+
910
+ .. _module_local:
911
+
912
+ Module-local class bindings
913
+ ===========================
914
+
915
+ When creating a binding for a class, pybind11 by default makes that binding
916
+ "global" across modules. What this means is that a type defined in one module
917
+ can be returned from any module resulting in the same Python type. For
918
+ example, this allows the following:
919
+
920
+ .. code-block:: cpp
921
+
922
+ // In the module1.cpp binding code for module1:
923
+ py::class_<Pet>(m, "Pet")
924
+ .def(py::init<std::string>())
925
+ .def_readonly("name", &Pet::name);
926
+
927
+ .. code-block:: cpp
928
+
929
+ // In the module2.cpp binding code for module2:
930
+ m.def("create_pet", [](std::string name) { return new Pet(name); });
931
+
932
+ .. code-block:: pycon
933
+
934
+ >>> from module1 import Pet
935
+ >>> from module2 import create_pet
936
+ >>> pet1 = Pet("Kitty")
937
+ >>> pet2 = create_pet("Doggy")
938
+ >>> pet2.name()
939
+ 'Doggy'
940
+
941
+ When writing binding code for a library, this is usually desirable: this
942
+ allows, for example, splitting up a complex library into multiple Python
943
+ modules.
944
+
945
+ In some cases, however, this can cause conflicts. For example, suppose two
946
+ unrelated modules make use of an external C++ library and each provide custom
947
+ bindings for one of that library's classes. This will result in an error when
948
+ a Python program attempts to import both modules (directly or indirectly)
949
+ because of conflicting definitions on the external type:
950
+
951
+ .. code-block:: cpp
952
+
953
+ // dogs.cpp
954
+
955
+ // Binding for external library class:
956
+ py::class<pets::Pet>(m, "Pet")
957
+ .def("name", &pets::Pet::name);
958
+
959
+ // Binding for local extension class:
960
+ py::class<Dog, pets::Pet>(m, "Dog")
961
+ .def(py::init<std::string>());
962
+
963
+ .. code-block:: cpp
964
+
965
+ // cats.cpp, in a completely separate project from the above dogs.cpp.
966
+
967
+ // Binding for external library class:
968
+ py::class<pets::Pet>(m, "Pet")
969
+ .def("get_name", &pets::Pet::name);
970
+
971
+ // Binding for local extending class:
972
+ py::class<Cat, pets::Pet>(m, "Cat")
973
+ .def(py::init<std::string>());
974
+
975
+ .. code-block:: pycon
976
+
977
+ >>> import cats
978
+ >>> import dogs
979
+ Traceback (most recent call last):
980
+ File "<stdin>", line 1, in <module>
981
+ ImportError: generic_type: type "Pet" is already registered!
982
+
983
+ To get around this, you can tell pybind11 to keep the external class binding
984
+ localized to the module by passing the ``py::module_local()`` attribute into
985
+ the ``py::class_`` constructor:
986
+
987
+ .. code-block:: cpp
988
+
989
+ // Pet binding in dogs.cpp:
990
+ py::class<pets::Pet>(m, "Pet", py::module_local())
991
+ .def("name", &pets::Pet::name);
992
+
993
+ .. code-block:: cpp
994
+
995
+ // Pet binding in cats.cpp:
996
+ py::class<pets::Pet>(m, "Pet", py::module_local())
997
+ .def("get_name", &pets::Pet::name);
998
+
999
+ This makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes,
1000
+ avoiding the conflict and allowing both modules to be loaded. C++ code in the
1001
+ ``dogs`` module that casts or returns a ``Pet`` instance will result in a
1002
+ ``dogs.Pet`` Python instance, while C++ code in the ``cats`` module will result
1003
+ in a ``cats.Pet`` Python instance.
1004
+
1005
+ This does come with two caveats, however: First, external modules cannot return
1006
+ or cast a ``Pet`` instance to Python (unless they also provide their own local
1007
+ bindings). Second, from the Python point of view they are two distinct classes.
1008
+
1009
+ Note that the locality only applies in the C++ -> Python direction. When
1010
+ passing such a ``py::module_local`` type into a C++ function, the module-local
1011
+ classes are still considered. This means that if the following function is
1012
+ added to any module (including but not limited to the ``cats`` and ``dogs``
1013
+ modules above) it will be callable with either a ``dogs.Pet`` or ``cats.Pet``
1014
+ argument:
1015
+
1016
+ .. code-block:: cpp
1017
+
1018
+ m.def("pet_name", [](const pets::Pet &pet) { return pet.name(); });
1019
+
1020
+ For example, suppose the above function is added to each of ``cats.cpp``,
1021
+ ``dogs.cpp`` and ``frogs.cpp`` (where ``frogs.cpp`` is some other module that
1022
+ does *not* bind ``Pets`` at all).
1023
+
1024
+ .. code-block:: pycon
1025
+
1026
+ >>> import cats, dogs, frogs # No error because of the added py::module_local()
1027
+ >>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover")
1028
+ >>> (cats.pet_name(mycat), dogs.pet_name(mydog))
1029
+ ('Fluffy', 'Rover')
1030
+ >>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat))
1031
+ ('Rover', 'Fluffy', 'Fluffy')
1032
+
1033
+ It is possible to use ``py::module_local()`` registrations in one module even
1034
+ if another module registers the same type globally: within the module with the
1035
+ module-local definition, all C++ instances will be cast to the associated bound
1036
+ Python type. In other modules any such values are converted to the global
1037
+ Python type created elsewhere.
1038
+
1039
+ .. note::
1040
+
1041
+ STL bindings (as provided via the optional :file:`pybind11/stl_bind.h`
1042
+ header) apply ``py::module_local`` by default when the bound type might
1043
+ conflict with other modules; see :ref:`stl_bind` for details.
1044
+
1045
+ .. note::
1046
+
1047
+ The localization of the bound types is actually tied to the shared object
1048
+ or binary generated by the compiler/linker. For typical modules created
1049
+ with ``PYBIND11_MODULE()``, this distinction is not significant. It is
1050
+ possible, however, when :ref:`embedding` to embed multiple modules in the
1051
+ same binary (see :ref:`embedding_modules`). In such a case, the
1052
+ localization will apply across all embedded modules within the same binary.
1053
+
1054
+ .. seealso::
1055
+
1056
+ The file :file:`tests/test_local_bindings.cpp` contains additional examples
1057
+ that demonstrate how ``py::module_local()`` works.
1058
+
1059
+ Binding protected member functions
1060
+ ==================================
1061
+
1062
+ It's normally not possible to expose ``protected`` member functions to Python:
1063
+
1064
+ .. code-block:: cpp
1065
+
1066
+ class A {
1067
+ protected:
1068
+ int foo() const { return 42; }
1069
+ };
1070
+
1071
+ py::class_<A>(m, "A")
1072
+ .def("foo", &A::foo); // error: 'foo' is a protected member of 'A'
1073
+
1074
+ On one hand, this is good because non-``public`` members aren't meant to be
1075
+ accessed from the outside. But we may want to make use of ``protected``
1076
+ functions in derived Python classes.
1077
+
1078
+ The following pattern makes this possible:
1079
+
1080
+ .. code-block:: cpp
1081
+
1082
+ class A {
1083
+ protected:
1084
+ int foo() const { return 42; }
1085
+ };
1086
+
1087
+ class Publicist : public A { // helper type for exposing protected functions
1088
+ public:
1089
+ using A::foo; // inherited with different access modifier
1090
+ };
1091
+
1092
+ py::class_<A>(m, "A") // bind the primary class
1093
+ .def("foo", &Publicist::foo); // expose protected methods via the publicist
1094
+
1095
+ This works because ``&Publicist::foo`` is exactly the same function as
1096
+ ``&A::foo`` (same signature and address), just with a different access
1097
+ modifier. The only purpose of the ``Publicist`` helper class is to make
1098
+ the function name ``public``.
1099
+
1100
+ If the intent is to expose ``protected`` ``virtual`` functions which can be
1101
+ overridden in Python, the publicist pattern can be combined with the previously
1102
+ described trampoline:
1103
+
1104
+ .. code-block:: cpp
1105
+
1106
+ class A {
1107
+ public:
1108
+ virtual ~A() = default;
1109
+
1110
+ protected:
1111
+ virtual int foo() const { return 42; }
1112
+ };
1113
+
1114
+ class Trampoline : public A {
1115
+ public:
1116
+ int foo() const override { PYBIND11_OVERRIDE(int, A, foo, ); }
1117
+ };
1118
+
1119
+ class Publicist : public A {
1120
+ public:
1121
+ using A::foo;
1122
+ };
1123
+
1124
+ py::class_<A, Trampoline>(m, "A") // <-- `Trampoline` here
1125
+ .def("foo", &Publicist::foo); // <-- `Publicist` here, not `Trampoline`!
1126
+
1127
+ .. note::
1128
+
1129
+ MSVC 2015 has a compiler bug (fixed in version 2017) which
1130
+ requires a more explicit function binding in the form of
1131
+ ``.def("foo", static_cast<int (A::*)() const>(&Publicist::foo));``
1132
+ where ``int (A::*)() const`` is the type of ``A::foo``.
1133
+
1134
+ Binding final classes
1135
+ =====================
1136
+
1137
+ Some classes may not be appropriate to inherit from. In C++11, classes can
1138
+ use the ``final`` specifier to ensure that a class cannot be inherited from.
1139
+ The ``py::is_final`` attribute can be used to ensure that Python classes
1140
+ cannot inherit from a specified type. The underlying C++ type does not need
1141
+ to be declared final.
1142
+
1143
+ .. code-block:: cpp
1144
+
1145
+ class IsFinal final {};
1146
+
1147
+ py::class_<IsFinal>(m, "IsFinal", py::is_final());
1148
+
1149
+ When you try to inherit from such a class in Python, you will now get this
1150
+ error:
1151
+
1152
+ .. code-block:: pycon
1153
+
1154
+ >>> class PyFinalChild(IsFinal):
1155
+ ... pass
1156
+ TypeError: type 'IsFinal' is not an acceptable base type
1157
+
1158
+ .. note:: This attribute is currently ignored on PyPy
1159
+
1160
+ .. versionadded:: 2.6
1161
+
1162
+ Custom automatic downcasters
1163
+ ============================
1164
+
1165
+ As explained in :ref:`inheritance`, pybind11 comes with built-in
1166
+ understanding of the dynamic type of polymorphic objects in C++; that
1167
+ is, returning a Pet to Python produces a Python object that knows it's
1168
+ wrapping a Dog, if Pet has virtual methods and pybind11 knows about
1169
+ Dog and this Pet is in fact a Dog. Sometimes, you might want to
1170
+ provide this automatic downcasting behavior when creating bindings for
1171
+ a class hierarchy that does not use standard C++ polymorphism, such as
1172
+ LLVM [#f4]_. As long as there's some way to determine at runtime
1173
+ whether a downcast is safe, you can proceed by specializing the
1174
+ ``pybind11::polymorphic_type_hook`` template:
1175
+
1176
+ .. code-block:: cpp
1177
+
1178
+ enum class PetKind { Cat, Dog, Zebra };
1179
+ struct Pet { // Not polymorphic: has no virtual methods
1180
+ const PetKind kind;
1181
+ int age = 0;
1182
+ protected:
1183
+ Pet(PetKind _kind) : kind(_kind) {}
1184
+ };
1185
+ struct Dog : Pet {
1186
+ Dog() : Pet(PetKind::Dog) {}
1187
+ std::string sound = "woof!";
1188
+ std::string bark() const { return sound; }
1189
+ };
1190
+
1191
+ namespace pybind11 {
1192
+ template<> struct polymorphic_type_hook<Pet> {
1193
+ static const void *get(const Pet *src, const std::type_info*& type) {
1194
+ // note that src may be nullptr
1195
+ if (src && src->kind == PetKind::Dog) {
1196
+ type = &typeid(Dog);
1197
+ return static_cast<const Dog*>(src);
1198
+ }
1199
+ return src;
1200
+ }
1201
+ };
1202
+ } // namespace pybind11
1203
+
1204
+ When pybind11 wants to convert a C++ pointer of type ``Base*`` to a
1205
+ Python object, it calls ``polymorphic_type_hook<Base>::get()`` to
1206
+ determine if a downcast is possible. The ``get()`` function should use
1207
+ whatever runtime information is available to determine if its ``src``
1208
+ parameter is in fact an instance of some class ``Derived`` that
1209
+ inherits from ``Base``. If it finds such a ``Derived``, it sets ``type
1210
+ = &typeid(Derived)`` and returns a pointer to the ``Derived`` object
1211
+ that contains ``src``. Otherwise, it just returns ``src``, leaving
1212
+ ``type`` at its default value of nullptr. If you set ``type`` to a
1213
+ type that pybind11 doesn't know about, no downcasting will occur, and
1214
+ the original ``src`` pointer will be used with its static type
1215
+ ``Base*``.
1216
+
1217
+ It is critical that the returned pointer and ``type`` argument of
1218
+ ``get()`` agree with each other: if ``type`` is set to something
1219
+ non-null, the returned pointer must point to the start of an object
1220
+ whose type is ``type``. If the hierarchy being exposed uses only
1221
+ single inheritance, a simple ``return src;`` will achieve this just
1222
+ fine, but in the general case, you must cast ``src`` to the
1223
+ appropriate derived-class pointer (e.g. using
1224
+ ``static_cast<Derived>(src)``) before allowing it to be returned as a
1225
+ ``void*``.
1226
+
1227
+ .. [#f4] https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html
1228
+
1229
+ .. note::
1230
+
1231
+ pybind11's standard support for downcasting objects whose types
1232
+ have virtual methods is implemented using
1233
+ ``polymorphic_type_hook`` too, using the standard C++ ability to
1234
+ determine the most-derived type of a polymorphic object using
1235
+ ``typeid()`` and to cast a base pointer to that most-derived type
1236
+ (even if you don't know what it is) using ``dynamic_cast<void*>``.
1237
+
1238
+ .. seealso::
1239
+
1240
+ The file :file:`tests/test_tagbased_polymorphic.cpp` contains a
1241
+ more complete example, including a demonstration of how to provide
1242
+ automatic downcasting for an entire class hierarchy without
1243
+ writing one get() function for each class.
1244
+
1245
+ Accessing the type object
1246
+ =========================
1247
+
1248
+ You can get the type object from a C++ class that has already been registered using:
1249
+
1250
+ .. code-block:: python
1251
+
1252
+ py::type T_py = py::type::of<T>();
1253
+
1254
+ You can directly use ``py::type::of(ob)`` to get the type object from any python
1255
+ object, just like ``type(ob)`` in Python.
1256
+
1257
+ .. note::
1258
+
1259
+ Other types, like ``py::type::of<int>()``, do not work, see :ref:`type-conversions`.
1260
+
1261
+ .. versionadded:: 2.6
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/embedding.rst ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def add(i, j):
126
+ return i + j
127
+
128
+
129
+ .. code-block:: cpp
130
+
131
+ py::module_ calc = py::module_::import("calc");
132
+ py::object result = calc.attr("add")(1, 2);
133
+ int n = result.cast<int>();
134
+ assert(n == 3);
135
+
136
+ Modules can be reloaded using `module_::reload()` if the source is modified e.g.
137
+ by an external process. This can be useful in scenarios where the application
138
+ imports a user defined data processing script which needs to be updated after
139
+ changes by the user. Note that this function does not reload modules recursively.
140
+
141
+ .. _embedding_modules:
142
+
143
+ Adding embedded modules
144
+ =======================
145
+
146
+ Embedded binary modules can be added using the `PYBIND11_EMBEDDED_MODULE` macro.
147
+ Note that the definition must be placed at global scope. They can be imported
148
+ like any other module.
149
+
150
+ .. code-block:: cpp
151
+
152
+ #include <pybind11/embed.h>
153
+ namespace py = pybind11;
154
+
155
+ PYBIND11_EMBEDDED_MODULE(fast_calc, m) {
156
+ // `m` is a `py::module_` which is used to bind functions and classes
157
+ m.def("add", [](int i, int j) {
158
+ return i + j;
159
+ });
160
+ }
161
+
162
+ int main() {
163
+ py::scoped_interpreter guard{};
164
+
165
+ auto fast_calc = py::module_::import("fast_calc");
166
+ auto result = fast_calc.attr("add")(1, 2).cast<int>();
167
+ assert(result == 3);
168
+ }
169
+
170
+ Unlike extension modules where only a single binary module can be created, on
171
+ the embedded side an unlimited number of modules can be added using multiple
172
+ `PYBIND11_EMBEDDED_MODULE` definitions (as long as they have unique names).
173
+
174
+ These modules are added to Python's list of builtins, so they can also be
175
+ imported in pure Python files loaded by the interpreter. Everything interacts
176
+ naturally:
177
+
178
+ .. code-block:: python
179
+
180
+ """py_module.py located in the working directory"""
181
+ import cpp_module
182
+
183
+ a = cpp_module.a
184
+ b = a + 1
185
+
186
+
187
+ .. code-block:: cpp
188
+
189
+ #include <pybind11/embed.h>
190
+ namespace py = pybind11;
191
+
192
+ PYBIND11_EMBEDDED_MODULE(cpp_module, m) {
193
+ m.attr("a") = 1;
194
+ }
195
+
196
+ int main() {
197
+ py::scoped_interpreter guard{};
198
+
199
+ auto py_module = py::module_::import("py_module");
200
+
201
+ auto locals = py::dict("fmt"_a="{} + {} = {}", **py_module.attr("__dict__"));
202
+ assert(locals["a"].cast<int>() == 1);
203
+ assert(locals["b"].cast<int>() == 2);
204
+
205
+ py::exec(R"(
206
+ c = a + b
207
+ message = fmt.format(a, b, c)
208
+ )", py::globals(), locals);
209
+
210
+ assert(locals["c"].cast<int>() == 3);
211
+ assert(locals["message"].cast<std::string>() == "1 + 2 = 3");
212
+ }
213
+
214
+
215
+ Interpreter lifetime
216
+ ====================
217
+
218
+ The Python interpreter shuts down when `scoped_interpreter` is destroyed. After
219
+ this, creating a new instance will restart the interpreter. Alternatively, the
220
+ `initialize_interpreter` / `finalize_interpreter` pair of functions can be used
221
+ to directly set the state at any time.
222
+
223
+ Modules created with pybind11 can be safely re-initialized after the interpreter
224
+ has been restarted. However, this may not apply to third-party extension modules.
225
+ The issue is that Python itself cannot completely unload extension modules and
226
+ there are several caveats with regard to interpreter restarting. In short, not
227
+ all memory may be freed, either due to Python reference cycles or user-created
228
+ global data. All the details can be found in the CPython documentation.
229
+
230
+ .. warning::
231
+
232
+ Creating two concurrent `scoped_interpreter` guards is a fatal error. So is
233
+ calling `initialize_interpreter` for a second time after the interpreter
234
+ has already been initialized.
235
+
236
+ Do not use the raw CPython API functions ``Py_Initialize`` and
237
+ ``Py_Finalize`` as these do not properly handle the lifetime of
238
+ pybind11's internal data.
239
+
240
+
241
+ Sub-interpreter support
242
+ =======================
243
+
244
+ Creating multiple copies of `scoped_interpreter` is not possible because it
245
+ represents the main Python interpreter. Sub-interpreters are something different
246
+ and they do permit the existence of multiple interpreters. This is an advanced
247
+ feature of the CPython API and should be handled with care. pybind11 does not
248
+ currently offer a C++ interface for sub-interpreters, so refer to the CPython
249
+ documentation for all the details regarding this feature.
250
+
251
+ We'll just mention a couple of caveats the sub-interpreters support in pybind11:
252
+
253
+ 1. Sub-interpreters will not receive independent copies of embedded modules.
254
+ Instead, these are shared and modifications in one interpreter may be
255
+ reflected in another.
256
+
257
+ 2. Managing multiple threads, multiple interpreters and the GIL can be
258
+ challenging and there are several caveats here, even within the pure
259
+ CPython API (please refer to the Python docs for details). As for
260
+ pybind11, keep in mind that `gil_scoped_release` and `gil_scoped_acquire`
261
+ do not take sub-interpreters into account.
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/exceptions.rst ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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` | ``import_error`` |
60
+ +--------------------------------------+--------------------------------------+
61
+ | Any other exception | ``RuntimeError`` |
62
+ +--------------------------------------+--------------------------------------+
63
+
64
+ Exception translation is not bidirectional. That is, *catching* the C++
65
+ exceptions defined above above will not trap exceptions that originate from
66
+ Python. For that, catch :class:`pybind11::error_already_set`. See :ref:`below
67
+ <handling_python_exceptions_cpp>` for further details.
68
+
69
+ There is also a special exception :class:`cast_error` that is thrown by
70
+ :func:`handle::call` when the input arguments cannot be converted to Python
71
+ objects.
72
+
73
+ Registering custom translators
74
+ ==============================
75
+
76
+ If the default exception conversion policy described above is insufficient,
77
+ pybind11 also provides support for registering custom exception translators.
78
+ To register a simple exception conversion that translates a C++ exception into
79
+ a new Python exception using the C++ exception's ``what()`` method, a helper
80
+ function is available:
81
+
82
+ .. code-block:: cpp
83
+
84
+ py::register_exception<CppExp>(module, "PyExp");
85
+
86
+ This call creates a Python exception class with the name ``PyExp`` in the given
87
+ module and automatically converts any encountered exceptions of type ``CppExp``
88
+ into Python exceptions of type ``PyExp``.
89
+
90
+ It is possible to specify base class for the exception using the third
91
+ parameter, a `handle`:
92
+
93
+ .. code-block:: cpp
94
+
95
+ py::register_exception<CppExp>(module, "PyExp", PyExc_RuntimeError);
96
+
97
+ Then `PyExp` can be caught both as `PyExp` and `RuntimeError`.
98
+
99
+ The class objects of the built-in Python exceptions are listed in the Python
100
+ documentation on `Standard Exceptions <https://docs.python.org/3/c-api/exceptions.html#standard-exceptions>`_.
101
+ The default base class is `PyExc_Exception`.
102
+
103
+ When more advanced exception translation is needed, the function
104
+ ``py::register_exception_translator(translator)`` can be used to register
105
+ functions that can translate arbitrary exception types (and which may include
106
+ additional logic to do so). The function takes a stateless callable (e.g. a
107
+ function pointer or a lambda function without captured variables) with the call
108
+ signature ``void(std::exception_ptr)``.
109
+
110
+ When a C++ exception is thrown, the registered exception translators are tried
111
+ in reverse order of registration (i.e. the last registered translator gets the
112
+ first shot at handling the exception).
113
+
114
+ Inside the translator, ``std::rethrow_exception`` should be used within
115
+ a try block to re-throw the exception. One or more catch clauses to catch
116
+ the appropriate exceptions should then be used with each clause using
117
+ ``PyErr_SetString`` to set a Python exception or ``ex(string)`` to set
118
+ the python exception to a custom exception type (see below).
119
+
120
+ To declare a custom Python exception type, declare a ``py::exception`` variable
121
+ and use this in the associated exception translator (note: it is often useful
122
+ to make this a static declaration when using it inside a lambda expression
123
+ without requiring capturing).
124
+
125
+ The following example demonstrates this for a hypothetical exception classes
126
+ ``MyCustomException`` and ``OtherException``: the first is translated to a
127
+ custom python exception ``MyCustomError``, while the second is translated to a
128
+ standard python RuntimeError:
129
+
130
+ .. code-block:: cpp
131
+
132
+ static py::exception<MyCustomException> exc(m, "MyCustomError");
133
+ py::register_exception_translator([](std::exception_ptr p) {
134
+ try {
135
+ if (p) std::rethrow_exception(p);
136
+ } catch (const MyCustomException &e) {
137
+ exc(e.what());
138
+ } catch (const OtherException &e) {
139
+ PyErr_SetString(PyExc_RuntimeError, e.what());
140
+ }
141
+ });
142
+
143
+ Multiple exceptions can be handled by a single translator, as shown in the
144
+ example above. If the exception is not caught by the current translator, the
145
+ previously registered one gets a chance.
146
+
147
+ If none of the registered exception translators is able to handle the
148
+ exception, it is handled by the default converter as described in the previous
149
+ section.
150
+
151
+ .. seealso::
152
+
153
+ The file :file:`tests/test_exceptions.cpp` contains examples
154
+ of various custom exception translators and custom exception types.
155
+
156
+ .. note::
157
+
158
+ Call either ``PyErr_SetString`` or a custom exception's call
159
+ operator (``exc(string)``) for every exception caught in a custom exception
160
+ translator. Failure to do so will cause Python to crash with ``SystemError:
161
+ error return without exception set``.
162
+
163
+ Exceptions that you do not plan to handle should simply not be caught, or
164
+ may be explicitly (re-)thrown to delegate it to the other,
165
+ previously-declared existing exception translators.
166
+
167
+ Note that ``libc++`` and ``libstdc++`` `behave differently <https://stackoverflow.com/questions/19496643/using-clang-fvisibility-hidden-and-typeinfo-and-type-erasure/28827430>`_
168
+ with ``-fvisibility=hidden``. Therefore exceptions that are used across ABI boundaries need to be explicitly exported, as exercised in ``tests/test_exceptions.h``.
169
+ See also: "Problems with C++ exceptions" under `GCC Wiki <https://gcc.gnu.org/wiki/Visibility>`_.
170
+
171
+ .. _handling_python_exceptions_cpp:
172
+
173
+ Handling exceptions from Python in C++
174
+ ======================================
175
+
176
+ When C++ calls Python functions, such as in a callback function or when
177
+ manipulating Python objects, and Python raises an ``Exception``, pybind11
178
+ converts the Python exception into a C++ exception of type
179
+ :class:`pybind11::error_already_set` whose payload contains a C++ string textual
180
+ summary and the actual Python exception. ``error_already_set`` is used to
181
+ propagate Python exception back to Python (or possibly, handle them in C++).
182
+
183
+ .. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
184
+
185
+ +--------------------------------------+--------------------------------------+
186
+ | Exception raised in Python | Thrown as C++ exception type |
187
+ +======================================+======================================+
188
+ | Any Python ``Exception`` | :class:`pybind11::error_already_set` |
189
+ +--------------------------------------+--------------------------------------+
190
+
191
+ For example:
192
+
193
+ .. code-block:: cpp
194
+
195
+ try {
196
+ // open("missing.txt", "r")
197
+ auto file = py::module_::import("io").attr("open")("missing.txt", "r");
198
+ auto text = file.attr("read")();
199
+ file.attr("close")();
200
+ } catch (py::error_already_set &e) {
201
+ if (e.matches(PyExc_FileNotFoundError)) {
202
+ py::print("missing.txt not found");
203
+ } else if (e.matches(PyExc_PermissionError)) {
204
+ py::print("missing.txt found but not accessible");
205
+ } else {
206
+ throw;
207
+ }
208
+ }
209
+
210
+ Note that C++ to Python exception translation does not apply here, since that is
211
+ a method for translating C++ exceptions to Python, not vice versa. The error raised
212
+ from Python is always ``error_already_set``.
213
+
214
+ This example illustrates this behavior:
215
+
216
+ .. code-block:: cpp
217
+
218
+ try {
219
+ py::eval("raise ValueError('The Ring')");
220
+ } catch (py::value_error &boromir) {
221
+ // Boromir never gets the ring
222
+ assert(false);
223
+ } catch (py::error_already_set &frodo) {
224
+ // Frodo gets the ring
225
+ py::print("I will take the ring");
226
+ }
227
+
228
+ try {
229
+ // py::value_error is a request for pybind11 to raise a Python exception
230
+ throw py::value_error("The ball");
231
+ } catch (py::error_already_set &cat) {
232
+ // cat won't catch the ball since
233
+ // py::value_error is not a Python exception
234
+ assert(false);
235
+ } catch (py::value_error &dog) {
236
+ // dog will catch the ball
237
+ py::print("Run Spot run");
238
+ throw; // Throw it again (pybind11 will raise ValueError)
239
+ }
240
+
241
+ Handling errors from the Python C API
242
+ =====================================
243
+
244
+ Where possible, use :ref:`pybind11 wrappers <wrappers>` instead of calling
245
+ the Python C API directly. When calling the Python C API directly, in
246
+ addition to manually managing reference counts, one must follow the pybind11
247
+ error protocol, which is outlined here.
248
+
249
+ After calling the Python C API, if Python returns an error,
250
+ ``throw py::error_already_set();``, which allows pybind11 to deal with the
251
+ exception and pass it back to the Python interpreter. This includes calls to
252
+ the error setting functions such as ``PyErr_SetString``.
253
+
254
+ .. code-block:: cpp
255
+
256
+ PyErr_SetString(PyExc_TypeError, "C API type error demo");
257
+ throw py::error_already_set();
258
+
259
+ // But it would be easier to simply...
260
+ throw py::type_error("pybind11 wrapper type error");
261
+
262
+ Alternately, to ignore the error, call `PyErr_Clear
263
+ <https://docs.python.org/3/c-api/exceptions.html#c.PyErr_Clear>`_.
264
+
265
+ Any Python error must be thrown or cleared, or Python/pybind11 will be left in
266
+ an invalid state.
267
+
268
+ .. _unraisable_exceptions:
269
+
270
+ Handling unraisable exceptions
271
+ ==============================
272
+
273
+ If a Python function invoked from a C++ destructor or any function marked
274
+ ``noexcept(true)`` (collectively, "noexcept functions") throws an exception, there
275
+ is no way to propagate the exception, as such functions may not throw.
276
+ Should they throw or fail to catch any exceptions in their call graph,
277
+ the C++ runtime calls ``std::terminate()`` to abort immediately.
278
+
279
+ Similarly, Python exceptions raised in a class's ``__del__`` method do not
280
+ propagate, but are logged by Python as an unraisable error. In Python 3.8+, a
281
+ `system hook is triggered
282
+ <https://docs.python.org/3/library/sys.html#sys.unraisablehook>`_
283
+ and an auditing event is logged.
284
+
285
+ Any noexcept function should have a try-catch block that traps
286
+ class:`error_already_set` (or any other exception that can occur). Note that
287
+ pybind11 wrappers around Python exceptions such as
288
+ :class:`pybind11::value_error` are *not* Python exceptions; they are C++
289
+ exceptions that pybind11 catches and converts to Python exceptions. Noexcept
290
+ functions cannot propagate these exceptions either. A useful approach is to
291
+ convert them to Python exceptions and then ``discard_as_unraisable`` as shown
292
+ below.
293
+
294
+ .. code-block:: cpp
295
+
296
+ void nonthrowing_func() noexcept(true) {
297
+ try {
298
+ // ...
299
+ } catch (py::error_already_set &eas) {
300
+ // Discard the Python error using Python APIs, using the C++ magic
301
+ // variable __func__. Python already knows the type and value and of the
302
+ // exception object.
303
+ eas.discard_as_unraisable(__func__);
304
+ } catch (const std::exception &e) {
305
+ // Log and discard C++ exceptions.
306
+ third_party::log(e);
307
+ }
308
+ }
309
+
310
+ .. versionadded:: 2.6
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/functions.rst ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 as long as the ``py::args`` and ``py::kwargs`` arguments are the last
310
+ arguments accepted by the function.
311
+
312
+ Please refer to the other examples for details on how to iterate over these,
313
+ and on how to cast their entries into C++ objects. A demonstration is also
314
+ available in ``tests/test_kwargs_and_defaults.cpp``.
315
+
316
+ .. note::
317
+
318
+ When combining \*args or \*\*kwargs with :ref:`keyword_args` you should
319
+ *not* include ``py::arg`` tags for the ``py::args`` and ``py::kwargs``
320
+ arguments.
321
+
322
+ Default arguments revisited
323
+ ===========================
324
+
325
+ The section on :ref:`default_args` previously discussed basic usage of default
326
+ arguments using pybind11. One noteworthy aspect of their implementation is that
327
+ default arguments are converted to Python objects right at declaration time.
328
+ Consider the following example:
329
+
330
+ .. code-block:: cpp
331
+
332
+ py::class_<MyClass>("MyClass")
333
+ .def("myFunction", py::arg("arg") = SomeType(123));
334
+
335
+ In this case, pybind11 must already be set up to deal with values of the type
336
+ ``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an
337
+ exception will be thrown.
338
+
339
+ Another aspect worth highlighting is that the "preview" of the default argument
340
+ in the function signature is generated using the object's ``__repr__`` method.
341
+ If not available, the signature may not be very helpful, e.g.:
342
+
343
+ .. code-block:: pycon
344
+
345
+ FUNCTIONS
346
+ ...
347
+ | myFunction(...)
348
+ | Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType
349
+ ...
350
+
351
+ The first way of addressing this is by defining ``SomeType.__repr__``.
352
+ Alternatively, it is possible to specify the human-readable preview of the
353
+ default argument manually using the ``arg_v`` notation:
354
+
355
+ .. code-block:: cpp
356
+
357
+ py::class_<MyClass>("MyClass")
358
+ .def("myFunction", py::arg_v("arg", SomeType(123), "SomeType(123)"));
359
+
360
+ Sometimes it may be necessary to pass a null pointer value as a default
361
+ argument. In this case, remember to cast it to the underlying type in question,
362
+ like so:
363
+
364
+ .. code-block:: cpp
365
+
366
+ py::class_<MyClass>("MyClass")
367
+ .def("myFunction", py::arg("arg") = static_cast<SomeType *>(nullptr));
368
+
369
+ Keyword-only arguments
370
+ ======================
371
+
372
+ Python 3 introduced keyword-only arguments by specifying an unnamed ``*``
373
+ argument in a function definition:
374
+
375
+ .. code-block:: python
376
+
377
+ def f(a, *, b): # a can be positional or via keyword; b must be via keyword
378
+ pass
379
+
380
+ f(a=1, b=2) # good
381
+ f(b=2, a=1) # good
382
+ f(1, b=2) # good
383
+ f(1, 2) # TypeError: f() takes 1 positional argument but 2 were given
384
+
385
+ Pybind11 provides a ``py::kw_only`` object that allows you to implement
386
+ the same behaviour by specifying the object between positional and keyword-only
387
+ argument annotations when registering the function:
388
+
389
+ .. code-block:: cpp
390
+
391
+ m.def("f", [](int a, int b) { /* ... */ },
392
+ py::arg("a"), py::kw_only(), py::arg("b"));
393
+
394
+ Note that you currently cannot combine this with a ``py::args`` argument. This
395
+ feature does *not* require Python 3 to work.
396
+
397
+ .. versionadded:: 2.6
398
+
399
+ Positional-only arguments
400
+ =========================
401
+
402
+ Python 3.8 introduced a new positional-only argument syntax, using ``/`` in the
403
+ function definition (note that this has been a convention for CPython
404
+ positional arguments, such as in ``pow()``, since Python 2). You can
405
+ do the same thing in any version of Python using ``py::pos_only()``:
406
+
407
+ .. code-block:: cpp
408
+
409
+ m.def("f", [](int a, int b) { /* ... */ },
410
+ py::arg("a"), py::pos_only(), py::arg("b"));
411
+
412
+ You now cannot give argument ``a`` by keyword. This can be combined with
413
+ keyword-only arguments, as well.
414
+
415
+ .. versionadded:: 2.6
416
+
417
+ .. _nonconverting_arguments:
418
+
419
+ Non-converting arguments
420
+ ========================
421
+
422
+ Certain argument types may support conversion from one type to another. Some
423
+ examples of conversions are:
424
+
425
+ * :ref:`implicit_conversions` declared using ``py::implicitly_convertible<A,B>()``
426
+ * Calling a method accepting a double with an integer argument
427
+ * Calling a ``std::complex<float>`` argument with a non-complex python type
428
+ (for example, with a float). (Requires the optional ``pybind11/complex.h``
429
+ header).
430
+ * Calling a function taking an Eigen matrix reference with a numpy array of the
431
+ wrong type or of an incompatible data layout. (Requires the optional
432
+ ``pybind11/eigen.h`` header).
433
+
434
+ This behaviour is sometimes undesirable: the binding code may prefer to raise
435
+ an error rather than convert the argument. This behaviour can be obtained
436
+ through ``py::arg`` by calling the ``.noconvert()`` method of the ``py::arg``
437
+ object, such as:
438
+
439
+ .. code-block:: cpp
440
+
441
+ m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert());
442
+ m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f"));
443
+
444
+ Attempting the call the second function (the one without ``.noconvert()``) with
445
+ an integer will succeed, but attempting to call the ``.noconvert()`` version
446
+ will fail with a ``TypeError``:
447
+
448
+ .. code-block:: pycon
449
+
450
+ >>> floats_preferred(4)
451
+ 2.0
452
+ >>> floats_only(4)
453
+ Traceback (most recent call last):
454
+ File "<stdin>", line 1, in <module>
455
+ TypeError: floats_only(): incompatible function arguments. The following argument types are supported:
456
+ 1. (f: float) -> float
457
+
458
+ Invoked with: 4
459
+
460
+ You may, of course, combine this with the :var:`_a` shorthand notation (see
461
+ :ref:`keyword_args`) and/or :ref:`default_args`. It is also permitted to omit
462
+ the argument name by using the ``py::arg()`` constructor without an argument
463
+ name, i.e. by specifying ``py::arg().noconvert()``.
464
+
465
+ .. note::
466
+
467
+ When specifying ``py::arg`` options it is necessary to provide the same
468
+ number of options as the bound function has arguments. Thus if you want to
469
+ enable no-convert behaviour for just one of several arguments, you will
470
+ need to specify a ``py::arg()`` annotation for each argument with the
471
+ no-convert argument modified to ``py::arg().noconvert()``.
472
+
473
+ .. _none_arguments:
474
+
475
+ Allow/Prohibiting None arguments
476
+ ================================
477
+
478
+ When a C++ type registered with :class:`py::class_` is passed as an argument to
479
+ a function taking the instance as pointer or shared holder (e.g. ``shared_ptr``
480
+ or a custom, copyable holder as described in :ref:`smart_pointers`), pybind
481
+ allows ``None`` to be passed from Python which results in calling the C++
482
+ function with ``nullptr`` (or an empty holder) for the argument.
483
+
484
+ To explicitly enable or disable this behaviour, using the
485
+ ``.none`` method of the :class:`py::arg` object:
486
+
487
+ .. code-block:: cpp
488
+
489
+ py::class_<Dog>(m, "Dog").def(py::init<>());
490
+ py::class_<Cat>(m, "Cat").def(py::init<>());
491
+ m.def("bark", [](Dog *dog) -> std::string {
492
+ if (dog) return "woof!"; /* Called with a Dog instance */
493
+ else return "(no dog)"; /* Called with None, dog == nullptr */
494
+ }, py::arg("dog").none(true));
495
+ m.def("meow", [](Cat *cat) -> std::string {
496
+ // Can't be called with None argument
497
+ return "meow";
498
+ }, py::arg("cat").none(false));
499
+
500
+ With the above, the Python call ``bark(None)`` will return the string ``"(no
501
+ dog)"``, while attempting to call ``meow(None)`` will raise a ``TypeError``:
502
+
503
+ .. code-block:: pycon
504
+
505
+ >>> from animals import Dog, Cat, bark, meow
506
+ >>> bark(Dog())
507
+ 'woof!'
508
+ >>> meow(Cat())
509
+ 'meow'
510
+ >>> bark(None)
511
+ '(no dog)'
512
+ >>> meow(None)
513
+ Traceback (most recent call last):
514
+ File "<stdin>", line 1, in <module>
515
+ TypeError: meow(): incompatible function arguments. The following argument types are supported:
516
+ 1. (cat: animals.Cat) -> str
517
+
518
+ Invoked with: None
519
+
520
+ The default behaviour when the tag is unspecified is to allow ``None``.
521
+
522
+ .. note::
523
+
524
+ Even when ``.none(true)`` is specified for an argument, ``None`` will be converted to a
525
+ ``nullptr`` *only* for custom and :ref:`opaque <opaque>` types. Pointers to built-in types
526
+ (``double *``, ``int *``, ...) and STL types (``std::vector<T> *``, ...; if ``pybind11/stl.h``
527
+ is included) are copied when converted to C++ (see :doc:`/advanced/cast/overview`) and will
528
+ not allow ``None`` as argument. To pass optional argument of these copied types consider
529
+ using ``std::optional<T>``
530
+
531
+ .. _overload_resolution:
532
+
533
+ Overload resolution order
534
+ =========================
535
+
536
+ When a function or method with multiple overloads is called from Python,
537
+ pybind11 determines which overload to call in two passes. The first pass
538
+ attempts to call each overload without allowing argument conversion (as if
539
+ every argument had been specified as ``py::arg().noconvert()`` as described
540
+ above).
541
+
542
+ If no overload succeeds in the no-conversion first pass, a second pass is
543
+ attempted in which argument conversion is allowed (except where prohibited via
544
+ an explicit ``py::arg().noconvert()`` attribute in the function definition).
545
+
546
+ If the second pass also fails a ``TypeError`` is raised.
547
+
548
+ Within each pass, overloads are tried in the order they were registered with
549
+ pybind11. If the ``py::prepend()`` tag is added to the definition, a function
550
+ can be placed at the beginning of the overload sequence instead, allowing user
551
+ overloads to proceed built in functions.
552
+
553
+ What this means in practice is that pybind11 will prefer any overload that does
554
+ not require conversion of arguments to an overload that does, but otherwise
555
+ prefers earlier-defined overloads to later-defined ones.
556
+
557
+ .. note::
558
+
559
+ pybind11 does *not* further prioritize based on the number/pattern of
560
+ overloaded arguments. That is, pybind11 does not prioritize a function
561
+ requiring one conversion over one requiring three, but only prioritizes
562
+ overloads requiring no conversion at all to overloads that require
563
+ conversion of at least one argument.
564
+
565
+ .. versionadded:: 2.6
566
+
567
+ The ``py::prepend()`` tag.
third-party/DPVO/Pangolin/components/pango_python/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/Pangolin/components/pango_python/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/Pangolin/components/pango_python/pybind11/docs/advanced/pycpp/numpy.rst ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sanity 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
+ Structured types
175
+ ================
176
+
177
+ In order for ``py::array_t`` to work with structured (record) types, we first
178
+ need to register the memory layout of the type. This can be done via
179
+ ``PYBIND11_NUMPY_DTYPE`` macro, called in the plugin definition code, which
180
+ expects the type followed by field names:
181
+
182
+ .. code-block:: cpp
183
+
184
+ struct A {
185
+ int x;
186
+ double y;
187
+ };
188
+
189
+ struct B {
190
+ int z;
191
+ A a;
192
+ };
193
+
194
+ // ...
195
+ PYBIND11_MODULE(test, m) {
196
+ // ...
197
+
198
+ PYBIND11_NUMPY_DTYPE(A, x, y);
199
+ PYBIND11_NUMPY_DTYPE(B, z, a);
200
+ /* now both A and B can be used as template arguments to py::array_t */
201
+ }
202
+
203
+ The structure should consist of fundamental arithmetic types, ``std::complex``,
204
+ previously registered substructures, and arrays of any of the above. Both C++
205
+ arrays and ``std::array`` are supported. While there is a static assertion to
206
+ prevent many types of unsupported structures, it is still the user's
207
+ responsibility to use only "plain" structures that can be safely manipulated as
208
+ raw memory without violating invariants.
209
+
210
+ Vectorizing functions
211
+ =====================
212
+
213
+ Suppose we want to bind a function with the following signature to Python so
214
+ that it can process arbitrary NumPy array arguments (vectors, matrices, general
215
+ N-D arrays) in addition to its normal arguments:
216
+
217
+ .. code-block:: cpp
218
+
219
+ double my_func(int x, float y, double z);
220
+
221
+ After including the ``pybind11/numpy.h`` header, this is extremely simple:
222
+
223
+ .. code-block:: cpp
224
+
225
+ m.def("vectorized_func", py::vectorize(my_func));
226
+
227
+ Invoking the function like below causes 4 calls to be made to ``my_func`` with
228
+ each of the array elements. The significant advantage of this compared to
229
+ solutions like ``numpy.vectorize()`` is that the loop over the elements runs
230
+ entirely on the C++ side and can be crunched down into a tight, optimized loop
231
+ by the compiler. The result is returned as a NumPy array of type
232
+ ``numpy.dtype.float64``.
233
+
234
+ .. code-block:: pycon
235
+
236
+ >>> x = np.array([[1, 3],[5, 7]])
237
+ >>> y = np.array([[2, 4],[6, 8]])
238
+ >>> z = 3
239
+ >>> result = vectorized_func(x, y, z)
240
+
241
+ The scalar argument ``z`` is transparently replicated 4 times. The input
242
+ arrays ``x`` and ``y`` are automatically converted into the right types (they
243
+ are of type ``numpy.dtype.int64`` but need to be ``numpy.dtype.int32`` and
244
+ ``numpy.dtype.float32``, respectively).
245
+
246
+ .. note::
247
+
248
+ Only arithmetic, complex, and POD types passed by value or by ``const &``
249
+ reference are vectorized; all other arguments are passed through as-is.
250
+ Functions taking rvalue reference arguments cannot be vectorized.
251
+
252
+ In cases where the computation is too complicated to be reduced to
253
+ ``vectorize``, it will be necessary to create and access the buffer contents
254
+ manually. The following snippet contains a complete example that shows how this
255
+ works (the code is somewhat contrived, since it could have been done more
256
+ simply using ``vectorize``).
257
+
258
+ .. code-block:: cpp
259
+
260
+ #include <pybind11/pybind11.h>
261
+ #include <pybind11/numpy.h>
262
+
263
+ namespace py = pybind11;
264
+
265
+ py::array_t<double> add_arrays(py::array_t<double> input1, py::array_t<double> input2) {
266
+ py::buffer_info buf1 = input1.request(), buf2 = input2.request();
267
+
268
+ if (buf1.ndim != 1 || buf2.ndim != 1)
269
+ throw std::runtime_error("Number of dimensions must be one");
270
+
271
+ if (buf1.size != buf2.size)
272
+ throw std::runtime_error("Input shapes must match");
273
+
274
+ /* No pointer is passed, so NumPy will allocate the buffer */
275
+ auto result = py::array_t<double>(buf1.size);
276
+
277
+ py::buffer_info buf3 = result.request();
278
+
279
+ double *ptr1 = static_cast<double *>(buf1.ptr);
280
+ double *ptr2 = static_cast<double *>(buf2.ptr);
281
+ double *ptr3 = static_cast<double *>(buf3.ptr);
282
+
283
+ for (size_t idx = 0; idx < buf1.shape[0]; idx++)
284
+ ptr3[idx] = ptr1[idx] + ptr2[idx];
285
+
286
+ return result;
287
+ }
288
+
289
+ PYBIND11_MODULE(test, m) {
290
+ m.def("add_arrays", &add_arrays, "Add two NumPy arrays");
291
+ }
292
+
293
+ .. seealso::
294
+
295
+ The file :file:`tests/test_numpy_vectorize.cpp` contains a complete
296
+ example that demonstrates using :func:`vectorize` in more detail.
297
+
298
+ Direct access
299
+ =============
300
+
301
+ For performance reasons, particularly when dealing with very large arrays, it
302
+ is often desirable to directly access array elements without internal checking
303
+ of dimensions and bounds on every access when indices are known to be already
304
+ valid. To avoid such checks, the ``array`` class and ``array_t<T>`` template
305
+ class offer an unchecked proxy object that can be used for this unchecked
306
+ access through the ``unchecked<N>`` and ``mutable_unchecked<N>`` methods,
307
+ where ``N`` gives the required dimensionality of the array:
308
+
309
+ .. code-block:: cpp
310
+
311
+ m.def("sum_3d", [](py::array_t<double> x) {
312
+ auto r = x.unchecked<3>(); // x must have ndim = 3; can be non-writeable
313
+ double sum = 0;
314
+ for (py::ssize_t i = 0; i < r.shape(0); i++)
315
+ for (py::ssize_t j = 0; j < r.shape(1); j++)
316
+ for (py::ssize_t k = 0; k < r.shape(2); k++)
317
+ sum += r(i, j, k);
318
+ return sum;
319
+ });
320
+ m.def("increment_3d", [](py::array_t<double> x) {
321
+ auto r = x.mutable_unchecked<3>(); // Will throw if ndim != 3 or flags.writeable is false
322
+ for (py::ssize_t i = 0; i < r.shape(0); i++)
323
+ for (py::ssize_t j = 0; j < r.shape(1); j++)
324
+ for (py::ssize_t k = 0; k < r.shape(2); k++)
325
+ r(i, j, k) += 1.0;
326
+ }, py::arg().noconvert());
327
+
328
+ To obtain the proxy from an ``array`` object, you must specify both the data
329
+ type and number of dimensions as template arguments, such as ``auto r =
330
+ myarray.mutable_unchecked<float, 2>()``.
331
+
332
+ If the number of dimensions is not known at compile time, you can omit the
333
+ dimensions template parameter (i.e. calling ``arr_t.unchecked()`` or
334
+ ``arr.unchecked<T>()``. This will give you a proxy object that works in the
335
+ same way, but results in less optimizable code and thus a small efficiency
336
+ loss in tight loops.
337
+
338
+ Note that the returned proxy object directly references the array's data, and
339
+ only reads its shape, strides, and writeable flag when constructed. You must
340
+ take care to ensure that the referenced array is not destroyed or reshaped for
341
+ the duration of the returned object, typically by limiting the scope of the
342
+ returned instance.
343
+
344
+ The returned proxy object supports some of the same methods as ``py::array`` so
345
+ that it can be used as a drop-in replacement for some existing, index-checked
346
+ uses of ``py::array``:
347
+
348
+ - ``r.ndim()`` returns the number of dimensions
349
+
350
+ - ``r.data(1, 2, ...)`` and ``r.mutable_data(1, 2, ...)``` returns a pointer to
351
+ the ``const T`` or ``T`` data, respectively, at the given indices. The
352
+ latter is only available to proxies obtained via ``a.mutable_unchecked()``.
353
+
354
+ - ``itemsize()`` returns the size of an item in bytes, i.e. ``sizeof(T)``.
355
+
356
+ - ``ndim()`` returns the number of dimensions.
357
+
358
+ - ``shape(n)`` returns the size of dimension ``n``
359
+
360
+ - ``size()`` returns the total number of elements (i.e. the product of the shapes).
361
+
362
+ - ``nbytes()`` returns the number of bytes used by the referenced elements
363
+ (i.e. ``itemsize()`` times ``size()``).
364
+
365
+ .. seealso::
366
+
367
+ The file :file:`tests/test_numpy_array.cpp` contains additional examples
368
+ demonstrating the use of this feature.
369
+
370
+ Ellipsis
371
+ ========
372
+
373
+ Python 3 provides a convenient ``...`` ellipsis notation that is often used to
374
+ slice multidimensional arrays. For instance, the following snippet extracts the
375
+ middle dimensions of a tensor with the first and last index set to zero.
376
+ In Python 2, the syntactic sugar ``...`` is not available, but the singleton
377
+ ``Ellipsis`` (of type ``ellipsis``) can still be used directly.
378
+
379
+ .. code-block:: python
380
+
381
+ a = # a NumPy array
382
+ b = a[0, ..., 0]
383
+
384
+ The function ``py::ellipsis()`` function can be used to perform the same
385
+ operation on the C++ side:
386
+
387
+ .. code-block:: cpp
388
+
389
+ py::array a = /* A NumPy array */;
390
+ py::array b = a[py::make_tuple(0, py::ellipsis(), 0)];
391
+
392
+ .. versionchanged:: 2.6
393
+ ``py::ellipsis()`` is now also available in Python 2.
394
+
395
+ Memory view
396
+ ===========
397
+
398
+ For a case when we simply want to provide a direct accessor to C/C++ buffer
399
+ without a concrete class object, we can return a ``memoryview`` object. Suppose
400
+ we wish to expose a ``memoryview`` for 2x4 uint8_t array, we can do the
401
+ following:
402
+
403
+ .. code-block:: cpp
404
+
405
+ const uint8_t buffer[] = {
406
+ 0, 1, 2, 3,
407
+ 4, 5, 6, 7
408
+ };
409
+ m.def("get_memoryview2d", []() {
410
+ return py::memoryview::from_buffer(
411
+ buffer, // buffer pointer
412
+ { 2, 4 }, // shape (rows, cols)
413
+ { sizeof(uint8_t) * 4, sizeof(uint8_t) } // strides in bytes
414
+ );
415
+ })
416
+
417
+ This approach is meant for providing a ``memoryview`` for a C/C++ buffer not
418
+ managed by Python. The user is responsible for managing the lifetime of the
419
+ buffer. Using a ``memoryview`` created in this way after deleting the buffer in
420
+ C++ side results in undefined behavior.
421
+
422
+ We can also use ``memoryview::from_memory`` for a simple 1D contiguous buffer:
423
+
424
+ .. code-block:: cpp
425
+
426
+ m.def("get_memoryview1d", []() {
427
+ return py::memoryview::from_memory(
428
+ buffer, // buffer pointer
429
+ sizeof(uint8_t) * 8 // buffer size
430
+ );
431
+ })
432
+
433
+ .. note::
434
+
435
+ ``memoryview::from_memory`` is not available in Python 2.
436
+
437
+ .. versionchanged:: 2.6
438
+ ``memoryview::from_memory`` added.
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/advanced/pycpp/object.rst ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ .. _casting_back_and_forth:
24
+
25
+ Casting back and forth
26
+ ======================
27
+
28
+ In this kind of mixed code, it is often necessary to convert arbitrary C++
29
+ types to Python, which can be done using :func:`py::cast`:
30
+
31
+ .. code-block:: cpp
32
+
33
+ MyClass *cls = ..;
34
+ py::object obj = py::cast(cls);
35
+
36
+ The reverse direction uses the following syntax:
37
+
38
+ .. code-block:: cpp
39
+
40
+ py::object obj = ...;
41
+ MyClass *cls = obj.cast<MyClass *>();
42
+
43
+ When conversion fails, both directions throw the exception :class:`cast_error`.
44
+
45
+ .. _python_libs:
46
+
47
+ Accessing Python libraries from C++
48
+ ===================================
49
+
50
+ It is also possible to import objects defined in the Python standard
51
+ library or available in the current Python environment (``sys.path``) and work
52
+ with these in C++.
53
+
54
+ This example obtains a reference to the Python ``Decimal`` class.
55
+
56
+ .. code-block:: cpp
57
+
58
+ // Equivalent to "from decimal import Decimal"
59
+ py::object Decimal = py::module_::import("decimal").attr("Decimal");
60
+
61
+ .. code-block:: cpp
62
+
63
+ // Try to import scipy
64
+ py::object scipy = py::module_::import("scipy");
65
+ return scipy.attr("__version__");
66
+
67
+
68
+ .. _calling_python_functions:
69
+
70
+ Calling Python functions
71
+ ========================
72
+
73
+ It is also possible to call Python classes, functions and methods
74
+ via ``operator()``.
75
+
76
+ .. code-block:: cpp
77
+
78
+ // Construct a Python object of class Decimal
79
+ py::object pi = Decimal("3.14159");
80
+
81
+ .. code-block:: cpp
82
+
83
+ // Use Python to make our directories
84
+ py::object os = py::module_::import("os");
85
+ py::object makedirs = os.attr("makedirs");
86
+ makedirs("/tmp/path/to/somewhere");
87
+
88
+ One can convert the result obtained from Python to a pure C++ version
89
+ if a ``py::class_`` or type conversion is defined.
90
+
91
+ .. code-block:: cpp
92
+
93
+ py::function f = <...>;
94
+ py::object result_py = f(1234, "hello", some_instance);
95
+ MyClass &result = result_py.cast<MyClass>();
96
+
97
+ .. _calling_python_methods:
98
+
99
+ Calling Python methods
100
+ ========================
101
+
102
+ To call an object's method, one can again use ``.attr`` to obtain access to the
103
+ Python method.
104
+
105
+ .. code-block:: cpp
106
+
107
+ // Calculate e^π in decimal
108
+ py::object exp_pi = pi.attr("exp")();
109
+ py::print(py::str(exp_pi));
110
+
111
+ In the example above ``pi.attr("exp")`` is a *bound method*: it will always call
112
+ the method for that same instance of the class. Alternately one can create an
113
+ *unbound method* via the Python class (instead of instance) and pass the ``self``
114
+ object explicitly, followed by other arguments.
115
+
116
+ .. code-block:: cpp
117
+
118
+ py::object decimal_exp = Decimal.attr("exp");
119
+
120
+ // Compute the e^n for n=0..4
121
+ for (int n = 0; n < 5; n++) {
122
+ py::print(decimal_exp(Decimal(n));
123
+ }
124
+
125
+ Keyword arguments
126
+ =================
127
+
128
+ Keyword arguments are also supported. In Python, there is the usual call syntax:
129
+
130
+ .. code-block:: python
131
+
132
+ def f(number, say, to):
133
+ ... # function code
134
+
135
+ f(1234, say="hello", to=some_instance) # keyword call in Python
136
+
137
+ In C++, the same call can be made using:
138
+
139
+ .. code-block:: cpp
140
+
141
+ using namespace pybind11::literals; // to bring in the `_a` literal
142
+ f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
143
+
144
+ Unpacking arguments
145
+ ===================
146
+
147
+ Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with
148
+ other arguments:
149
+
150
+ .. code-block:: cpp
151
+
152
+ // * unpacking
153
+ py::tuple args = py::make_tuple(1234, "hello", some_instance);
154
+ f(*args);
155
+
156
+ // ** unpacking
157
+ py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance);
158
+ f(**kwargs);
159
+
160
+ // mixed keywords, * and ** unpacking
161
+ py::tuple args = py::make_tuple(1234);
162
+ py::dict kwargs = py::dict("to"_a=some_instance);
163
+ f(*args, "say"_a="hello", **kwargs);
164
+
165
+ Generalized unpacking according to PEP448_ is also supported:
166
+
167
+ .. code-block:: cpp
168
+
169
+ py::dict kwargs1 = py::dict("number"_a=1234);
170
+ py::dict kwargs2 = py::dict("to"_a=some_instance);
171
+ f(**kwargs1, "say"_a="hello", **kwargs2);
172
+
173
+ .. seealso::
174
+
175
+ The file :file:`tests/test_pytypes.cpp` contains a complete
176
+ example that demonstrates passing native Python types in more detail. The
177
+ file :file:`tests/test_callbacks.cpp` presents a few examples of calling
178
+ Python functions from C++, including keywords arguments and unpacking.
179
+
180
+ .. _PEP448: https://www.python.org/dev/peps/pep-0448/
181
+
182
+ .. _implicit_casting:
183
+
184
+ Implicit casting
185
+ ================
186
+
187
+ When using the C++ interface for Python types, or calling Python functions,
188
+ objects of type :class:`object` are returned. It is possible to invoke implicit
189
+ conversions to subclasses like :class:`dict`. The same holds for the proxy objects
190
+ returned by ``operator[]`` or ``obj.attr()``.
191
+ Casting to subtypes improves code readability and allows values to be passed to
192
+ C++ functions that require a specific subtype rather than a generic :class:`object`.
193
+
194
+ .. code-block:: cpp
195
+
196
+ #include <pybind11/numpy.h>
197
+ using namespace pybind11::literals;
198
+
199
+ py::module_ os = py::module_::import("os");
200
+ py::module_ path = py::module_::import("os.path"); // like 'import os.path as path'
201
+ py::module_ np = py::module_::import("numpy"); // like 'import numpy as np'
202
+
203
+ py::str curdir_abs = path.attr("abspath")(path.attr("curdir"));
204
+ py::print(py::str("Current directory: ") + curdir_abs);
205
+ py::dict environ = os.attr("environ");
206
+ py::print(environ["HOME"]);
207
+ py::array_t<float> arr = np.attr("ones")(3, "dtype"_a="float32");
208
+ py::print(py::repr(arr + py::int_(1)));
209
+
210
+ These implicit conversions are available for subclasses of :class:`object`; there
211
+ is no need to call ``obj.cast()`` explicitly as for custom classes, see
212
+ :ref:`casting_back_and_forth`.
213
+
214
+ .. note::
215
+ If a trivial conversion via move constructor is not possible, both implicit and
216
+ explicit casting (calling ``obj.cast()``) will attempt a "rich" conversion.
217
+ For instance, ``py::list env = os.attr("environ");`` will succeed and is
218
+ equivalent to the Python code ``env = list(os.environ)`` that produces a
219
+ list of the dict keys.
220
+
221
+ .. TODO: Adapt text once PR #2349 has landed
222
+
223
+ Handling exceptions
224
+ ===================
225
+
226
+ Python exceptions from wrapper classes will be thrown as a ``py::error_already_set``.
227
+ See :ref:`Handling exceptions from Python in C++
228
+ <handling_python_exceptions_cpp>` for more information on handling exceptions
229
+ raised when calling C++ wrapper classes.
230
+
231
+ .. _pytypes_gotchas:
232
+
233
+ Gotchas
234
+ =======
235
+
236
+ Default-Constructed Wrappers
237
+ ----------------------------
238
+
239
+ 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
240
+ ``PyObject*`` null pointer. To check for this, use
241
+ ``static_cast<bool>(my_wrapper)``.
242
+
243
+ Assigning py::none() to wrappers
244
+ --------------------------------
245
+
246
+ You may be tempted to use types like ``py::str`` and ``py::dict`` in C++
247
+ signatures (either pure C++, or in bound signatures), and assign them default
248
+ values of ``py::none()``. However, in a best case scenario, it will fail fast
249
+ because ``None`` is not convertible to that type (e.g. ``py::dict``), or in a
250
+ worse case scenario, it will silently work but corrupt the types you want to
251
+ work with (e.g. ``py::str(py::none())`` will yield ``"None"`` in Python).
third-party/DPVO/Pangolin/components/pango_python/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:: py
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/Pangolin/components/pango_python/pybind11/docs/advanced/smart_ptrs.rst ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ print(Parent().get_child())
81
+
82
+ The problem is that ``Parent::get_child()`` returns a pointer to an instance of
83
+ ``Child``, but the fact that this instance is already managed by
84
+ ``std::shared_ptr<...>`` is lost when passing raw pointers. In this case,
85
+ pybind11 will create a second independent ``std::shared_ptr<...>`` that also
86
+ claims ownership of the pointer. In the end, the object will be freed **twice**
87
+ since these shared pointers have no way of knowing about each other.
88
+
89
+ There are two ways to resolve this issue:
90
+
91
+ 1. For types that are managed by a smart pointer class, never use raw pointers
92
+ in function arguments or return values. In other words: always consistently
93
+ wrap pointers into their designated holder types (such as
94
+ ``std::shared_ptr<...>``). In this case, the signature of ``get_child()``
95
+ should be modified as follows:
96
+
97
+ .. code-block:: cpp
98
+
99
+ std::shared_ptr<Child> get_child() { return child; }
100
+
101
+ 2. Adjust the definition of ``Child`` by specifying
102
+ ``std::enable_shared_from_this<T>`` (see cppreference_ for details) as a
103
+ base class. This adds a small bit of information to ``Child`` that allows
104
+ pybind11 to realize that there is already an existing
105
+ ``std::shared_ptr<...>`` and communicate with it. In this case, the
106
+ declaration of ``Child`` should look as follows:
107
+
108
+ .. _cppreference: http://en.cppreference.com/w/cpp/memory/enable_shared_from_this
109
+
110
+ .. code-block:: cpp
111
+
112
+ class Child : public std::enable_shared_from_this<Child> { };
113
+
114
+ .. _smart_pointers:
115
+
116
+ Custom smart pointers
117
+ =====================
118
+
119
+ pybind11 supports ``std::unique_ptr`` and ``std::shared_ptr`` right out of the
120
+ box. For any other custom smart pointer, transparent conversions can be enabled
121
+ using a macro invocation similar to the following. It must be declared at the
122
+ top namespace level before any binding code:
123
+
124
+ .. code-block:: cpp
125
+
126
+ PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>);
127
+
128
+ The first argument of :func:`PYBIND11_DECLARE_HOLDER_TYPE` should be a
129
+ placeholder name that is used as a template parameter of the second argument.
130
+ Thus, feel free to use any identifier, but use it consistently on both sides;
131
+ also, don't use the name of a type that already exists in your codebase.
132
+
133
+ The macro also accepts a third optional boolean parameter that is set to false
134
+ by default. Specify
135
+
136
+ .. code-block:: cpp
137
+
138
+ PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>, true);
139
+
140
+ if ``SmartPtr<T>`` can always be initialized from a ``T*`` pointer without the
141
+ risk of inconsistencies (such as multiple independent ``SmartPtr`` instances
142
+ believing that they are the sole owner of the ``T*`` pointer). A common
143
+ situation where ``true`` should be passed is when the ``T`` instances use
144
+ *intrusive* reference counting.
145
+
146
+ Please take a look at the :ref:`macro_notes` before using this feature.
147
+
148
+ By default, pybind11 assumes that your custom smart pointer has a standard
149
+ interface, i.e. provides a ``.get()`` member function to access the underlying
150
+ raw pointer. If this is not the case, pybind11's ``holder_helper`` must be
151
+ specialized:
152
+
153
+ .. code-block:: cpp
154
+
155
+ // Always needed for custom holder types
156
+ PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>);
157
+
158
+ // Only needed if the type's `.get()` goes by another name
159
+ namespace pybind11 { namespace detail {
160
+ template <typename T>
161
+ struct holder_helper<SmartPtr<T>> { // <-- specialization
162
+ static const T *get(const SmartPtr<T> &p) { return p.getPointer(); }
163
+ };
164
+ }}
165
+
166
+ The above specialization informs pybind11 that the custom ``SmartPtr`` class
167
+ provides ``.get()`` functionality via ``.getPointer()``.
168
+
169
+ .. seealso::
170
+
171
+ The file :file:`tests/test_smart_ptr.cpp` contains a complete example
172
+ that demonstrates how to work with custom reference-counting holder types
173
+ in more detail.
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/basics.rst ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _basics:
2
+
3
+ First steps
4
+ ###########
5
+
6
+ This sections demonstrates the basic features of pybind11. Before getting
7
+ started, make sure that development environment is set up to compile the
8
+ included set of test cases.
9
+
10
+
11
+ Compiling the test cases
12
+ ========================
13
+
14
+ Linux/macOS
15
+ -----------
16
+
17
+ On Linux you'll need to install the **python-dev** or **python3-dev** packages as
18
+ well as **cmake**. On macOS, the included python version works out of the box,
19
+ but **cmake** must still be installed.
20
+
21
+ After installing the prerequisites, run
22
+
23
+ .. code-block:: bash
24
+
25
+ mkdir build
26
+ cd build
27
+ cmake ..
28
+ make check -j 4
29
+
30
+ The last line will both compile and run the tests.
31
+
32
+ Windows
33
+ -------
34
+
35
+ On Windows, only **Visual Studio 2015** and newer are supported since pybind11 relies
36
+ on various C++11 language features that break older versions of Visual Studio.
37
+
38
+ .. Note::
39
+
40
+ To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag
41
+ ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When
42
+ building with Visual Studio 2019, this is not strictly necessary, but still advised.
43
+
44
+ .. _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017
45
+
46
+ To compile and run the tests:
47
+
48
+ .. code-block:: batch
49
+
50
+ mkdir build
51
+ cd build
52
+ cmake ..
53
+ cmake --build . --config Release --target check
54
+
55
+ This will create a Visual Studio project, compile and run the target, all from the
56
+ command line.
57
+
58
+ .. Note::
59
+
60
+ If all tests fail, make sure that the Python binary and the testcases are compiled
61
+ for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
62
+ can specify **x86_64** as the target architecture for the generated Visual Studio
63
+ project using ``cmake -A x64 ..``.
64
+
65
+ .. seealso::
66
+
67
+ Advanced users who are already familiar with Boost.Python may want to skip
68
+ the tutorial and look at the test cases in the :file:`tests` directory,
69
+ which exercise all features of pybind11.
70
+
71
+ Header and namespace conventions
72
+ ================================
73
+
74
+ For brevity, all code examples assume that the following two lines are present:
75
+
76
+ .. code-block:: cpp
77
+
78
+ #include <pybind11/pybind11.h>
79
+
80
+ namespace py = pybind11;
81
+
82
+ Some features may require additional headers, but those will be specified as needed.
83
+
84
+ .. _simple_example:
85
+
86
+ Creating bindings for a simple function
87
+ =======================================
88
+
89
+ Let's start by creating Python bindings for an extremely simple function, which
90
+ adds two numbers and returns their result:
91
+
92
+ .. code-block:: cpp
93
+
94
+ int add(int i, int j) {
95
+ return i + j;
96
+ }
97
+
98
+ For simplicity [#f1]_, we'll put both this function and the binding code into
99
+ a file named :file:`example.cpp` with the following contents:
100
+
101
+ .. code-block:: cpp
102
+
103
+ #include <pybind11/pybind11.h>
104
+
105
+ int add(int i, int j) {
106
+ return i + j;
107
+ }
108
+
109
+ PYBIND11_MODULE(example, m) {
110
+ m.doc() = "pybind11 example plugin"; // optional module docstring
111
+
112
+ m.def("add", &add, "A function which adds two numbers");
113
+ }
114
+
115
+ .. [#f1] In practice, implementation and binding code will generally be located
116
+ in separate files.
117
+
118
+ The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
119
+ ``import`` statement is issued from within Python. The module name (``example``)
120
+ is given as the first macro argument (it should not be in quotes). The second
121
+ argument (``m``) defines a variable of type :class:`py::module_ <module>` which
122
+ is the main interface for creating bindings. The method :func:`module_::def`
123
+ generates binding code that exposes the ``add()`` function to Python.
124
+
125
+ .. note::
126
+
127
+ Notice how little code was needed to expose our function to Python: all
128
+ details regarding the function's parameters and return value were
129
+ automatically inferred using template metaprogramming. This overall
130
+ approach and the used syntax are borrowed from Boost.Python, though the
131
+ underlying implementation is very different.
132
+
133
+ pybind11 is a header-only library, hence it is not necessary to link against
134
+ any special libraries and there are no intermediate (magic) translation steps.
135
+ On Linux, the above example can be compiled using the following command:
136
+
137
+ .. code-block:: bash
138
+
139
+ $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
140
+
141
+ .. note::
142
+
143
+ If you used :ref:`include_as_a_submodule` to get the pybind11 source, then
144
+ use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of
145
+ ``$(python3 -m pybind11 --includes)`` in the above compilation, as
146
+ explained in :ref:`building_manually`.
147
+
148
+ For more details on the required compiler flags on Linux and macOS, see
149
+ :ref:`building_manually`. For complete cross-platform compilation instructions,
150
+ refer to the :ref:`compiling` page.
151
+
152
+ The `python_example`_ and `cmake_example`_ repositories are also a good place
153
+ to start. They are both complete project examples with cross-platform build
154
+ systems. The only difference between the two is that `python_example`_ uses
155
+ Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
156
+ (which may be preferable for existing C++ projects).
157
+
158
+ .. _python_example: https://github.com/pybind/python_example
159
+ .. _cmake_example: https://github.com/pybind/cmake_example
160
+
161
+ Building the above C++ code will produce a binary module file that can be
162
+ imported to Python. Assuming that the compiled module is located in the
163
+ current directory, the following interactive Python session shows how to
164
+ load and execute the example:
165
+
166
+ .. code-block:: pycon
167
+
168
+ $ python
169
+ Python 2.7.10 (default, Aug 22 2015, 20:33:39)
170
+ [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
171
+ Type "help", "copyright", "credits" or "license" for more information.
172
+ >>> import example
173
+ >>> example.add(1, 2)
174
+ 3L
175
+ >>>
176
+
177
+ .. _keyword_args:
178
+
179
+ Keyword arguments
180
+ =================
181
+
182
+ With a simple code modification, it is possible to inform Python about the
183
+ names of the arguments ("i" and "j" in this case).
184
+
185
+ .. code-block:: cpp
186
+
187
+ m.def("add", &add, "A function which adds two numbers",
188
+ py::arg("i"), py::arg("j"));
189
+
190
+ :class:`arg` is one of several special tag classes which can be used to pass
191
+ metadata into :func:`module_::def`. With this modified binding code, we can now
192
+ call the function using keyword arguments, which is a more readable alternative
193
+ particularly for functions taking many parameters:
194
+
195
+ .. code-block:: pycon
196
+
197
+ >>> import example
198
+ >>> example.add(i=1, j=2)
199
+ 3L
200
+
201
+ The keyword names also appear in the function signatures within the documentation.
202
+
203
+ .. code-block:: pycon
204
+
205
+ >>> help(example)
206
+
207
+ ....
208
+
209
+ FUNCTIONS
210
+ add(...)
211
+ Signature : (i: int, j: int) -> int
212
+
213
+ A function which adds two numbers
214
+
215
+ A shorter notation for named arguments is also available:
216
+
217
+ .. code-block:: cpp
218
+
219
+ // regular notation
220
+ m.def("add1", &add, py::arg("i"), py::arg("j"));
221
+ // shorthand
222
+ using namespace pybind11::literals;
223
+ m.def("add2", &add, "i"_a, "j"_a);
224
+
225
+ The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
226
+ Note that the literal operator must first be made visible with the directive
227
+ ``using namespace pybind11::literals``. This does not bring in anything else
228
+ from the ``pybind11`` namespace except for literals.
229
+
230
+ .. _default_args:
231
+
232
+ Default arguments
233
+ =================
234
+
235
+ Suppose now that the function to be bound has default arguments, e.g.:
236
+
237
+ .. code-block:: cpp
238
+
239
+ int add(int i = 1, int j = 2) {
240
+ return i + j;
241
+ }
242
+
243
+ Unfortunately, pybind11 cannot automatically extract these parameters, since they
244
+ are not part of the function's type information. However, they are simple to specify
245
+ using an extension of :class:`arg`:
246
+
247
+ .. code-block:: cpp
248
+
249
+ m.def("add", &add, "A function which adds two numbers",
250
+ py::arg("i") = 1, py::arg("j") = 2);
251
+
252
+ The default values also appear within the documentation.
253
+
254
+ .. code-block:: pycon
255
+
256
+ >>> help(example)
257
+
258
+ ....
259
+
260
+ FUNCTIONS
261
+ add(...)
262
+ Signature : (i: int = 1, j: int = 2) -> int
263
+
264
+ A function which adds two numbers
265
+
266
+ The shorthand notation is also available for default arguments:
267
+
268
+ .. code-block:: cpp
269
+
270
+ // regular notation
271
+ m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
272
+ // shorthand
273
+ m.def("add2", &add, "i"_a=1, "j"_a=2);
274
+
275
+ Exporting variables
276
+ ===================
277
+
278
+ To expose a value from C++, use the ``attr`` function to register it in a
279
+ module as shown below. Built-in types and general objects (more on that later)
280
+ are automatically converted when assigned as attributes, and can be explicitly
281
+ converted using the function ``py::cast``.
282
+
283
+ .. code-block:: cpp
284
+
285
+ PYBIND11_MODULE(example, m) {
286
+ m.attr("the_answer") = 42;
287
+ py::object world = py::cast("World");
288
+ m.attr("what") = world;
289
+ }
290
+
291
+ These are then accessible from Python:
292
+
293
+ .. code-block:: pycon
294
+
295
+ >>> import example
296
+ >>> example.the_answer
297
+ 42
298
+ >>> example.what
299
+ 'World'
300
+
301
+ .. _supported_types:
302
+
303
+ Supported data types
304
+ ====================
305
+
306
+ A large number of data types are supported out of the box and can be used
307
+ seamlessly as functions arguments, return values or with ``py::cast`` in general.
308
+ For a full overview, see the :doc:`advanced/cast/index` section.
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/benchmark.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import random
3
+ import os
4
+ import time
5
+ import datetime as dt
6
+
7
+ nfns = 4 # Functions per class
8
+ nargs = 4 # Arguments per function
9
+
10
+
11
+ def generate_dummy_code_pybind11(nclasses=10):
12
+ decl = ""
13
+ bindings = ""
14
+
15
+ for cl in range(nclasses):
16
+ decl += "class cl%03i;\n" % cl
17
+ decl += "\n"
18
+
19
+ for cl in range(nclasses):
20
+ decl += "class cl%03i {\n" % cl
21
+ decl += "public:\n"
22
+ bindings += ' py::class_<cl%03i>(m, "cl%03i")\n' % (cl, cl)
23
+ for fn in range(nfns):
24
+ ret = random.randint(0, nclasses - 1)
25
+ params = [random.randint(0, nclasses - 1) for i in range(nargs)]
26
+ decl += " cl%03i *fn_%03i(" % (ret, fn)
27
+ decl += ", ".join("cl%03i *" % p for p in params)
28
+ decl += ");\n"
29
+ bindings += ' .def("fn_%03i", &cl%03i::fn_%03i)\n' % (fn, cl, fn)
30
+ decl += "};\n\n"
31
+ bindings += " ;\n"
32
+
33
+ result = "#include <pybind11/pybind11.h>\n\n"
34
+ result += "namespace py = pybind11;\n\n"
35
+ result += decl + "\n"
36
+ result += "PYBIND11_MODULE(example, m) {\n"
37
+ result += bindings
38
+ result += "}"
39
+ return result
40
+
41
+
42
+ def generate_dummy_code_boost(nclasses=10):
43
+ decl = ""
44
+ bindings = ""
45
+
46
+ for cl in range(nclasses):
47
+ decl += "class cl%03i;\n" % cl
48
+ decl += "\n"
49
+
50
+ for cl in range(nclasses):
51
+ decl += "class cl%03i {\n" % cl
52
+ decl += "public:\n"
53
+ bindings += ' py::class_<cl%03i>("cl%03i")\n' % (cl, cl)
54
+ for fn in range(nfns):
55
+ ret = random.randint(0, nclasses - 1)
56
+ params = [random.randint(0, nclasses - 1) for i in range(nargs)]
57
+ decl += " cl%03i *fn_%03i(" % (ret, fn)
58
+ decl += ", ".join("cl%03i *" % p for p in params)
59
+ decl += ");\n"
60
+ bindings += (
61
+ ' .def("fn_%03i", &cl%03i::fn_%03i, py::return_value_policy<py::manage_new_object>())\n'
62
+ % (fn, cl, fn)
63
+ )
64
+ decl += "};\n\n"
65
+ bindings += " ;\n"
66
+
67
+ result = "#include <boost/python.hpp>\n\n"
68
+ result += "namespace py = boost::python;\n\n"
69
+ result += decl + "\n"
70
+ result += "BOOST_PYTHON_MODULE(example) {\n"
71
+ result += bindings
72
+ result += "}"
73
+ return result
74
+
75
+
76
+ for codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]:
77
+ print("{")
78
+ for i in range(0, 10):
79
+ nclasses = 2 ** i
80
+ with open("test.cpp", "w") as f:
81
+ f.write(codegen(nclasses))
82
+ n1 = dt.datetime.now()
83
+ os.system(
84
+ "g++ -Os -shared -rdynamic -undefined dynamic_lookup "
85
+ "-fvisibility=hidden -std=c++14 test.cpp -I include "
86
+ "-I /System/Library/Frameworks/Python.framework/Headers -o test.so"
87
+ )
88
+ n2 = dt.datetime.now()
89
+ elapsed = (n2 - n1).total_seconds()
90
+ size = os.stat("test.so").st_size
91
+ print(" {%i, %f, %i}," % (nclasses * nfns, elapsed, size))
92
+ print("}")
third-party/DPVO/Pangolin/components/pango_python/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/Pangolin/components/pango_python/pybind11/docs/changelog.rst ADDED
@@ -0,0 +1,1881 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _changelog:
2
+
3
+ Changelog
4
+ #########
5
+
6
+ Starting with version 1.8.0, pybind11 releases use a `semantic versioning
7
+ <http://semver.org>`_ policy.
8
+
9
+ v2.8.0 (WIP)
10
+ ------------
11
+
12
+ * Allow exception translators to be optionally registered local to a module
13
+ instead of applying globally across all pybind11 modules. Use
14
+ ``register_local_exception_translator(ExceptionTranslator&& translator)``
15
+ instead of ``register_exception_translator(ExceptionTranslator&&
16
+ translator)`` to keep your exception remapping code local to the module.
17
+ `#2650 <https://github.com/pybind/pybind11/pull/2650>`_
18
+
19
+ v2.7.1 (Aug 3, 2021)
20
+ ---------------------
21
+
22
+ Minor missing functionality added:
23
+
24
+ * Allow Python builtins to be used as callbacks in CPython.
25
+ `#1413 <https://github.com/pybind/pybind11/pull/1413>`_
26
+
27
+ Bug fixes:
28
+
29
+ * Fix regression in CMake Python package config: improper use of absolute path.
30
+ `#3144 <https://github.com/pybind/pybind11/pull/3144>`_
31
+
32
+ * Fix Mingw64 and add to the CI testing matrix.
33
+ `#3132 <https://github.com/pybind/pybind11/pull/3132>`_
34
+
35
+ * Specified UTF8-encoding in setup.py calls of open().
36
+ `#3137 <https://github.com/pybind/pybind11/pull/3137>`_
37
+
38
+ * Add clang-tidy-readability rules to make boolean casts explicit improving
39
+ code readability. Also enabled other misc and readability clang-tidy checks.
40
+ `#3148 <https://github.com/pybind/pybind11/pull/3148>`_
41
+
42
+ * Move object in ``.pop()`` for list.
43
+ `#3116 <https://github.com/pybind/pybind11/pull/3116>`_
44
+
45
+ Backend and tidying up:
46
+
47
+ * Removed and fixed warning suppressions.
48
+ `#3127 <https://github.com/pybind/pybind11/pull/3127>`_
49
+ `#3129 <https://github.com/pybind/pybind11/pull/3129>`_
50
+ `#3135 <https://github.com/pybind/pybind11/pull/3135>`_
51
+ `#3141 <https://github.com/pybind/pybind11/pull/3141>`_
52
+ `#3142 <https://github.com/pybind/pybind11/pull/3142>`_
53
+ `#3150 <https://github.com/pybind/pybind11/pull/3150>`_
54
+ `#3152 <https://github.com/pybind/pybind11/pull/3152>`_
55
+ `#3160 <https://github.com/pybind/pybind11/pull/3160>`_
56
+ `#3161 <https://github.com/pybind/pybind11/pull/3161>`_
57
+
58
+
59
+ v2.7.0 (Jul 16, 2021)
60
+ ---------------------
61
+
62
+ New features:
63
+
64
+ * Enable ``py::implicitly_convertible<py::none, ...>`` for
65
+ ``py::class_``-wrapped types.
66
+ `#3059 <https://github.com/pybind/pybind11/pull/3059>`_
67
+
68
+ * Allow function pointer extraction from overloaded functions.
69
+ `#2944 <https://github.com/pybind/pybind11/pull/2944>`_
70
+
71
+ * NumPy: added ``.char_()`` to type which gives the NumPy public ``char``
72
+ result, which also distinguishes types by bit length (unlike ``.kind()``).
73
+ `#2864 <https://github.com/pybind/pybind11/pull/2864>`_
74
+
75
+ * Add ``pybind11::bytearray`` to manipulate ``bytearray`` similar to ``bytes``.
76
+ `#2799 <https://github.com/pybind/pybind11/pull/2799>`_
77
+
78
+ * ``pybind11/stl/filesystem.h`` registers a type caster that, on C++17/Python
79
+ 3.6+, converts ``std::filesystem::path`` to ``pathlib.Path`` and any
80
+ ``os.PathLike`` to ``std::filesystem::path``.
81
+ `#2730 <https://github.com/pybind/pybind11/pull/2730>`_
82
+
83
+ * A ``PYBIND11_VERSION_HEX`` define was added, similar to ``PY_VERSION_HEX``.
84
+ `#3120 <https://github.com/pybind/pybind11/pull/3120>`_
85
+
86
+
87
+
88
+ Changes:
89
+
90
+ * ``py::str`` changed to exclusively hold `PyUnicodeObject`. Previously
91
+ ``py::str`` could also hold `bytes`, which is probably surprising, was
92
+ never documented, and can mask bugs (e.g. accidental use of ``py::str``
93
+ instead of ``py::bytes``).
94
+ `#2409 <https://github.com/pybind/pybind11/pull/2409>`_
95
+
96
+ * Add a safety guard to ensure that the Python GIL is held when C++ calls back
97
+ into Python via ``object_api<>::operator()`` (e.g. ``py::function``
98
+ ``__call__``). (This feature is available for Python 3.6+ only.)
99
+ `#2919 <https://github.com/pybind/pybind11/pull/2919>`_
100
+
101
+ * Catch a missing ``self`` argument in calls to ``__init__()``.
102
+ `#2914 <https://github.com/pybind/pybind11/pull/2914>`_
103
+
104
+ * Use ``std::string_view`` if available to avoid a copy when passing an object
105
+ to a ``std::ostream``.
106
+ `#3042 <https://github.com/pybind/pybind11/pull/3042>`_
107
+
108
+ * An important warning about thread safety was added to the ``iostream.h``
109
+ documentation; attempts to make ``py::scoped_ostream_redirect`` thread safe
110
+ have been removed, as it was only partially effective.
111
+ `#2995 <https://github.com/pybind/pybind11/pull/2995>`_
112
+
113
+
114
+ Fixes:
115
+
116
+ * Performance: avoid unnecessary strlen calls.
117
+ `#3058 <https://github.com/pybind/pybind11/pull/3058>`_
118
+
119
+ * Fix auto-generated documentation string when using ``const T`` in
120
+ ``pyarray_t``.
121
+ `#3020 <https://github.com/pybind/pybind11/pull/3020>`_
122
+
123
+ * Unify error messages thrown by ``simple_collector``/``unpacking_collector``.
124
+ `#3013 <https://github.com/pybind/pybind11/pull/3013>`_
125
+
126
+ * ``pybind11::builtin_exception`` is now explicitly exported, which means the
127
+ types included/defined in different modules are identical, and exceptions
128
+ raised in different modules can be caught correctly. The documentation was
129
+ updated to explain that custom exceptions that are used across module
130
+ boundaries need to be explicitly exported as well.
131
+ `#2999 <https://github.com/pybind/pybind11/pull/2999>`_
132
+
133
+ * Fixed exception when printing UTF-8 to a ``scoped_ostream_redirect``.
134
+ `#2982 <https://github.com/pybind/pybind11/pull/2982>`_
135
+
136
+ * Pickle support enhancement: ``setstate`` implementation will attempt to
137
+ ``setattr`` ``__dict__`` only if the unpickled ``dict`` object is not empty,
138
+ to not force use of ``py::dynamic_attr()`` unnecessarily.
139
+ `#2972 <https://github.com/pybind/pybind11/pull/2972>`_
140
+
141
+ * Allow negative timedelta values to roundtrip.
142
+ `#2870 <https://github.com/pybind/pybind11/pull/2870>`_
143
+
144
+ * Fix unchecked errors could potentially swallow signals/other exceptions.
145
+ `#2863 <https://github.com/pybind/pybind11/pull/2863>`_
146
+
147
+ * Add null pointer check with ``std::localtime``.
148
+ `#2846 <https://github.com/pybind/pybind11/pull/2846>`_
149
+
150
+ * Fix the ``weakref`` constructor from ``py::object`` to create a new
151
+ ``weakref`` on conversion.
152
+ `#2832 <https://github.com/pybind/pybind11/pull/2832>`_
153
+
154
+ * Avoid relying on exceptions in C++17 when getting a ``shared_ptr`` holder
155
+ from a ``shared_from_this`` class.
156
+ `#2819 <https://github.com/pybind/pybind11/pull/2819>`_
157
+
158
+ * Allow the codec's exception to be raised instead of :code:`RuntimeError` when
159
+ casting from :code:`py::str` to :code:`std::string`.
160
+ `#2903 <https://github.com/pybind/pybind11/pull/2903>`_
161
+
162
+
163
+ Build system improvements:
164
+
165
+ * In ``setup_helpers.py``, test for platforms that have some multiprocessing
166
+ features but lack semaphores, which ``ParallelCompile`` requires.
167
+ `#3043 <https://github.com/pybind/pybind11/pull/3043>`_
168
+
169
+ * Fix ``pybind11_INCLUDE_DIR`` in case ``CMAKE_INSTALL_INCLUDEDIR`` is
170
+ absolute.
171
+ `#3005 <https://github.com/pybind/pybind11/pull/3005>`_
172
+
173
+ * Fix bug not respecting ``WITH_SOABI`` or ``WITHOUT_SOABI`` to CMake.
174
+ `#2938 <https://github.com/pybind/pybind11/pull/2938>`_
175
+
176
+ * Fix the default ``Pybind11Extension`` compilation flags with a Mingw64 python.
177
+ `#2921 <https://github.com/pybind/pybind11/pull/2921>`_
178
+
179
+ * Clang on Windows: do not pass ``/MP`` (ignored flag).
180
+ `#2824 <https://github.com/pybind/pybind11/pull/2824>`_
181
+
182
+ * ``pybind11.setup_helpers.intree_extensions`` can be used to generate
183
+ ``Pybind11Extension`` instances from cpp files placed in the Python package
184
+ source tree.
185
+ `#2831 <https://github.com/pybind/pybind11/pull/2831>`_
186
+
187
+ Backend and tidying up:
188
+
189
+ * Enable clang-tidy performance, readability, and modernization checks
190
+ throughout the codebase to enforce best coding practices.
191
+ `#3046 <https://github.com/pybind/pybind11/pull/3046>`_,
192
+ `#3049 <https://github.com/pybind/pybind11/pull/3049>`_,
193
+ `#3051 <https://github.com/pybind/pybind11/pull/3051>`_,
194
+ `#3052 <https://github.com/pybind/pybind11/pull/3052>`_,
195
+ `#3080 <https://github.com/pybind/pybind11/pull/3080>`_, and
196
+ `#3094 <https://github.com/pybind/pybind11/pull/3094>`_
197
+
198
+
199
+ * Checks for common misspellings were added to the pre-commit hooks.
200
+ `#3076 <https://github.com/pybind/pybind11/pull/3076>`_
201
+
202
+ * Changed ``Werror`` to stricter ``Werror-all`` for Intel compiler and fixed
203
+ minor issues.
204
+ `#2948 <https://github.com/pybind/pybind11/pull/2948>`_
205
+
206
+ * Fixed compilation with GCC < 5 when the user defines ``_GLIBCXX_USE_CXX11_ABI``.
207
+ `#2956 <https://github.com/pybind/pybind11/pull/2956>`_
208
+
209
+ * Added nox support for easier local testing and linting of contributions.
210
+ `#3101 <https://github.com/pybind/pybind11/pull/3101>`_ and
211
+ `#3121 <https://github.com/pybind/pybind11/pull/3121>`_
212
+
213
+ * Avoid RTD style issue with docutils 0.17+.
214
+ `#3119 <https://github.com/pybind/pybind11/pull/3119>`_
215
+
216
+ * Support pipx run, such as ``pipx run pybind11 --include`` for a quick compile.
217
+ `#3117 <https://github.com/pybind/pybind11/pull/3117>`_
218
+
219
+
220
+
221
+ v2.6.2 (Jan 26, 2021)
222
+ ---------------------
223
+
224
+ Minor missing functionality added:
225
+
226
+ * enum: add missing Enum.value property.
227
+ `#2739 <https://github.com/pybind/pybind11/pull/2739>`_
228
+
229
+ * Allow thread termination to be avoided during shutdown for CPython 3.7+ via
230
+ ``.disarm`` for ``gil_scoped_acquire``/``gil_scoped_release``.
231
+ `#2657 <https://github.com/pybind/pybind11/pull/2657>`_
232
+
233
+ Fixed or improved behavior in a few special cases:
234
+
235
+ * Fix bug where the constructor of ``object`` subclasses would not throw on
236
+ being passed a Python object of the wrong type.
237
+ `#2701 <https://github.com/pybind/pybind11/pull/2701>`_
238
+
239
+ * The ``type_caster`` for integers does not convert Python objects with
240
+ ``__int__`` anymore with ``noconvert`` or during the first round of trying
241
+ overloads.
242
+ `#2698 <https://github.com/pybind/pybind11/pull/2698>`_
243
+
244
+ * When casting to a C++ integer, ``__index__`` is always called and not
245
+ considered as conversion, consistent with Python 3.8+.
246
+ `#2801 <https://github.com/pybind/pybind11/pull/2801>`_
247
+
248
+ Build improvements:
249
+
250
+ * Setup helpers: ``extra_compile_args`` and ``extra_link_args`` automatically set by
251
+ Pybind11Extension are now prepended, which allows them to be overridden
252
+ by user-set ``extra_compile_args`` and ``extra_link_args``.
253
+ `#2808 <https://github.com/pybind/pybind11/pull/2808>`_
254
+
255
+ * Setup helpers: Don't trigger unused parameter warning.
256
+ `#2735 <https://github.com/pybind/pybind11/pull/2735>`_
257
+
258
+ * CMake: Support running with ``--warn-uninitialized`` active.
259
+ `#2806 <https://github.com/pybind/pybind11/pull/2806>`_
260
+
261
+ * CMake: Avoid error if included from two submodule directories.
262
+ `#2804 <https://github.com/pybind/pybind11/pull/2804>`_
263
+
264
+ * CMake: Fix ``STATIC`` / ``SHARED`` being ignored in FindPython mode.
265
+ `#2796 <https://github.com/pybind/pybind11/pull/2796>`_
266
+
267
+ * CMake: Respect the setting for ``CMAKE_CXX_VISIBILITY_PRESET`` if defined.
268
+ `#2793 <https://github.com/pybind/pybind11/pull/2793>`_
269
+
270
+ * CMake: Fix issue with FindPython2/FindPython3 not working with ``pybind11::embed``.
271
+ `#2662 <https://github.com/pybind/pybind11/pull/2662>`_
272
+
273
+ * CMake: mixing local and installed pybind11's would prioritize the installed
274
+ one over the local one (regression in 2.6.0).
275
+ `#2716 <https://github.com/pybind/pybind11/pull/2716>`_
276
+
277
+
278
+ Bug fixes:
279
+
280
+ * Fixed segfault in multithreaded environments when using
281
+ ``scoped_ostream_redirect``.
282
+ `#2675 <https://github.com/pybind/pybind11/pull/2675>`_
283
+
284
+ * Leave docstring unset when all docstring-related options are disabled, rather
285
+ than set an empty string.
286
+ `#2745 <https://github.com/pybind/pybind11/pull/2745>`_
287
+
288
+ * The module key in builtins that pybind11 uses to store its internals changed
289
+ from std::string to a python str type (more natural on Python 2, no change on
290
+ Python 3).
291
+ `#2814 <https://github.com/pybind/pybind11/pull/2814>`_
292
+
293
+ * Fixed assertion error related to unhandled (later overwritten) exception in
294
+ CPython 3.8 and 3.9 debug builds.
295
+ `#2685 <https://github.com/pybind/pybind11/pull/2685>`_
296
+
297
+ * Fix ``py::gil_scoped_acquire`` assert with CPython 3.9 debug build.
298
+ `#2683 <https://github.com/pybind/pybind11/pull/2683>`_
299
+
300
+ * Fix issue with a test failing on pytest 6.2.
301
+ `#2741 <https://github.com/pybind/pybind11/pull/2741>`_
302
+
303
+ Warning fixes:
304
+
305
+ * Fix warning modifying constructor parameter 'flag' that shadows a field of
306
+ 'set_flag' ``[-Wshadow-field-in-constructor-modified]``.
307
+ `#2780 <https://github.com/pybind/pybind11/pull/2780>`_
308
+
309
+ * Suppressed some deprecation warnings about old-style
310
+ ``__init__``/``__setstate__`` in the tests.
311
+ `#2759 <https://github.com/pybind/pybind11/pull/2759>`_
312
+
313
+ Valgrind work:
314
+
315
+ * Fix invalid access when calling a pybind11 ``__init__`` on a non-pybind11
316
+ class instance.
317
+ `#2755 <https://github.com/pybind/pybind11/pull/2755>`_
318
+
319
+ * Fixed various minor memory leaks in pybind11's test suite.
320
+ `#2758 <https://github.com/pybind/pybind11/pull/2758>`_
321
+
322
+ * Resolved memory leak in cpp_function initialization when exceptions occurred.
323
+ `#2756 <https://github.com/pybind/pybind11/pull/2756>`_
324
+
325
+ * Added a Valgrind build, checking for leaks and memory-related UB, to CI.
326
+ `#2746 <https://github.com/pybind/pybind11/pull/2746>`_
327
+
328
+ Compiler support:
329
+
330
+ * Intel compiler was not activating C++14 support due to a broken define.
331
+ `#2679 <https://github.com/pybind/pybind11/pull/2679>`_
332
+
333
+ * Support ICC and NVIDIA HPC SDK in C++17 mode.
334
+ `#2729 <https://github.com/pybind/pybind11/pull/2729>`_
335
+
336
+ * Support Intel OneAPI compiler (ICC 20.2) and add to CI.
337
+ `#2573 <https://github.com/pybind/pybind11/pull/2573>`_
338
+
339
+
340
+
341
+ v2.6.1 (Nov 11, 2020)
342
+ ---------------------
343
+
344
+ * ``py::exec``, ``py::eval``, and ``py::eval_file`` now add the builtins module
345
+ as ``"__builtins__"`` to their ``globals`` argument, better matching ``exec``
346
+ and ``eval`` in pure Python.
347
+ `#2616 <https://github.com/pybind/pybind11/pull/2616>`_
348
+
349
+ * ``setup_helpers`` will no longer set a minimum macOS version higher than the
350
+ current version.
351
+ `#2622 <https://github.com/pybind/pybind11/pull/2622>`_
352
+
353
+ * Allow deleting static properties.
354
+ `#2629 <https://github.com/pybind/pybind11/pull/2629>`_
355
+
356
+ * Seal a leak in ``def_buffer``, cleaning up the ``capture`` object after the
357
+ ``class_`` object goes out of scope.
358
+ `#2634 <https://github.com/pybind/pybind11/pull/2634>`_
359
+
360
+ * ``pybind11_INCLUDE_DIRS`` was incorrect, potentially causing a regression if
361
+ it was expected to include ``PYTHON_INCLUDE_DIRS`` (please use targets
362
+ instead).
363
+ `#2636 <https://github.com/pybind/pybind11/pull/2636>`_
364
+
365
+ * Added parameter names to the ``py::enum_`` constructor and methods, avoiding
366
+ ``arg0`` in the generated docstrings.
367
+ `#2637 <https://github.com/pybind/pybind11/pull/2637>`_
368
+
369
+ * Added ``needs_recompile`` optional function to the ``ParallelCompiler``
370
+ helper, to allow a recompile to be skipped based on a user-defined function.
371
+ `#2643 <https://github.com/pybind/pybind11/pull/2643>`_
372
+
373
+
374
+ v2.6.0 (Oct 21, 2020)
375
+ ---------------------
376
+
377
+ See :ref:`upgrade-guide-2.6` for help upgrading to the new version.
378
+
379
+ New features:
380
+
381
+ * Keyword-only arguments supported in Python 2 or 3 with ``py::kw_only()``.
382
+ `#2100 <https://github.com/pybind/pybind11/pull/2100>`_
383
+
384
+ * Positional-only arguments supported in Python 2 or 3 with ``py::pos_only()``.
385
+ `#2459 <https://github.com/pybind/pybind11/pull/2459>`_
386
+
387
+ * ``py::is_final()`` class modifier to block subclassing (CPython only).
388
+ `#2151 <https://github.com/pybind/pybind11/pull/2151>`_
389
+
390
+ * Added ``py::prepend()``, allowing a function to be placed at the beginning of
391
+ the overload chain.
392
+ `#1131 <https://github.com/pybind/pybind11/pull/1131>`_
393
+
394
+ * Access to the type object now provided with ``py::type::of<T>()`` and
395
+ ``py::type::of(h)``.
396
+ `#2364 <https://github.com/pybind/pybind11/pull/2364>`_
397
+
398
+ * Perfect forwarding support for methods.
399
+ `#2048 <https://github.com/pybind/pybind11/pull/2048>`_
400
+
401
+ * Added ``py::error_already_set::discard_as_unraisable()``.
402
+ `#2372 <https://github.com/pybind/pybind11/pull/2372>`_
403
+
404
+ * ``py::hash`` is now public.
405
+ `#2217 <https://github.com/pybind/pybind11/pull/2217>`_
406
+
407
+ * ``py::class_<union_type>`` is now supported. Note that writing to one data
408
+ member of the union and reading another (type punning) is UB in C++. Thus
409
+ pybind11-bound enums should never be used for such conversions.
410
+ `#2320 <https://github.com/pybind/pybind11/pull/2320>`_.
411
+
412
+ * Classes now check local scope when registering members, allowing a subclass
413
+ to have a member with the same name as a parent (such as an enum).
414
+ `#2335 <https://github.com/pybind/pybind11/pull/2335>`_
415
+
416
+ Code correctness features:
417
+
418
+ * Error now thrown when ``__init__`` is forgotten on subclasses.
419
+ `#2152 <https://github.com/pybind/pybind11/pull/2152>`_
420
+
421
+ * Throw error if conversion to a pybind11 type if the Python object isn't a
422
+ valid instance of that type, such as ``py::bytes(o)`` when ``py::object o``
423
+ isn't a bytes instance.
424
+ `#2349 <https://github.com/pybind/pybind11/pull/2349>`_
425
+
426
+ * Throw if conversion to ``str`` fails.
427
+ `#2477 <https://github.com/pybind/pybind11/pull/2477>`_
428
+
429
+
430
+ API changes:
431
+
432
+ * ``py::module`` was renamed ``py::module_`` to avoid issues with C++20 when
433
+ used unqualified, but an alias ``py::module`` is provided for backward
434
+ compatibility.
435
+ `#2489 <https://github.com/pybind/pybind11/pull/2489>`_
436
+
437
+ * Public constructors for ``py::module_`` have been deprecated; please use
438
+ ``pybind11::module_::create_extension_module`` if you were using the public
439
+ constructor (fairly rare after ``PYBIND11_MODULE`` was introduced).
440
+ `#2552 <https://github.com/pybind/pybind11/pull/2552>`_
441
+
442
+ * ``PYBIND11_OVERLOAD*`` macros and ``get_overload`` function replaced by
443
+ correctly-named ``PYBIND11_OVERRIDE*`` and ``get_override``, fixing
444
+ inconsistencies in the presence of a closing ``;`` in these macros.
445
+ ``get_type_overload`` is deprecated.
446
+ `#2325 <https://github.com/pybind/pybind11/pull/2325>`_
447
+
448
+ Packaging / building improvements:
449
+
450
+ * The Python package was reworked to be more powerful and useful.
451
+ `#2433 <https://github.com/pybind/pybind11/pull/2433>`_
452
+
453
+ * :ref:`build-setuptools` is easier thanks to a new
454
+ ``pybind11.setup_helpers`` module, which provides utilities to use
455
+ setuptools with pybind11. It can be used via PEP 518, ``setup_requires``,
456
+ or by directly importing or copying ``setup_helpers.py`` into your project.
457
+
458
+ * CMake configuration files are now included in the Python package. Use
459
+ ``pybind11.get_cmake_dir()`` or ``python -m pybind11 --cmakedir`` to get
460
+ the directory with the CMake configuration files, or include the
461
+ site-packages location in your ``CMAKE_MODULE_PATH``. Or you can use the
462
+ new ``pybind11[global]`` extra when you install ``pybind11``, which
463
+ installs the CMake files and headers into your base environment in the
464
+ standard location.
465
+
466
+ * ``pybind11-config`` is another way to write ``python -m pybind11`` if you
467
+ have your PATH set up.
468
+
469
+ * Added external typing support to the helper module, code from
470
+ ``import pybind11`` can now be type checked.
471
+ `#2588 <https://github.com/pybind/pybind11/pull/2588>`_
472
+
473
+ * Minimum CMake required increased to 3.4.
474
+ `#2338 <https://github.com/pybind/pybind11/pull/2338>`_ and
475
+ `#2370 <https://github.com/pybind/pybind11/pull/2370>`_
476
+
477
+ * Full integration with CMake’s C++ standard system and compile features
478
+ replaces ``PYBIND11_CPP_STANDARD``.
479
+
480
+ * Generated config file is now portable to different Python/compiler/CMake
481
+ versions.
482
+
483
+ * Virtual environments prioritized if ``PYTHON_EXECUTABLE`` is not set
484
+ (``venv``, ``virtualenv``, and ``conda``) (similar to the new FindPython
485
+ mode).
486
+
487
+ * Other CMake features now natively supported, like
488
+ ``CMAKE_INTERPROCEDURAL_OPTIMIZATION``, ``set(CMAKE_CXX_VISIBILITY_PRESET
489
+ hidden)``.
490
+
491
+ * ``CUDA`` as a language is now supported.
492
+
493
+ * Helper functions ``pybind11_strip``, ``pybind11_extension``,
494
+ ``pybind11_find_import`` added, see :doc:`cmake/index`.
495
+
496
+ * Optional :ref:`find-python-mode` and :ref:`nopython-mode` with CMake.
497
+ `#2370 <https://github.com/pybind/pybind11/pull/2370>`_
498
+
499
+ * Uninstall target added.
500
+ `#2265 <https://github.com/pybind/pybind11/pull/2265>`_ and
501
+ `#2346 <https://github.com/pybind/pybind11/pull/2346>`_
502
+
503
+ * ``pybind11_add_module()`` now accepts an optional ``OPT_SIZE`` flag that
504
+ switches the binding target to size-based optimization if the global build
505
+ type can not always be fixed to ``MinSizeRel`` (except in debug mode, where
506
+ optimizations remain disabled). ``MinSizeRel`` or this flag reduces binary
507
+ size quite substantially (~25% on some platforms).
508
+ `#2463 <https://github.com/pybind/pybind11/pull/2463>`_
509
+
510
+ Smaller or developer focused features and fixes:
511
+
512
+ * Moved ``mkdoc.py`` to a new repo, `pybind11-mkdoc`_. There are no longer
513
+ submodules in the main repo.
514
+
515
+ * ``py::memoryview`` segfault fix and update, with new
516
+ ``py::memoryview::from_memory`` in Python 3, and documentation.
517
+ `#2223 <https://github.com/pybind/pybind11/pull/2223>`_
518
+
519
+ * Fix for ``buffer_info`` on Python 2.
520
+ `#2503 <https://github.com/pybind/pybind11/pull/2503>`_
521
+
522
+ * If ``__eq__`` defined but not ``__hash__``, ``__hash__`` is now set to
523
+ ``None``.
524
+ `#2291 <https://github.com/pybind/pybind11/pull/2291>`_
525
+
526
+ * ``py::ellipsis`` now also works on Python 2.
527
+ `#2360 <https://github.com/pybind/pybind11/pull/2360>`_
528
+
529
+ * Pointer to ``std::tuple`` & ``std::pair`` supported in cast.
530
+ `#2334 <https://github.com/pybind/pybind11/pull/2334>`_
531
+
532
+ * Small fixes in NumPy support. ``py::array`` now uses ``py::ssize_t`` as first
533
+ argument type.
534
+ `#2293 <https://github.com/pybind/pybind11/pull/2293>`_
535
+
536
+ * Added missing signature for ``py::array``.
537
+ `#2363 <https://github.com/pybind/pybind11/pull/2363>`_
538
+
539
+ * ``unchecked_mutable_reference`` has access to operator ``()`` and ``[]`` when
540
+ const.
541
+ `#2514 <https://github.com/pybind/pybind11/pull/2514>`_
542
+
543
+ * ``py::vectorize`` is now supported on functions that return void.
544
+ `#1969 <https://github.com/pybind/pybind11/pull/1969>`_
545
+
546
+ * ``py::capsule`` supports ``get_pointer`` and ``set_pointer``.
547
+ `#1131 <https://github.com/pybind/pybind11/pull/1131>`_
548
+
549
+ * Fix crash when different instances share the same pointer of the same type.
550
+ `#2252 <https://github.com/pybind/pybind11/pull/2252>`_
551
+
552
+ * Fix for ``py::len`` not clearing Python's error state when it fails and throws.
553
+ `#2575 <https://github.com/pybind/pybind11/pull/2575>`_
554
+
555
+ * Bugfixes related to more extensive testing, new GitHub Actions CI.
556
+ `#2321 <https://github.com/pybind/pybind11/pull/2321>`_
557
+
558
+ * Bug in timezone issue in Eastern hemisphere midnight fixed.
559
+ `#2438 <https://github.com/pybind/pybind11/pull/2438>`_
560
+
561
+ * ``std::chrono::time_point`` now works when the resolution is not the same as
562
+ the system.
563
+ `#2481 <https://github.com/pybind/pybind11/pull/2481>`_
564
+
565
+ * Bug fixed where ``py::array_t`` could accept arrays that did not match the
566
+ requested ordering.
567
+ `#2484 <https://github.com/pybind/pybind11/pull/2484>`_
568
+
569
+ * Avoid a segfault on some compilers when types are removed in Python.
570
+ `#2564 <https://github.com/pybind/pybind11/pull/2564>`_
571
+
572
+ * ``py::arg::none()`` is now also respected when passing keyword arguments.
573
+ `#2611 <https://github.com/pybind/pybind11/pull/2611>`_
574
+
575
+ * PyPy fixes, PyPy 7.3.x now supported, including PyPy3. (Known issue with
576
+ PyPy2 and Windows `#2596 <https://github.com/pybind/pybind11/issues/2596>`_).
577
+ `#2146 <https://github.com/pybind/pybind11/pull/2146>`_
578
+
579
+ * CPython 3.9.0 workaround for undefined behavior (macOS segfault).
580
+ `#2576 <https://github.com/pybind/pybind11/pull/2576>`_
581
+
582
+ * CPython 3.9 warning fixes.
583
+ `#2253 <https://github.com/pybind/pybind11/pull/2253>`_
584
+
585
+ * Improved C++20 support, now tested in CI.
586
+ `#2489 <https://github.com/pybind/pybind11/pull/2489>`_
587
+ `#2599 <https://github.com/pybind/pybind11/pull/2599>`_
588
+
589
+ * Improved but still incomplete debug Python interpreter support.
590
+ `#2025 <https://github.com/pybind/pybind11/pull/2025>`_
591
+
592
+ * NVCC (CUDA 11) now supported and tested in CI.
593
+ `#2461 <https://github.com/pybind/pybind11/pull/2461>`_
594
+
595
+ * NVIDIA PGI compilers now supported and tested in CI.
596
+ `#2475 <https://github.com/pybind/pybind11/pull/2475>`_
597
+
598
+ * At least Intel 18 now explicitly required when compiling with Intel.
599
+ `#2577 <https://github.com/pybind/pybind11/pull/2577>`_
600
+
601
+ * Extensive style checking in CI, with `pre-commit`_ support. Code
602
+ modernization, checked by clang-tidy.
603
+
604
+ * Expanded docs, including new main page, new installing section, and CMake
605
+ helpers page, along with over a dozen new sections on existing pages.
606
+
607
+ * In GitHub, new docs for contributing and new issue templates.
608
+
609
+ .. _pre-commit: https://pre-commit.com
610
+
611
+ .. _pybind11-mkdoc: https://github.com/pybind/pybind11-mkdoc
612
+
613
+ v2.5.0 (Mar 31, 2020)
614
+ -----------------------------------------------------
615
+
616
+ * Use C++17 fold expressions in type casters, if available. This can
617
+ improve performance during overload resolution when functions have
618
+ multiple arguments.
619
+ `#2043 <https://github.com/pybind/pybind11/pull/2043>`_.
620
+
621
+ * Changed include directory resolution in ``pybind11/__init__.py``
622
+ and installation in ``setup.py``. This fixes a number of open issues
623
+ where pybind11 headers could not be found in certain environments.
624
+ `#1995 <https://github.com/pybind/pybind11/pull/1995>`_.
625
+
626
+ * C++20 ``char8_t`` and ``u8string`` support. `#2026
627
+ <https://github.com/pybind/pybind11/pull/2026>`_.
628
+
629
+ * CMake: search for Python 3.9. `bb9c91
630
+ <https://github.com/pybind/pybind11/commit/bb9c91>`_.
631
+
632
+ * Fixes for MSYS-based build environments.
633
+ `#2087 <https://github.com/pybind/pybind11/pull/2087>`_,
634
+ `#2053 <https://github.com/pybind/pybind11/pull/2053>`_.
635
+
636
+ * STL bindings for ``std::vector<...>::clear``. `#2074
637
+ <https://github.com/pybind/pybind11/pull/2074>`_.
638
+
639
+ * Read-only flag for ``py::buffer``. `#1466
640
+ <https://github.com/pybind/pybind11/pull/1466>`_.
641
+
642
+ * Exception handling during module initialization.
643
+ `bf2b031 <https://github.com/pybind/pybind11/commit/bf2b031>`_.
644
+
645
+ * Support linking against a CPython debug build.
646
+ `#2025 <https://github.com/pybind/pybind11/pull/2025>`_.
647
+
648
+ * Fixed issues involving the availability and use of aligned ``new`` and
649
+ ``delete``. `#1988 <https://github.com/pybind/pybind11/pull/1988>`_,
650
+ `759221 <https://github.com/pybind/pybind11/commit/759221>`_.
651
+
652
+ * Fixed a resource leak upon interpreter shutdown.
653
+ `#2020 <https://github.com/pybind/pybind11/pull/2020>`_.
654
+
655
+ * Fixed error handling in the boolean caster.
656
+ `#1976 <https://github.com/pybind/pybind11/pull/1976>`_.
657
+
658
+ v2.4.3 (Oct 15, 2019)
659
+ -----------------------------------------------------
660
+
661
+ * Adapt pybind11 to a C API convention change in Python 3.8. `#1950
662
+ <https://github.com/pybind/pybind11/pull/1950>`_.
663
+
664
+ v2.4.2 (Sep 21, 2019)
665
+ -----------------------------------------------------
666
+
667
+ * Replaced usage of a C++14 only construct. `#1929
668
+ <https://github.com/pybind/pybind11/pull/1929>`_.
669
+
670
+ * Made an ifdef future-proof for Python >= 4. `f3109d
671
+ <https://github.com/pybind/pybind11/commit/f3109d>`_.
672
+
673
+ v2.4.1 (Sep 20, 2019)
674
+ -----------------------------------------------------
675
+
676
+ * Fixed a problem involving implicit conversion from enumerations to integers
677
+ on Python 3.8. `#1780 <https://github.com/pybind/pybind11/pull/1780>`_.
678
+
679
+ v2.4.0 (Sep 19, 2019)
680
+ -----------------------------------------------------
681
+
682
+ * Try harder to keep pybind11-internal data structures separate when there
683
+ are potential ABI incompatibilities. Fixes crashes that occurred when loading
684
+ multiple pybind11 extensions that were e.g. compiled by GCC (libstdc++)
685
+ and Clang (libc++).
686
+ `#1588 <https://github.com/pybind/pybind11/pull/1588>`_ and
687
+ `c9f5a <https://github.com/pybind/pybind11/commit/c9f5a>`_.
688
+
689
+ * Added support for ``__await__``, ``__aiter__``, and ``__anext__`` protocols.
690
+ `#1842 <https://github.com/pybind/pybind11/pull/1842>`_.
691
+
692
+ * ``pybind11_add_module()``: don't strip symbols when compiling in
693
+ ``RelWithDebInfo`` mode. `#1980
694
+ <https://github.com/pybind/pybind11/pull/1980>`_.
695
+
696
+ * ``enum_``: Reproduce Python behavior when comparing against invalid values
697
+ (e.g. ``None``, strings, etc.). Add back support for ``__invert__()``.
698
+ `#1912 <https://github.com/pybind/pybind11/pull/1912>`_,
699
+ `#1907 <https://github.com/pybind/pybind11/pull/1907>`_.
700
+
701
+ * List insertion operation for ``py::list``.
702
+ Added ``.empty()`` to all collection types.
703
+ Added ``py::set::contains()`` and ``py::dict::contains()``.
704
+ `#1887 <https://github.com/pybind/pybind11/pull/1887>`_,
705
+ `#1884 <https://github.com/pybind/pybind11/pull/1884>`_,
706
+ `#1888 <https://github.com/pybind/pybind11/pull/1888>`_.
707
+
708
+ * ``py::details::overload_cast_impl`` is available in C++11 mode, can be used
709
+ like ``overload_cast`` with an additional set of parentheses.
710
+ `#1581 <https://github.com/pybind/pybind11/pull/1581>`_.
711
+
712
+ * Fixed ``get_include()`` on Conda.
713
+ `#1877 <https://github.com/pybind/pybind11/pull/1877>`_.
714
+
715
+ * ``stl_bind.h``: negative indexing support.
716
+ `#1882 <https://github.com/pybind/pybind11/pull/1882>`_.
717
+
718
+ * Minor CMake fix to add MinGW compatibility.
719
+ `#1851 <https://github.com/pybind/pybind11/pull/1851>`_.
720
+
721
+ * GIL-related fixes.
722
+ `#1836 <https://github.com/pybind/pybind11/pull/1836>`_,
723
+ `8b90b <https://github.com/pybind/pybind11/commit/8b90b>`_.
724
+
725
+ * Other very minor/subtle fixes and improvements.
726
+ `#1329 <https://github.com/pybind/pybind11/pull/1329>`_,
727
+ `#1910 <https://github.com/pybind/pybind11/pull/1910>`_,
728
+ `#1863 <https://github.com/pybind/pybind11/pull/1863>`_,
729
+ `#1847 <https://github.com/pybind/pybind11/pull/1847>`_,
730
+ `#1890 <https://github.com/pybind/pybind11/pull/1890>`_,
731
+ `#1860 <https://github.com/pybind/pybind11/pull/1860>`_,
732
+ `#1848 <https://github.com/pybind/pybind11/pull/1848>`_,
733
+ `#1821 <https://github.com/pybind/pybind11/pull/1821>`_,
734
+ `#1837 <https://github.com/pybind/pybind11/pull/1837>`_,
735
+ `#1833 <https://github.com/pybind/pybind11/pull/1833>`_,
736
+ `#1748 <https://github.com/pybind/pybind11/pull/1748>`_,
737
+ `#1852 <https://github.com/pybind/pybind11/pull/1852>`_.
738
+
739
+ v2.3.0 (June 11, 2019)
740
+ -----------------------------------------------------
741
+
742
+ * Significantly reduced module binary size (10-20%) when compiled in C++11 mode
743
+ with GCC/Clang, or in any mode with MSVC. Function signatures are now always
744
+ precomputed at compile time (this was previously only available in C++14 mode
745
+ for non-MSVC compilers).
746
+ `#934 <https://github.com/pybind/pybind11/pull/934>`_.
747
+
748
+ * Add basic support for tag-based static polymorphism, where classes
749
+ provide a method to returns the desired type of an instance.
750
+ `#1326 <https://github.com/pybind/pybind11/pull/1326>`_.
751
+
752
+ * Python type wrappers (``py::handle``, ``py::object``, etc.)
753
+ now support map Python's number protocol onto C++ arithmetic
754
+ operators such as ``operator+``, ``operator/=``, etc.
755
+ `#1511 <https://github.com/pybind/pybind11/pull/1511>`_.
756
+
757
+ * A number of improvements related to enumerations:
758
+
759
+ 1. The ``enum_`` implementation was rewritten from scratch to reduce
760
+ code bloat. Rather than instantiating a full implementation for each
761
+ enumeration, most code is now contained in a generic base class.
762
+ `#1511 <https://github.com/pybind/pybind11/pull/1511>`_.
763
+
764
+ 2. The ``value()`` method of ``py::enum_`` now accepts an optional
765
+ docstring that will be shown in the documentation of the associated
766
+ enumeration. `#1160 <https://github.com/pybind/pybind11/pull/1160>`_.
767
+
768
+ 3. check for already existing enum value and throw an error if present.
769
+ `#1453 <https://github.com/pybind/pybind11/pull/1453>`_.
770
+
771
+ * Support for over-aligned type allocation via C++17's aligned ``new``
772
+ statement. `#1582 <https://github.com/pybind/pybind11/pull/1582>`_.
773
+
774
+ * Added ``py::ellipsis()`` method for slicing of multidimensional NumPy arrays
775
+ `#1502 <https://github.com/pybind/pybind11/pull/1502>`_.
776
+
777
+ * Numerous Improvements to the ``mkdoc.py`` script for extracting documentation
778
+ from C++ header files.
779
+ `#1788 <https://github.com/pybind/pybind11/pull/1788>`_.
780
+
781
+ * ``pybind11_add_module()``: allow including Python as a ``SYSTEM`` include path.
782
+ `#1416 <https://github.com/pybind/pybind11/pull/1416>`_.
783
+
784
+ * ``pybind11/stl.h`` does not convert strings to ``vector<string>`` anymore.
785
+ `#1258 <https://github.com/pybind/pybind11/issues/1258>`_.
786
+
787
+ * Mark static methods as such to fix auto-generated Sphinx documentation.
788
+ `#1732 <https://github.com/pybind/pybind11/pull/1732>`_.
789
+
790
+ * Re-throw forced unwind exceptions (e.g. during pthread termination).
791
+ `#1208 <https://github.com/pybind/pybind11/pull/1208>`_.
792
+
793
+ * Added ``__contains__`` method to the bindings of maps (``std::map``,
794
+ ``std::unordered_map``).
795
+ `#1767 <https://github.com/pybind/pybind11/pull/1767>`_.
796
+
797
+ * Improvements to ``gil_scoped_acquire``.
798
+ `#1211 <https://github.com/pybind/pybind11/pull/1211>`_.
799
+
800
+ * Type caster support for ``std::deque<T>``.
801
+ `#1609 <https://github.com/pybind/pybind11/pull/1609>`_.
802
+
803
+ * Support for ``std::unique_ptr`` holders, whose deleters differ between a base and derived
804
+ class. `#1353 <https://github.com/pybind/pybind11/pull/1353>`_.
805
+
806
+ * Construction of STL array/vector-like data structures from
807
+ iterators. Added an ``extend()`` operation.
808
+ `#1709 <https://github.com/pybind/pybind11/pull/1709>`_,
809
+
810
+ * CMake build system improvements for projects that include non-C++
811
+ files (e.g. plain C, CUDA) in ``pybind11_add_module`` et al.
812
+ `#1678 <https://github.com/pybind/pybind11/pull/1678>`_.
813
+
814
+ * Fixed asynchronous invocation and deallocation of Python functions
815
+ wrapped in ``std::function``.
816
+ `#1595 <https://github.com/pybind/pybind11/pull/1595>`_.
817
+
818
+ * Fixes regarding return value policy propagation in STL type casters.
819
+ `#1603 <https://github.com/pybind/pybind11/pull/1603>`_.
820
+
821
+ * Fixed scoped enum comparisons.
822
+ `#1571 <https://github.com/pybind/pybind11/pull/1571>`_.
823
+
824
+ * Fixed iostream redirection for code that releases the GIL.
825
+ `#1368 <https://github.com/pybind/pybind11/pull/1368>`_,
826
+
827
+ * A number of CI-related fixes.
828
+ `#1757 <https://github.com/pybind/pybind11/pull/1757>`_,
829
+ `#1744 <https://github.com/pybind/pybind11/pull/1744>`_,
830
+ `#1670 <https://github.com/pybind/pybind11/pull/1670>`_.
831
+
832
+ v2.2.4 (September 11, 2018)
833
+ -----------------------------------------------------
834
+
835
+ * Use new Python 3.7 Thread Specific Storage (TSS) implementation if available.
836
+ `#1454 <https://github.com/pybind/pybind11/pull/1454>`_,
837
+ `#1517 <https://github.com/pybind/pybind11/pull/1517>`_.
838
+
839
+ * Fixes for newer MSVC versions and C++17 mode.
840
+ `#1347 <https://github.com/pybind/pybind11/pull/1347>`_,
841
+ `#1462 <https://github.com/pybind/pybind11/pull/1462>`_.
842
+
843
+ * Propagate return value policies to type-specific casters
844
+ when casting STL containers.
845
+ `#1455 <https://github.com/pybind/pybind11/pull/1455>`_.
846
+
847
+ * Allow ostream-redirection of more than 1024 characters.
848
+ `#1479 <https://github.com/pybind/pybind11/pull/1479>`_.
849
+
850
+ * Set ``Py_DEBUG`` define when compiling against a debug Python build.
851
+ `#1438 <https://github.com/pybind/pybind11/pull/1438>`_.
852
+
853
+ * Untangle integer logic in number type caster to work for custom
854
+ types that may only be castable to a restricted set of builtin types.
855
+ `#1442 <https://github.com/pybind/pybind11/pull/1442>`_.
856
+
857
+ * CMake build system: Remember Python version in cache file.
858
+ `#1434 <https://github.com/pybind/pybind11/pull/1434>`_.
859
+
860
+ * Fix for custom smart pointers: use ``std::addressof`` to obtain holder
861
+ address instead of ``operator&``.
862
+ `#1435 <https://github.com/pybind/pybind11/pull/1435>`_.
863
+
864
+ * Properly report exceptions thrown during module initialization.
865
+ `#1362 <https://github.com/pybind/pybind11/pull/1362>`_.
866
+
867
+ * Fixed a segmentation fault when creating empty-shaped NumPy array.
868
+ `#1371 <https://github.com/pybind/pybind11/pull/1371>`_.
869
+
870
+ * The version of Intel C++ compiler must be >= 2017, and this is now checked by
871
+ the header files. `#1363 <https://github.com/pybind/pybind11/pull/1363>`_.
872
+
873
+ * A few minor typo fixes and improvements to the test suite, and
874
+ patches that silence compiler warnings.
875
+
876
+ * Vectors now support construction from generators, as well as ``extend()`` from a
877
+ list or generator.
878
+ `#1496 <https://github.com/pybind/pybind11/pull/1496>`_.
879
+
880
+
881
+ v2.2.3 (April 29, 2018)
882
+ -----------------------------------------------------
883
+
884
+ * The pybind11 header location detection was replaced by a new implementation
885
+ that no longer depends on ``pip`` internals (the recently released ``pip``
886
+ 10 has restricted access to this API).
887
+ `#1190 <https://github.com/pybind/pybind11/pull/1190>`_.
888
+
889
+ * Small adjustment to an implementation detail to work around a compiler segmentation fault in Clang 3.3/3.4.
890
+ `#1350 <https://github.com/pybind/pybind11/pull/1350>`_.
891
+
892
+ * The minimal supported version of the Intel compiler was >= 17.0 since
893
+ pybind11 v2.1. This check is now explicit, and a compile-time error is raised
894
+ if the compiler meet the requirement.
895
+ `#1363 <https://github.com/pybind/pybind11/pull/1363>`_.
896
+
897
+ * Fixed an endianness-related fault in the test suite.
898
+ `#1287 <https://github.com/pybind/pybind11/pull/1287>`_.
899
+
900
+ v2.2.2 (February 7, 2018)
901
+ -----------------------------------------------------
902
+
903
+ * Fixed a segfault when combining embedded interpreter
904
+ shutdown/reinitialization with external loaded pybind11 modules.
905
+ `#1092 <https://github.com/pybind/pybind11/pull/1092>`_.
906
+
907
+ * Eigen support: fixed a bug where Nx1/1xN numpy inputs couldn't be passed as
908
+ arguments to Eigen vectors (which for Eigen are simply compile-time fixed
909
+ Nx1/1xN matrices).
910
+ `#1106 <https://github.com/pybind/pybind11/pull/1106>`_.
911
+
912
+ * Clarified to license by moving the licensing of contributions from
913
+ ``LICENSE`` into ``CONTRIBUTING.md``: the licensing of contributions is not
914
+ actually part of the software license as distributed. This isn't meant to be
915
+ a substantial change in the licensing of the project, but addresses concerns
916
+ that the clause made the license non-standard.
917
+ `#1109 <https://github.com/pybind/pybind11/issues/1109>`_.
918
+
919
+ * Fixed a regression introduced in 2.1 that broke binding functions with lvalue
920
+ character literal arguments.
921
+ `#1128 <https://github.com/pybind/pybind11/pull/1128>`_.
922
+
923
+ * MSVC: fix for compilation failures under /permissive-, and added the flag to
924
+ the appveyor test suite.
925
+ `#1155 <https://github.com/pybind/pybind11/pull/1155>`_.
926
+
927
+ * Fixed ``__qualname__`` generation, and in turn, fixes how class names
928
+ (especially nested class names) are shown in generated docstrings.
929
+ `#1171 <https://github.com/pybind/pybind11/pull/1171>`_.
930
+
931
+ * Updated the FAQ with a suggested project citation reference.
932
+ `#1189 <https://github.com/pybind/pybind11/pull/1189>`_.
933
+
934
+ * Added fixes for deprecation warnings when compiled under C++17 with
935
+ ``-Wdeprecated`` turned on, and add ``-Wdeprecated`` to the test suite
936
+ compilation flags.
937
+ `#1191 <https://github.com/pybind/pybind11/pull/1191>`_.
938
+
939
+ * Fixed outdated PyPI URLs in ``setup.py``.
940
+ `#1213 <https://github.com/pybind/pybind11/pull/1213>`_.
941
+
942
+ * Fixed a refcount leak for arguments that end up in a ``py::args`` argument
943
+ for functions with both fixed positional and ``py::args`` arguments.
944
+ `#1216 <https://github.com/pybind/pybind11/pull/1216>`_.
945
+
946
+ * Fixed a potential segfault resulting from possible premature destruction of
947
+ ``py::args``/``py::kwargs`` arguments with overloaded functions.
948
+ `#1223 <https://github.com/pybind/pybind11/pull/1223>`_.
949
+
950
+ * Fixed ``del map[item]`` for a ``stl_bind.h`` bound stl map.
951
+ `#1229 <https://github.com/pybind/pybind11/pull/1229>`_.
952
+
953
+ * Fixed a regression from v2.1.x where the aggregate initialization could
954
+ unintentionally end up at a constructor taking a templated
955
+ ``std::initializer_list<T>`` argument.
956
+ `#1249 <https://github.com/pybind/pybind11/pull/1249>`_.
957
+
958
+ * Fixed an issue where calling a function with a keep_alive policy on the same
959
+ nurse/patient pair would cause the internal patient storage to needlessly
960
+ grow (unboundedly, if the nurse is long-lived).
961
+ `#1251 <https://github.com/pybind/pybind11/issues/1251>`_.
962
+
963
+ * Various other minor fixes.
964
+
965
+ v2.2.1 (September 14, 2017)
966
+ -----------------------------------------------------
967
+
968
+ * Added ``py::module_::reload()`` member function for reloading a module.
969
+ `#1040 <https://github.com/pybind/pybind11/pull/1040>`_.
970
+
971
+ * Fixed a reference leak in the number converter.
972
+ `#1078 <https://github.com/pybind/pybind11/pull/1078>`_.
973
+
974
+ * Fixed compilation with Clang on host GCC < 5 (old libstdc++ which isn't fully
975
+ C++11 compliant). `#1062 <https://github.com/pybind/pybind11/pull/1062>`_.
976
+
977
+ * Fixed a regression where the automatic ``std::vector<bool>`` caster would
978
+ fail to compile. The same fix also applies to any container which returns
979
+ element proxies instead of references.
980
+ `#1053 <https://github.com/pybind/pybind11/pull/1053>`_.
981
+
982
+ * Fixed a regression where the ``py::keep_alive`` policy could not be applied
983
+ to constructors. `#1065 <https://github.com/pybind/pybind11/pull/1065>`_.
984
+
985
+ * Fixed a nullptr dereference when loading a ``py::module_local`` type
986
+ that's only registered in an external module.
987
+ `#1058 <https://github.com/pybind/pybind11/pull/1058>`_.
988
+
989
+ * Fixed implicit conversion of accessors to types derived from ``py::object``.
990
+ `#1076 <https://github.com/pybind/pybind11/pull/1076>`_.
991
+
992
+ * The ``name`` in ``PYBIND11_MODULE(name, variable)`` can now be a macro.
993
+ `#1082 <https://github.com/pybind/pybind11/pull/1082>`_.
994
+
995
+ * Relaxed overly strict ``py::pickle()`` check for matching get and set types.
996
+ `#1064 <https://github.com/pybind/pybind11/pull/1064>`_.
997
+
998
+ * Conversion errors now try to be more informative when it's likely that
999
+ a missing header is the cause (e.g. forgetting ``<pybind11/stl.h>``).
1000
+ `#1077 <https://github.com/pybind/pybind11/pull/1077>`_.
1001
+
1002
+ v2.2.0 (August 31, 2017)
1003
+ -----------------------------------------------------
1004
+
1005
+ * Support for embedding the Python interpreter. See the
1006
+ :doc:`documentation page </advanced/embedding>` for a
1007
+ full overview of the new features.
1008
+ `#774 <https://github.com/pybind/pybind11/pull/774>`_,
1009
+ `#889 <https://github.com/pybind/pybind11/pull/889>`_,
1010
+ `#892 <https://github.com/pybind/pybind11/pull/892>`_,
1011
+ `#920 <https://github.com/pybind/pybind11/pull/920>`_.
1012
+
1013
+ .. code-block:: cpp
1014
+
1015
+ #include <pybind11/embed.h>
1016
+ namespace py = pybind11;
1017
+
1018
+ int main() {
1019
+ py::scoped_interpreter guard{}; // start the interpreter and keep it alive
1020
+
1021
+ py::print("Hello, World!"); // use the Python API
1022
+ }
1023
+
1024
+ * Support for inheriting from multiple C++ bases in Python.
1025
+ `#693 <https://github.com/pybind/pybind11/pull/693>`_.
1026
+
1027
+ .. code-block:: python
1028
+
1029
+ from cpp_module import CppBase1, CppBase2
1030
+
1031
+ class PyDerived(CppBase1, CppBase2):
1032
+ def __init__(self):
1033
+ CppBase1.__init__(self) # C++ bases must be initialized explicitly
1034
+ CppBase2.__init__(self)
1035
+
1036
+ * ``PYBIND11_MODULE`` is now the preferred way to create module entry points.
1037
+ ``PYBIND11_PLUGIN`` is deprecated. See :ref:`macros` for details.
1038
+ `#879 <https://github.com/pybind/pybind11/pull/879>`_.
1039
+
1040
+ .. code-block:: cpp
1041
+
1042
+ // new
1043
+ PYBIND11_MODULE(example, m) {
1044
+ m.def("add", [](int a, int b) { return a + b; });
1045
+ }
1046
+
1047
+ // old
1048
+ PYBIND11_PLUGIN(example) {
1049
+ py::module m("example");
1050
+ m.def("add", [](int a, int b) { return a + b; });
1051
+ return m.ptr();
1052
+ }
1053
+
1054
+ * pybind11's headers and build system now more strictly enforce hidden symbol
1055
+ visibility for extension modules. This should be seamless for most users,
1056
+ but see the :doc:`upgrade` if you use a custom build system.
1057
+ `#995 <https://github.com/pybind/pybind11/pull/995>`_.
1058
+
1059
+ * Support for ``py::module_local`` types which allow multiple modules to
1060
+ export the same C++ types without conflicts. This is useful for opaque
1061
+ types like ``std::vector<int>``. ``py::bind_vector`` and ``py::bind_map``
1062
+ now default to ``py::module_local`` if their elements are builtins or
1063
+ local types. See :ref:`module_local` for details.
1064
+ `#949 <https://github.com/pybind/pybind11/pull/949>`_,
1065
+ `#981 <https://github.com/pybind/pybind11/pull/981>`_,
1066
+ `#995 <https://github.com/pybind/pybind11/pull/995>`_,
1067
+ `#997 <https://github.com/pybind/pybind11/pull/997>`_.
1068
+
1069
+ * Custom constructors can now be added very easily using lambdas or factory
1070
+ functions which return a class instance by value, pointer or holder. This
1071
+ supersedes the old placement-new ``__init__`` technique.
1072
+ See :ref:`custom_constructors` for details.
1073
+ `#805 <https://github.com/pybind/pybind11/pull/805>`_,
1074
+ `#1014 <https://github.com/pybind/pybind11/pull/1014>`_.
1075
+
1076
+ .. code-block:: cpp
1077
+
1078
+ struct Example {
1079
+ Example(std::string);
1080
+ };
1081
+
1082
+ py::class_<Example>(m, "Example")
1083
+ .def(py::init<std::string>()) // existing constructor
1084
+ .def(py::init([](int n) { // custom constructor
1085
+ return std::make_unique<Example>(std::to_string(n));
1086
+ }));
1087
+
1088
+ * Similarly to custom constructors, pickling support functions are now bound
1089
+ using the ``py::pickle()`` adaptor which improves type safety. See the
1090
+ :doc:`upgrade` and :ref:`pickling` for details.
1091
+ `#1038 <https://github.com/pybind/pybind11/pull/1038>`_.
1092
+
1093
+ * Builtin support for converting C++17 standard library types and general
1094
+ conversion improvements:
1095
+
1096
+ 1. C++17 ``std::variant`` is supported right out of the box. C++11/14
1097
+ equivalents (e.g. ``boost::variant``) can also be added with a simple
1098
+ user-defined specialization. See :ref:`cpp17_container_casters` for details.
1099
+ `#811 <https://github.com/pybind/pybind11/pull/811>`_,
1100
+ `#845 <https://github.com/pybind/pybind11/pull/845>`_,
1101
+ `#989 <https://github.com/pybind/pybind11/pull/989>`_.
1102
+
1103
+ 2. Out-of-the-box support for C++17 ``std::string_view``.
1104
+ `#906 <https://github.com/pybind/pybind11/pull/906>`_.
1105
+
1106
+ 3. Improved compatibility of the builtin ``optional`` converter.
1107
+ `#874 <https://github.com/pybind/pybind11/pull/874>`_.
1108
+
1109
+ 4. The ``bool`` converter now accepts ``numpy.bool_`` and types which
1110
+ define ``__bool__`` (Python 3.x) or ``__nonzero__`` (Python 2.7).
1111
+ `#925 <https://github.com/pybind/pybind11/pull/925>`_.
1112
+
1113
+ 5. C++-to-Python casters are now more efficient and move elements out
1114
+ of rvalue containers whenever possible.
1115
+ `#851 <https://github.com/pybind/pybind11/pull/851>`_,
1116
+ `#936 <https://github.com/pybind/pybind11/pull/936>`_,
1117
+ `#938 <https://github.com/pybind/pybind11/pull/938>`_.
1118
+
1119
+ 6. Fixed ``bytes`` to ``std::string/char*`` conversion on Python 3.
1120
+ `#817 <https://github.com/pybind/pybind11/pull/817>`_.
1121
+
1122
+ 7. Fixed lifetime of temporary C++ objects created in Python-to-C++ conversions.
1123
+ `#924 <https://github.com/pybind/pybind11/pull/924>`_.
1124
+
1125
+ * Scope guard call policy for RAII types, e.g. ``py::call_guard<py::gil_scoped_release>()``,
1126
+ ``py::call_guard<py::scoped_ostream_redirect>()``. See :ref:`call_policies` for details.
1127
+ `#740 <https://github.com/pybind/pybind11/pull/740>`_.
1128
+
1129
+ * Utility for redirecting C++ streams to Python (e.g. ``std::cout`` ->
1130
+ ``sys.stdout``). Scope guard ``py::scoped_ostream_redirect`` in C++ and
1131
+ a context manager in Python. See :ref:`ostream_redirect`.
1132
+ `#1009 <https://github.com/pybind/pybind11/pull/1009>`_.
1133
+
1134
+ * Improved handling of types and exceptions across module boundaries.
1135
+ `#915 <https://github.com/pybind/pybind11/pull/915>`_,
1136
+ `#951 <https://github.com/pybind/pybind11/pull/951>`_,
1137
+ `#995 <https://github.com/pybind/pybind11/pull/995>`_.
1138
+
1139
+ * Fixed destruction order of ``py::keep_alive`` nurse/patient objects
1140
+ in reference cycles.
1141
+ `#856 <https://github.com/pybind/pybind11/pull/856>`_.
1142
+
1143
+ * NumPy and buffer protocol related improvements:
1144
+
1145
+ 1. Support for negative strides in Python buffer objects/numpy arrays. This
1146
+ required changing integers from unsigned to signed for the related C++ APIs.
1147
+ Note: If you have compiler warnings enabled, you may notice some new conversion
1148
+ warnings after upgrading. These can be resolved with ``static_cast``.
1149
+ `#782 <https://github.com/pybind/pybind11/pull/782>`_.
1150
+
1151
+ 2. Support ``std::complex`` and arrays inside ``PYBIND11_NUMPY_DTYPE``.
1152
+ `#831 <https://github.com/pybind/pybind11/pull/831>`_,
1153
+ `#832 <https://github.com/pybind/pybind11/pull/832>`_.
1154
+
1155
+ 3. Support for constructing ``py::buffer_info`` and ``py::arrays`` using
1156
+ arbitrary containers or iterators instead of requiring a ``std::vector``.
1157
+ `#788 <https://github.com/pybind/pybind11/pull/788>`_,
1158
+ `#822 <https://github.com/pybind/pybind11/pull/822>`_,
1159
+ `#860 <https://github.com/pybind/pybind11/pull/860>`_.
1160
+
1161
+ 4. Explicitly check numpy version and require >= 1.7.0.
1162
+ `#819 <https://github.com/pybind/pybind11/pull/819>`_.
1163
+
1164
+ * Support for allowing/prohibiting ``None`` for specific arguments and improved
1165
+ ``None`` overload resolution order. See :ref:`none_arguments` for details.
1166
+ `#843 <https://github.com/pybind/pybind11/pull/843>`_.
1167
+ `#859 <https://github.com/pybind/pybind11/pull/859>`_.
1168
+
1169
+ * Added ``py::exec()`` as a shortcut for ``py::eval<py::eval_statements>()``
1170
+ and support for C++11 raw string literals as input. See :ref:`eval`.
1171
+ `#766 <https://github.com/pybind/pybind11/pull/766>`_,
1172
+ `#827 <https://github.com/pybind/pybind11/pull/827>`_.
1173
+
1174
+ * ``py::vectorize()`` ignores non-vectorizable arguments and supports
1175
+ member functions.
1176
+ `#762 <https://github.com/pybind/pybind11/pull/762>`_.
1177
+
1178
+ * Support for bound methods as callbacks (``pybind11/functional.h``).
1179
+ `#815 <https://github.com/pybind/pybind11/pull/815>`_.
1180
+
1181
+ * Allow aliasing pybind11 methods: ``cls.attr("foo") = cls.attr("bar")``.
1182
+ `#802 <https://github.com/pybind/pybind11/pull/802>`_.
1183
+
1184
+ * Don't allow mixed static/non-static overloads.
1185
+ `#804 <https://github.com/pybind/pybind11/pull/804>`_.
1186
+
1187
+ * Fixed overriding static properties in derived classes.
1188
+ `#784 <https://github.com/pybind/pybind11/pull/784>`_.
1189
+
1190
+ * Added support for write only properties.
1191
+ `#1144 <https://github.com/pybind/pybind11/pull/1144>`_.
1192
+
1193
+ * Improved deduction of member functions of a derived class when its bases
1194
+ aren't registered with pybind11.
1195
+ `#855 <https://github.com/pybind/pybind11/pull/855>`_.
1196
+
1197
+ .. code-block:: cpp
1198
+
1199
+ struct Base {
1200
+ int foo() { return 42; }
1201
+ }
1202
+
1203
+ struct Derived : Base {}
1204
+
1205
+ // Now works, but previously required also binding `Base`
1206
+ py::class_<Derived>(m, "Derived")
1207
+ .def("foo", &Derived::foo); // function is actually from `Base`
1208
+
1209
+ * The implementation of ``py::init<>`` now uses C++11 brace initialization
1210
+ syntax to construct instances, which permits binding implicit constructors of
1211
+ aggregate types. `#1015 <https://github.com/pybind/pybind11/pull/1015>`_.
1212
+
1213
+ .. code-block:: cpp
1214
+
1215
+ struct Aggregate {
1216
+ int a;
1217
+ std::string b;
1218
+ };
1219
+
1220
+ py::class_<Aggregate>(m, "Aggregate")
1221
+ .def(py::init<int, const std::string &>());
1222
+
1223
+ * Fixed issues with multiple inheritance with offset base/derived pointers.
1224
+ `#812 <https://github.com/pybind/pybind11/pull/812>`_,
1225
+ `#866 <https://github.com/pybind/pybind11/pull/866>`_,
1226
+ `#960 <https://github.com/pybind/pybind11/pull/960>`_.
1227
+
1228
+ * Fixed reference leak of type objects.
1229
+ `#1030 <https://github.com/pybind/pybind11/pull/1030>`_.
1230
+
1231
+ * Improved support for the ``/std:c++14`` and ``/std:c++latest`` modes
1232
+ on MSVC 2017.
1233
+ `#841 <https://github.com/pybind/pybind11/pull/841>`_,
1234
+ `#999 <https://github.com/pybind/pybind11/pull/999>`_.
1235
+
1236
+ * Fixed detection of private operator new on MSVC.
1237
+ `#893 <https://github.com/pybind/pybind11/pull/893>`_,
1238
+ `#918 <https://github.com/pybind/pybind11/pull/918>`_.
1239
+
1240
+ * Intel C++ compiler compatibility fixes.
1241
+ `#937 <https://github.com/pybind/pybind11/pull/937>`_.
1242
+
1243
+ * Fixed implicit conversion of `py::enum_` to integer types on Python 2.7.
1244
+ `#821 <https://github.com/pybind/pybind11/pull/821>`_.
1245
+
1246
+ * Added ``py::hash`` to fetch the hash value of Python objects, and
1247
+ ``.def(hash(py::self))`` to provide the C++ ``std::hash`` as the Python
1248
+ ``__hash__`` method.
1249
+ `#1034 <https://github.com/pybind/pybind11/pull/1034>`_.
1250
+
1251
+ * Fixed ``__truediv__`` on Python 2 and ``__itruediv__`` on Python 3.
1252
+ `#867 <https://github.com/pybind/pybind11/pull/867>`_.
1253
+
1254
+ * ``py::capsule`` objects now support the ``name`` attribute. This is useful
1255
+ for interfacing with ``scipy.LowLevelCallable``.
1256
+ `#902 <https://github.com/pybind/pybind11/pull/902>`_.
1257
+
1258
+ * Fixed ``py::make_iterator``'s ``__next__()`` for past-the-end calls.
1259
+ `#897 <https://github.com/pybind/pybind11/pull/897>`_.
1260
+
1261
+ * Added ``error_already_set::matches()`` for checking Python exceptions.
1262
+ `#772 <https://github.com/pybind/pybind11/pull/772>`_.
1263
+
1264
+ * Deprecated ``py::error_already_set::clear()``. It's no longer needed
1265
+ following a simplification of the ``py::error_already_set`` class.
1266
+ `#954 <https://github.com/pybind/pybind11/pull/954>`_.
1267
+
1268
+ * Deprecated ``py::handle::operator==()`` in favor of ``py::handle::is()``
1269
+ `#825 <https://github.com/pybind/pybind11/pull/825>`_.
1270
+
1271
+ * Deprecated ``py::object::borrowed``/``py::object::stolen``.
1272
+ Use ``py::object::borrowed_t{}``/``py::object::stolen_t{}`` instead.
1273
+ `#771 <https://github.com/pybind/pybind11/pull/771>`_.
1274
+
1275
+ * Changed internal data structure versioning to avoid conflicts between
1276
+ modules compiled with different revisions of pybind11.
1277
+ `#1012 <https://github.com/pybind/pybind11/pull/1012>`_.
1278
+
1279
+ * Additional compile-time and run-time error checking and more informative messages.
1280
+ `#786 <https://github.com/pybind/pybind11/pull/786>`_,
1281
+ `#794 <https://github.com/pybind/pybind11/pull/794>`_,
1282
+ `#803 <https://github.com/pybind/pybind11/pull/803>`_.
1283
+
1284
+ * Various minor improvements and fixes.
1285
+ `#764 <https://github.com/pybind/pybind11/pull/764>`_,
1286
+ `#791 <https://github.com/pybind/pybind11/pull/791>`_,
1287
+ `#795 <https://github.com/pybind/pybind11/pull/795>`_,
1288
+ `#840 <https://github.com/pybind/pybind11/pull/840>`_,
1289
+ `#844 <https://github.com/pybind/pybind11/pull/844>`_,
1290
+ `#846 <https://github.com/pybind/pybind11/pull/846>`_,
1291
+ `#849 <https://github.com/pybind/pybind11/pull/849>`_,
1292
+ `#858 <https://github.com/pybind/pybind11/pull/858>`_,
1293
+ `#862 <https://github.com/pybind/pybind11/pull/862>`_,
1294
+ `#871 <https://github.com/pybind/pybind11/pull/871>`_,
1295
+ `#872 <https://github.com/pybind/pybind11/pull/872>`_,
1296
+ `#881 <https://github.com/pybind/pybind11/pull/881>`_,
1297
+ `#888 <https://github.com/pybind/pybind11/pull/888>`_,
1298
+ `#899 <https://github.com/pybind/pybind11/pull/899>`_,
1299
+ `#928 <https://github.com/pybind/pybind11/pull/928>`_,
1300
+ `#931 <https://github.com/pybind/pybind11/pull/931>`_,
1301
+ `#944 <https://github.com/pybind/pybind11/pull/944>`_,
1302
+ `#950 <https://github.com/pybind/pybind11/pull/950>`_,
1303
+ `#952 <https://github.com/pybind/pybind11/pull/952>`_,
1304
+ `#962 <https://github.com/pybind/pybind11/pull/962>`_,
1305
+ `#965 <https://github.com/pybind/pybind11/pull/965>`_,
1306
+ `#970 <https://github.com/pybind/pybind11/pull/970>`_,
1307
+ `#978 <https://github.com/pybind/pybind11/pull/978>`_,
1308
+ `#979 <https://github.com/pybind/pybind11/pull/979>`_,
1309
+ `#986 <https://github.com/pybind/pybind11/pull/986>`_,
1310
+ `#1020 <https://github.com/pybind/pybind11/pull/1020>`_,
1311
+ `#1027 <https://github.com/pybind/pybind11/pull/1027>`_,
1312
+ `#1037 <https://github.com/pybind/pybind11/pull/1037>`_.
1313
+
1314
+ * Testing improvements.
1315
+ `#798 <https://github.com/pybind/pybind11/pull/798>`_,
1316
+ `#882 <https://github.com/pybind/pybind11/pull/882>`_,
1317
+ `#898 <https://github.com/pybind/pybind11/pull/898>`_,
1318
+ `#900 <https://github.com/pybind/pybind11/pull/900>`_,
1319
+ `#921 <https://github.com/pybind/pybind11/pull/921>`_,
1320
+ `#923 <https://github.com/pybind/pybind11/pull/923>`_,
1321
+ `#963 <https://github.com/pybind/pybind11/pull/963>`_.
1322
+
1323
+ v2.1.1 (April 7, 2017)
1324
+ -----------------------------------------------------
1325
+
1326
+ * Fixed minimum version requirement for MSVC 2015u3
1327
+ `#773 <https://github.com/pybind/pybind11/pull/773>`_.
1328
+
1329
+ v2.1.0 (March 22, 2017)
1330
+ -----------------------------------------------------
1331
+
1332
+ * pybind11 now performs function overload resolution in two phases. The first
1333
+ phase only considers exact type matches, while the second allows for implicit
1334
+ conversions to take place. A special ``noconvert()`` syntax can be used to
1335
+ completely disable implicit conversions for specific arguments.
1336
+ `#643 <https://github.com/pybind/pybind11/pull/643>`_,
1337
+ `#634 <https://github.com/pybind/pybind11/pull/634>`_,
1338
+ `#650 <https://github.com/pybind/pybind11/pull/650>`_.
1339
+
1340
+ * Fixed a regression where static properties no longer worked with classes
1341
+ using multiple inheritance. The ``py::metaclass`` attribute is no longer
1342
+ necessary (and deprecated as of this release) when binding classes with
1343
+ static properties.
1344
+ `#679 <https://github.com/pybind/pybind11/pull/679>`_,
1345
+
1346
+ * Classes bound using ``pybind11`` can now use custom metaclasses.
1347
+ `#679 <https://github.com/pybind/pybind11/pull/679>`_,
1348
+
1349
+ * ``py::args`` and ``py::kwargs`` can now be mixed with other positional
1350
+ arguments when binding functions using pybind11.
1351
+ `#611 <https://github.com/pybind/pybind11/pull/611>`_.
1352
+
1353
+ * Improved support for C++11 unicode string and character types; added
1354
+ extensive documentation regarding pybind11's string conversion behavior.
1355
+ `#624 <https://github.com/pybind/pybind11/pull/624>`_,
1356
+ `#636 <https://github.com/pybind/pybind11/pull/636>`_,
1357
+ `#715 <https://github.com/pybind/pybind11/pull/715>`_.
1358
+
1359
+ * pybind11 can now avoid expensive copies when converting Eigen arrays to NumPy
1360
+ arrays (and vice versa). `#610 <https://github.com/pybind/pybind11/pull/610>`_.
1361
+
1362
+ * The "fast path" in ``py::vectorize`` now works for any full-size group of C or
1363
+ F-contiguous arrays. The non-fast path is also faster since it no longer performs
1364
+ copies of the input arguments (except when type conversions are necessary).
1365
+ `#610 <https://github.com/pybind/pybind11/pull/610>`_.
1366
+
1367
+ * Added fast, unchecked access to NumPy arrays via a proxy object.
1368
+ `#746 <https://github.com/pybind/pybind11/pull/746>`_.
1369
+
1370
+ * Transparent support for class-specific ``operator new`` and
1371
+ ``operator delete`` implementations.
1372
+ `#755 <https://github.com/pybind/pybind11/pull/755>`_.
1373
+
1374
+ * Slimmer and more efficient STL-compatible iterator interface for sequence types.
1375
+ `#662 <https://github.com/pybind/pybind11/pull/662>`_.
1376
+
1377
+ * Improved custom holder type support.
1378
+ `#607 <https://github.com/pybind/pybind11/pull/607>`_.
1379
+
1380
+ * ``nullptr`` to ``None`` conversion fixed in various builtin type casters.
1381
+ `#732 <https://github.com/pybind/pybind11/pull/732>`_.
1382
+
1383
+ * ``enum_`` now exposes its members via a special ``__members__`` attribute.
1384
+ `#666 <https://github.com/pybind/pybind11/pull/666>`_.
1385
+
1386
+ * ``std::vector`` bindings created using ``stl_bind.h`` can now optionally
1387
+ implement the buffer protocol. `#488 <https://github.com/pybind/pybind11/pull/488>`_.
1388
+
1389
+ * Automated C++ reference documentation using doxygen and breathe.
1390
+ `#598 <https://github.com/pybind/pybind11/pull/598>`_.
1391
+
1392
+ * Added minimum compiler version assertions.
1393
+ `#727 <https://github.com/pybind/pybind11/pull/727>`_.
1394
+
1395
+ * Improved compatibility with C++1z.
1396
+ `#677 <https://github.com/pybind/pybind11/pull/677>`_.
1397
+
1398
+ * Improved ``py::capsule`` API. Can be used to implement cleanup
1399
+ callbacks that are involved at module destruction time.
1400
+ `#752 <https://github.com/pybind/pybind11/pull/752>`_.
1401
+
1402
+ * Various minor improvements and fixes.
1403
+ `#595 <https://github.com/pybind/pybind11/pull/595>`_,
1404
+ `#588 <https://github.com/pybind/pybind11/pull/588>`_,
1405
+ `#589 <https://github.com/pybind/pybind11/pull/589>`_,
1406
+ `#603 <https://github.com/pybind/pybind11/pull/603>`_,
1407
+ `#619 <https://github.com/pybind/pybind11/pull/619>`_,
1408
+ `#648 <https://github.com/pybind/pybind11/pull/648>`_,
1409
+ `#695 <https://github.com/pybind/pybind11/pull/695>`_,
1410
+ `#720 <https://github.com/pybind/pybind11/pull/720>`_,
1411
+ `#723 <https://github.com/pybind/pybind11/pull/723>`_,
1412
+ `#729 <https://github.com/pybind/pybind11/pull/729>`_,
1413
+ `#724 <https://github.com/pybind/pybind11/pull/724>`_,
1414
+ `#742 <https://github.com/pybind/pybind11/pull/742>`_,
1415
+ `#753 <https://github.com/pybind/pybind11/pull/753>`_.
1416
+
1417
+ v2.0.1 (Jan 4, 2017)
1418
+ -----------------------------------------------------
1419
+
1420
+ * Fix pointer to reference error in type_caster on MSVC
1421
+ `#583 <https://github.com/pybind/pybind11/pull/583>`_.
1422
+
1423
+ * Fixed a segmentation in the test suite due to a typo
1424
+ `cd7eac <https://github.com/pybind/pybind11/commit/cd7eac>`_.
1425
+
1426
+ v2.0.0 (Jan 1, 2017)
1427
+ -----------------------------------------------------
1428
+
1429
+ * Fixed a reference counting regression affecting types with custom metaclasses
1430
+ (introduced in v2.0.0-rc1).
1431
+ `#571 <https://github.com/pybind/pybind11/pull/571>`_.
1432
+
1433
+ * Quenched a CMake policy warning.
1434
+ `#570 <https://github.com/pybind/pybind11/pull/570>`_.
1435
+
1436
+ v2.0.0-rc1 (Dec 23, 2016)
1437
+ -----------------------------------------------------
1438
+
1439
+ The pybind11 developers are excited to issue a release candidate of pybind11
1440
+ with a subsequent v2.0.0 release planned in early January next year.
1441
+
1442
+ An incredible amount of effort by went into pybind11 over the last ~5 months,
1443
+ leading to a release that is jam-packed with exciting new features and numerous
1444
+ usability improvements. The following list links PRs or individual commits
1445
+ whenever applicable.
1446
+
1447
+ Happy Christmas!
1448
+
1449
+ * Support for binding C++ class hierarchies that make use of multiple
1450
+ inheritance. `#410 <https://github.com/pybind/pybind11/pull/410>`_.
1451
+
1452
+ * PyPy support: pybind11 now supports nightly builds of PyPy and will
1453
+ interoperate with the future 5.7 release. No code changes are necessary,
1454
+ everything "just" works as usual. Note that we only target the Python 2.7
1455
+ branch for now; support for 3.x will be added once its ``cpyext`` extension
1456
+ support catches up. A few minor features remain unsupported for the time
1457
+ being (notably dynamic attributes in custom types).
1458
+ `#527 <https://github.com/pybind/pybind11/pull/527>`_.
1459
+
1460
+ * Significant work on the documentation -- in particular, the monolithic
1461
+ ``advanced.rst`` file was restructured into a easier to read hierarchical
1462
+ organization. `#448 <https://github.com/pybind/pybind11/pull/448>`_.
1463
+
1464
+ * Many NumPy-related improvements:
1465
+
1466
+ 1. Object-oriented API to access and modify NumPy ``ndarray`` instances,
1467
+ replicating much of the corresponding NumPy C API functionality.
1468
+ `#402 <https://github.com/pybind/pybind11/pull/402>`_.
1469
+
1470
+ 2. NumPy array ``dtype`` array descriptors are now first-class citizens and
1471
+ are exposed via a new class ``py::dtype``.
1472
+
1473
+ 3. Structured dtypes can be registered using the ``PYBIND11_NUMPY_DTYPE()``
1474
+ macro. Special ``array`` constructors accepting dtype objects were also
1475
+ added.
1476
+
1477
+ One potential caveat involving this change: format descriptor strings
1478
+ should now be accessed via ``format_descriptor::format()`` (however, for
1479
+ compatibility purposes, the old syntax ``format_descriptor::value`` will
1480
+ still work for non-structured data types). `#308
1481
+ <https://github.com/pybind/pybind11/pull/308>`_.
1482
+
1483
+ 4. Further improvements to support structured dtypes throughout the system.
1484
+ `#472 <https://github.com/pybind/pybind11/pull/472>`_,
1485
+ `#474 <https://github.com/pybind/pybind11/pull/474>`_,
1486
+ `#459 <https://github.com/pybind/pybind11/pull/459>`_,
1487
+ `#453 <https://github.com/pybind/pybind11/pull/453>`_,
1488
+ `#452 <https://github.com/pybind/pybind11/pull/452>`_, and
1489
+ `#505 <https://github.com/pybind/pybind11/pull/505>`_.
1490
+
1491
+ 5. Fast access operators. `#497 <https://github.com/pybind/pybind11/pull/497>`_.
1492
+
1493
+ 6. Constructors for arrays whose storage is owned by another object.
1494
+ `#440 <https://github.com/pybind/pybind11/pull/440>`_.
1495
+
1496
+ 7. Added constructors for ``array`` and ``array_t`` explicitly accepting shape
1497
+ and strides; if strides are not provided, they are deduced assuming
1498
+ C-contiguity. Also added simplified constructors for 1-dimensional case.
1499
+
1500
+ 8. Added buffer/NumPy support for ``char[N]`` and ``std::array<char, N>`` types.
1501
+
1502
+ 9. Added ``memoryview`` wrapper type which is constructible from ``buffer_info``.
1503
+
1504
+ * Eigen: many additional conversions and support for non-contiguous
1505
+ arrays/slices.
1506
+ `#427 <https://github.com/pybind/pybind11/pull/427>`_,
1507
+ `#315 <https://github.com/pybind/pybind11/pull/315>`_,
1508
+ `#316 <https://github.com/pybind/pybind11/pull/316>`_,
1509
+ `#312 <https://github.com/pybind/pybind11/pull/312>`_, and
1510
+ `#267 <https://github.com/pybind/pybind11/pull/267>`_
1511
+
1512
+ * Incompatible changes in ``class_<...>::class_()``:
1513
+
1514
+ 1. Declarations of types that provide access via the buffer protocol must
1515
+ now include the ``py::buffer_protocol()`` annotation as an argument to
1516
+ the ``class_`` constructor.
1517
+
1518
+ 2. Declarations of types that require a custom metaclass (i.e. all classes
1519
+ which include static properties via commands such as
1520
+ ``def_readwrite_static()``) must now include the ``py::metaclass()``
1521
+ annotation as an argument to the ``class_`` constructor.
1522
+
1523
+ These two changes were necessary to make type definitions in pybind11
1524
+ future-proof, and to support PyPy via its cpyext mechanism. `#527
1525
+ <https://github.com/pybind/pybind11/pull/527>`_.
1526
+
1527
+
1528
+ 3. This version of pybind11 uses a redesigned mechanism for instantiating
1529
+ trampoline classes that are used to override virtual methods from within
1530
+ Python. This led to the following user-visible syntax change: instead of
1531
+
1532
+ .. code-block:: cpp
1533
+
1534
+ py::class_<TrampolineClass>("MyClass")
1535
+ .alias<MyClass>()
1536
+ ....
1537
+
1538
+ write
1539
+
1540
+ .. code-block:: cpp
1541
+
1542
+ py::class_<MyClass, TrampolineClass>("MyClass")
1543
+ ....
1544
+
1545
+ Importantly, both the original and the trampoline class are now
1546
+ specified as an arguments (in arbitrary order) to the ``py::class_``
1547
+ template, and the ``alias<..>()`` call is gone. The new scheme has zero
1548
+ overhead in cases when Python doesn't override any functions of the
1549
+ underlying C++ class. `rev. 86d825
1550
+ <https://github.com/pybind/pybind11/commit/86d825>`_.
1551
+
1552
+ * Added ``eval`` and ``eval_file`` functions for evaluating expressions and
1553
+ statements from a string or file. `rev. 0d3fc3
1554
+ <https://github.com/pybind/pybind11/commit/0d3fc3>`_.
1555
+
1556
+ * pybind11 can now create types with a modifiable dictionary.
1557
+ `#437 <https://github.com/pybind/pybind11/pull/437>`_ and
1558
+ `#444 <https://github.com/pybind/pybind11/pull/444>`_.
1559
+
1560
+ * Support for translation of arbitrary C++ exceptions to Python counterparts.
1561
+ `#296 <https://github.com/pybind/pybind11/pull/296>`_ and
1562
+ `#273 <https://github.com/pybind/pybind11/pull/273>`_.
1563
+
1564
+ * Report full backtraces through mixed C++/Python code, better reporting for
1565
+ import errors, fixed GIL management in exception processing.
1566
+ `#537 <https://github.com/pybind/pybind11/pull/537>`_,
1567
+ `#494 <https://github.com/pybind/pybind11/pull/494>`_,
1568
+ `rev. e72d95 <https://github.com/pybind/pybind11/commit/e72d95>`_, and
1569
+ `rev. 099d6e <https://github.com/pybind/pybind11/commit/099d6e>`_.
1570
+
1571
+ * Support for bit-level operations, comparisons, and serialization of C++
1572
+ enumerations. `#503 <https://github.com/pybind/pybind11/pull/503>`_,
1573
+ `#508 <https://github.com/pybind/pybind11/pull/508>`_,
1574
+ `#380 <https://github.com/pybind/pybind11/pull/380>`_,
1575
+ `#309 <https://github.com/pybind/pybind11/pull/309>`_.
1576
+ `#311 <https://github.com/pybind/pybind11/pull/311>`_.
1577
+
1578
+ * The ``class_`` constructor now accepts its template arguments in any order.
1579
+ `#385 <https://github.com/pybind/pybind11/pull/385>`_.
1580
+
1581
+ * Attribute and item accessors now have a more complete interface which makes
1582
+ it possible to chain attributes as in
1583
+ ``obj.attr("a")[key].attr("b").attr("method")(1, 2, 3)``. `#425
1584
+ <https://github.com/pybind/pybind11/pull/425>`_.
1585
+
1586
+ * Major redesign of the default and conversion constructors in ``pytypes.h``.
1587
+ `#464 <https://github.com/pybind/pybind11/pull/464>`_.
1588
+
1589
+ * Added built-in support for ``std::shared_ptr`` holder type. It is no longer
1590
+ necessary to to include a declaration of the form
1591
+ ``PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)`` (though continuing to
1592
+ do so won't cause an error).
1593
+ `#454 <https://github.com/pybind/pybind11/pull/454>`_.
1594
+
1595
+ * New ``py::overload_cast`` casting operator to select among multiple possible
1596
+ overloads of a function. An example:
1597
+
1598
+ .. code-block:: cpp
1599
+
1600
+ py::class_<Pet>(m, "Pet")
1601
+ .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
1602
+ .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
1603
+
1604
+ This feature only works on C++14-capable compilers.
1605
+ `#541 <https://github.com/pybind/pybind11/pull/541>`_.
1606
+
1607
+ * C++ types are automatically cast to Python types, e.g. when assigning
1608
+ them as an attribute. For instance, the following is now legal:
1609
+
1610
+ .. code-block:: cpp
1611
+
1612
+ py::module m = /* ... */
1613
+ m.attr("constant") = 123;
1614
+
1615
+ (Previously, a ``py::cast`` call was necessary to avoid a compilation error.)
1616
+ `#551 <https://github.com/pybind/pybind11/pull/551>`_.
1617
+
1618
+ * Redesigned ``pytest``-based test suite. `#321 <https://github.com/pybind/pybind11/pull/321>`_.
1619
+
1620
+ * Instance tracking to detect reference leaks in test suite. `#324 <https://github.com/pybind/pybind11/pull/324>`_
1621
+
1622
+ * pybind11 can now distinguish between multiple different instances that are
1623
+ located at the same memory address, but which have different types.
1624
+ `#329 <https://github.com/pybind/pybind11/pull/329>`_.
1625
+
1626
+ * Improved logic in ``move`` return value policy.
1627
+ `#510 <https://github.com/pybind/pybind11/pull/510>`_,
1628
+ `#297 <https://github.com/pybind/pybind11/pull/297>`_.
1629
+
1630
+ * Generalized unpacking API to permit calling Python functions from C++ using
1631
+ notation such as ``foo(a1, a2, *args, "ka"_a=1, "kb"_a=2, **kwargs)``. `#372 <https://github.com/pybind/pybind11/pull/372>`_.
1632
+
1633
+ * ``py::print()`` function whose behavior matches that of the native Python
1634
+ ``print()`` function. `#372 <https://github.com/pybind/pybind11/pull/372>`_.
1635
+
1636
+ * Added ``py::dict`` keyword constructor:``auto d = dict("number"_a=42,
1637
+ "name"_a="World");``. `#372 <https://github.com/pybind/pybind11/pull/372>`_.
1638
+
1639
+ * Added ``py::str::format()`` method and ``_s`` literal: ``py::str s = "1 + 2
1640
+ = {}"_s.format(3);``. `#372 <https://github.com/pybind/pybind11/pull/372>`_.
1641
+
1642
+ * Added ``py::repr()`` function which is equivalent to Python's builtin
1643
+ ``repr()``. `#333 <https://github.com/pybind/pybind11/pull/333>`_.
1644
+
1645
+ * Improved construction and destruction logic for holder types. It is now
1646
+ possible to reference instances with smart pointer holder types without
1647
+ constructing the holder if desired. The ``PYBIND11_DECLARE_HOLDER_TYPE``
1648
+ macro now accepts an optional second parameter to indicate whether the holder
1649
+ type uses intrusive reference counting.
1650
+ `#533 <https://github.com/pybind/pybind11/pull/533>`_ and
1651
+ `#561 <https://github.com/pybind/pybind11/pull/561>`_.
1652
+
1653
+ * Mapping a stateless C++ function to Python and back is now "for free" (i.e.
1654
+ no extra indirections or argument conversion overheads). `rev. 954b79
1655
+ <https://github.com/pybind/pybind11/commit/954b79>`_.
1656
+
1657
+ * Bindings for ``std::valarray<T>``.
1658
+ `#545 <https://github.com/pybind/pybind11/pull/545>`_.
1659
+
1660
+ * Improved support for C++17 capable compilers.
1661
+ `#562 <https://github.com/pybind/pybind11/pull/562>`_.
1662
+
1663
+ * Bindings for ``std::optional<t>``.
1664
+ `#475 <https://github.com/pybind/pybind11/pull/475>`_,
1665
+ `#476 <https://github.com/pybind/pybind11/pull/476>`_,
1666
+ `#479 <https://github.com/pybind/pybind11/pull/479>`_,
1667
+ `#499 <https://github.com/pybind/pybind11/pull/499>`_, and
1668
+ `#501 <https://github.com/pybind/pybind11/pull/501>`_.
1669
+
1670
+ * ``stl_bind.h``: general improvements and support for ``std::map`` and
1671
+ ``std::unordered_map``.
1672
+ `#490 <https://github.com/pybind/pybind11/pull/490>`_,
1673
+ `#282 <https://github.com/pybind/pybind11/pull/282>`_,
1674
+ `#235 <https://github.com/pybind/pybind11/pull/235>`_.
1675
+
1676
+ * The ``std::tuple``, ``std::pair``, ``std::list``, and ``std::vector`` type
1677
+ casters now accept any Python sequence type as input. `rev. 107285
1678
+ <https://github.com/pybind/pybind11/commit/107285>`_.
1679
+
1680
+ * Improved CMake Python detection on multi-architecture Linux.
1681
+ `#532 <https://github.com/pybind/pybind11/pull/532>`_.
1682
+
1683
+ * Infrastructure to selectively disable or enable parts of the automatically
1684
+ generated docstrings. `#486 <https://github.com/pybind/pybind11/pull/486>`_.
1685
+
1686
+ * ``reference`` and ``reference_internal`` are now the default return value
1687
+ properties for static and non-static properties, respectively. `#473
1688
+ <https://github.com/pybind/pybind11/pull/473>`_. (the previous defaults
1689
+ were ``automatic``). `#473 <https://github.com/pybind/pybind11/pull/473>`_.
1690
+
1691
+ * Support for ``std::unique_ptr`` with non-default deleters or no deleter at
1692
+ all (``py::nodelete``). `#384 <https://github.com/pybind/pybind11/pull/384>`_.
1693
+
1694
+ * Deprecated ``handle::call()`` method. The new syntax to call Python
1695
+ functions is simply ``handle()``. It can also be invoked explicitly via
1696
+ ``handle::operator<X>()``, where ``X`` is an optional return value policy.
1697
+
1698
+ * Print more informative error messages when ``make_tuple()`` or ``cast()``
1699
+ fail. `#262 <https://github.com/pybind/pybind11/pull/262>`_.
1700
+
1701
+ * Creation of holder types for classes deriving from
1702
+ ``std::enable_shared_from_this<>`` now also works for ``const`` values.
1703
+ `#260 <https://github.com/pybind/pybind11/pull/260>`_.
1704
+
1705
+ * ``make_iterator()`` improvements for better compatibility with various
1706
+ types (now uses prefix increment operator); it now also accepts iterators
1707
+ with different begin/end types as long as they are equality comparable.
1708
+ `#247 <https://github.com/pybind/pybind11/pull/247>`_.
1709
+
1710
+ * ``arg()`` now accepts a wider range of argument types for default values.
1711
+ `#244 <https://github.com/pybind/pybind11/pull/244>`_.
1712
+
1713
+ * Support ``keep_alive`` where the nurse object may be ``None``. `#341
1714
+ <https://github.com/pybind/pybind11/pull/341>`_.
1715
+
1716
+ * Added constructors for ``str`` and ``bytes`` from zero-terminated char
1717
+ pointers, and from char pointers and length. Added constructors for ``str``
1718
+ from ``bytes`` and for ``bytes`` from ``str``, which will perform UTF-8
1719
+ decoding/encoding as required.
1720
+
1721
+ * Many other improvements of library internals without user-visible changes
1722
+
1723
+
1724
+ 1.8.1 (July 12, 2016)
1725
+ ----------------------
1726
+ * Fixed a rare but potentially very severe issue when the garbage collector ran
1727
+ during pybind11 type creation.
1728
+
1729
+ 1.8.0 (June 14, 2016)
1730
+ ----------------------
1731
+ * Redesigned CMake build system which exports a convenient
1732
+ ``pybind11_add_module`` function to parent projects.
1733
+ * ``std::vector<>`` type bindings analogous to Boost.Python's ``indexing_suite``
1734
+ * Transparent conversion of sparse and dense Eigen matrices and vectors (``eigen.h``)
1735
+ * Added an ``ExtraFlags`` template argument to the NumPy ``array_t<>`` wrapper
1736
+ to disable an enforced cast that may lose precision, e.g. to create overloads
1737
+ for different precisions and complex vs real-valued matrices.
1738
+ * Prevent implicit conversion of floating point values to integral types in
1739
+ function arguments
1740
+ * Fixed incorrect default return value policy for functions returning a shared
1741
+ pointer
1742
+ * Don't allow registering a type via ``class_`` twice
1743
+ * Don't allow casting a ``None`` value into a C++ lvalue reference
1744
+ * Fixed a crash in ``enum_::operator==`` that was triggered by the ``help()`` command
1745
+ * Improved detection of whether or not custom C++ types can be copy/move-constructed
1746
+ * Extended ``str`` type to also work with ``bytes`` instances
1747
+ * Added a ``"name"_a`` user defined string literal that is equivalent to ``py::arg("name")``.
1748
+ * When specifying function arguments via ``py::arg``, the test that verifies
1749
+ the number of arguments now runs at compile time.
1750
+ * Added ``[[noreturn]]`` attribute to ``pybind11_fail()`` to quench some
1751
+ compiler warnings
1752
+ * List function arguments in exception text when the dispatch code cannot find
1753
+ a matching overload
1754
+ * Added ``PYBIND11_OVERLOAD_NAME`` and ``PYBIND11_OVERLOAD_PURE_NAME`` macros which
1755
+ can be used to override virtual methods whose name differs in C++ and Python
1756
+ (e.g. ``__call__`` and ``operator()``)
1757
+ * Various minor ``iterator`` and ``make_iterator()`` improvements
1758
+ * Transparently support ``__bool__`` on Python 2.x and Python 3.x
1759
+ * Fixed issue with destructor of unpickled object not being called
1760
+ * Minor CMake build system improvements on Windows
1761
+ * New ``pybind11::args`` and ``pybind11::kwargs`` types to create functions which
1762
+ take an arbitrary number of arguments and keyword arguments
1763
+ * New syntax to call a Python function from C++ using ``*args`` and ``*kwargs``
1764
+ * The functions ``def_property_*`` now correctly process docstring arguments (these
1765
+ formerly caused a segmentation fault)
1766
+ * Many ``mkdoc.py`` improvements (enumerations, template arguments, ``DOC()``
1767
+ macro accepts more arguments)
1768
+ * Cygwin support
1769
+ * Documentation improvements (pickling support, ``keep_alive``, macro usage)
1770
+
1771
+ 1.7 (April 30, 2016)
1772
+ ----------------------
1773
+ * Added a new ``move`` return value policy that triggers C++11 move semantics.
1774
+ The automatic return value policy falls back to this case whenever a rvalue
1775
+ reference is encountered
1776
+ * Significantly more general GIL state routines that are used instead of
1777
+ Python's troublesome ``PyGILState_Ensure`` and ``PyGILState_Release`` API
1778
+ * Redesign of opaque types that drastically simplifies their usage
1779
+ * Extended ability to pass values of type ``[const] void *``
1780
+ * ``keep_alive`` fix: don't fail when there is no patient
1781
+ * ``functional.h``: acquire the GIL before calling a Python function
1782
+ * Added Python RAII type wrappers ``none`` and ``iterable``
1783
+ * Added ``*args`` and ``*kwargs`` pass-through parameters to
1784
+ ``pybind11.get_include()`` function
1785
+ * Iterator improvements and fixes
1786
+ * Documentation on return value policies and opaque types improved
1787
+
1788
+ 1.6 (April 30, 2016)
1789
+ ----------------------
1790
+ * Skipped due to upload to PyPI gone wrong and inability to recover
1791
+ (https://github.com/pypa/packaging-problems/issues/74)
1792
+
1793
+ 1.5 (April 21, 2016)
1794
+ ----------------------
1795
+ * For polymorphic types, use RTTI to try to return the closest type registered with pybind11
1796
+ * Pickling support for serializing and unserializing C++ instances to a byte stream in Python
1797
+ * Added a convenience routine ``make_iterator()`` which turns a range indicated
1798
+ by a pair of C++ iterators into a iterable Python object
1799
+ * Added ``len()`` and a variadic ``make_tuple()`` function
1800
+ * Addressed a rare issue that could confuse the current virtual function
1801
+ dispatcher and another that could lead to crashes in multi-threaded
1802
+ applications
1803
+ * Added a ``get_include()`` function to the Python module that returns the path
1804
+ of the directory containing the installed pybind11 header files
1805
+ * Documentation improvements: import issues, symbol visibility, pickling, limitations
1806
+ * Added casting support for ``std::reference_wrapper<>``
1807
+
1808
+ 1.4 (April 7, 2016)
1809
+ --------------------------
1810
+ * Transparent type conversion for ``std::wstring`` and ``wchar_t``
1811
+ * Allow passing ``nullptr``-valued strings
1812
+ * Transparent passing of ``void *`` pointers using capsules
1813
+ * Transparent support for returning values wrapped in ``std::unique_ptr<>``
1814
+ * Improved docstring generation for compatibility with Sphinx
1815
+ * Nicer debug error message when default parameter construction fails
1816
+ * Support for "opaque" types that bypass the transparent conversion layer for STL containers
1817
+ * Redesigned type casting interface to avoid ambiguities that could occasionally cause compiler errors
1818
+ * Redesigned property implementation; fixes crashes due to an unfortunate default return value policy
1819
+ * Anaconda package generation support
1820
+
1821
+ 1.3 (March 8, 2016)
1822
+ --------------------------
1823
+
1824
+ * Added support for the Intel C++ compiler (v15+)
1825
+ * Added support for the STL unordered set/map data structures
1826
+ * Added support for the STL linked list data structure
1827
+ * NumPy-style broadcasting support in ``pybind11::vectorize``
1828
+ * pybind11 now displays more verbose error messages when ``arg::operator=()`` fails
1829
+ * pybind11 internal data structures now live in a version-dependent namespace to avoid ABI issues
1830
+ * Many, many bugfixes involving corner cases and advanced usage
1831
+
1832
+ 1.2 (February 7, 2016)
1833
+ --------------------------
1834
+
1835
+ * Optional: efficient generation of function signatures at compile time using C++14
1836
+ * Switched to a simpler and more general way of dealing with function default
1837
+ arguments. Unused keyword arguments in function calls are now detected and
1838
+ cause errors as expected
1839
+ * New ``keep_alive`` call policy analogous to Boost.Python's ``with_custodian_and_ward``
1840
+ * New ``pybind11::base<>`` attribute to indicate a subclass relationship
1841
+ * Improved interface for RAII type wrappers in ``pytypes.h``
1842
+ * Use RAII type wrappers consistently within pybind11 itself. This
1843
+ fixes various potential refcount leaks when exceptions occur
1844
+ * Added new ``bytes`` RAII type wrapper (maps to ``string`` in Python 2.7)
1845
+ * Made handle and related RAII classes const correct, using them more
1846
+ consistently everywhere now
1847
+ * Got rid of the ugly ``__pybind11__`` attributes on the Python side---they are
1848
+ now stored in a C++ hash table that is not visible in Python
1849
+ * Fixed refcount leaks involving NumPy arrays and bound functions
1850
+ * Vastly improved handling of shared/smart pointers
1851
+ * Removed an unnecessary copy operation in ``pybind11::vectorize``
1852
+ * Fixed naming clashes when both pybind11 and NumPy headers are included
1853
+ * Added conversions for additional exception types
1854
+ * Documentation improvements (using multiple extension modules, smart pointers,
1855
+ other minor clarifications)
1856
+ * unified infrastructure for parsing variadic arguments in ``class_`` and cpp_function
1857
+ * Fixed license text (was: ZLIB, should have been: 3-clause BSD)
1858
+ * Python 3.2 compatibility
1859
+ * Fixed remaining issues when accessing types in another plugin module
1860
+ * Added enum comparison and casting methods
1861
+ * Improved SFINAE-based detection of whether types are copy-constructible
1862
+ * Eliminated many warnings about unused variables and the use of ``offsetof()``
1863
+ * Support for ``std::array<>`` conversions
1864
+
1865
+ 1.1 (December 7, 2015)
1866
+ --------------------------
1867
+
1868
+ * Documentation improvements (GIL, wrapping functions, casting, fixed many typos)
1869
+ * Generalized conversion of integer types
1870
+ * Improved support for casting function objects
1871
+ * Improved support for ``std::shared_ptr<>`` conversions
1872
+ * Initial support for ``std::set<>`` conversions
1873
+ * Fixed type resolution issue for types defined in a separate plugin module
1874
+ * CMake build system improvements
1875
+ * Factored out generic functionality to non-templated code (smaller code size)
1876
+ * Added a code size / compile time benchmark vs Boost.Python
1877
+ * Added an appveyor CI script
1878
+
1879
+ 1.0 (October 15, 2015)
1880
+ ------------------------
1881
+ * Initial release
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/classes.rst ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _classes:
2
+
3
+ Object-oriented code
4
+ ####################
5
+
6
+ Creating bindings for a custom type
7
+ ===================================
8
+
9
+ Let's now look at a more complex example where we'll create bindings for a
10
+ custom C++ data structure named ``Pet``. Its definition is given below:
11
+
12
+ .. code-block:: cpp
13
+
14
+ struct Pet {
15
+ Pet(const std::string &name) : name(name) { }
16
+ void setName(const std::string &name_) { name = name_; }
17
+ const std::string &getName() const { return name; }
18
+
19
+ std::string name;
20
+ };
21
+
22
+ The binding code for ``Pet`` looks as follows:
23
+
24
+ .. code-block:: cpp
25
+
26
+ #include <pybind11/pybind11.h>
27
+
28
+ namespace py = pybind11;
29
+
30
+ PYBIND11_MODULE(example, m) {
31
+ py::class_<Pet>(m, "Pet")
32
+ .def(py::init<const std::string &>())
33
+ .def("setName", &Pet::setName)
34
+ .def("getName", &Pet::getName);
35
+ }
36
+
37
+ :class:`class_` creates bindings for a C++ *class* or *struct*-style data
38
+ structure. :func:`init` is a convenience function that takes the types of a
39
+ constructor's parameters as template arguments and wraps the corresponding
40
+ constructor (see the :ref:`custom_constructors` section for details). An
41
+ interactive Python session demonstrating this example is shown below:
42
+
43
+ .. code-block:: pycon
44
+
45
+ % python
46
+ >>> import example
47
+ >>> p = example.Pet('Molly')
48
+ >>> print(p)
49
+ <example.Pet object at 0x10cd98060>
50
+ >>> p.getName()
51
+ u'Molly'
52
+ >>> p.setName('Charly')
53
+ >>> p.getName()
54
+ u'Charly'
55
+
56
+ .. seealso::
57
+
58
+ Static member functions can be bound in the same way using
59
+ :func:`class_::def_static`.
60
+
61
+ Keyword and default arguments
62
+ =============================
63
+ It is possible to specify keyword and default arguments using the syntax
64
+ discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
65
+ and :ref:`default_args` for details.
66
+
67
+ Binding lambda functions
68
+ ========================
69
+
70
+ Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
71
+
72
+ .. code-block:: pycon
73
+
74
+ >>> print(p)
75
+ <example.Pet object at 0x10cd98060>
76
+
77
+ To address this, we could bind a utility function that returns a human-readable
78
+ summary to the special method slot named ``__repr__``. Unfortunately, there is no
79
+ suitable functionality in the ``Pet`` data structure, and it would be nice if
80
+ we did not have to change it. This can easily be accomplished by binding a
81
+ Lambda function instead:
82
+
83
+ .. code-block:: cpp
84
+
85
+ py::class_<Pet>(m, "Pet")
86
+ .def(py::init<const std::string &>())
87
+ .def("setName", &Pet::setName)
88
+ .def("getName", &Pet::getName)
89
+ .def("__repr__",
90
+ [](const Pet &a) {
91
+ return "<example.Pet named '" + a.name + "'>";
92
+ }
93
+ );
94
+
95
+ Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
96
+ With the above change, the same Python code now produces the following output:
97
+
98
+ .. code-block:: pycon
99
+
100
+ >>> print(p)
101
+ <example.Pet named 'Molly'>
102
+
103
+ .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
104
+
105
+ .. _properties:
106
+
107
+ Instance and static fields
108
+ ==========================
109
+
110
+ We can also directly expose the ``name`` field using the
111
+ :func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
112
+ method also exists for ``const`` fields.
113
+
114
+ .. code-block:: cpp
115
+
116
+ py::class_<Pet>(m, "Pet")
117
+ .def(py::init<const std::string &>())
118
+ .def_readwrite("name", &Pet::name)
119
+ // ... remainder ...
120
+
121
+ This makes it possible to write
122
+
123
+ .. code-block:: pycon
124
+
125
+ >>> p = example.Pet('Molly')
126
+ >>> p.name
127
+ u'Molly'
128
+ >>> p.name = 'Charly'
129
+ >>> p.name
130
+ u'Charly'
131
+
132
+ Now suppose that ``Pet::name`` was a private internal variable
133
+ that can only be accessed via setters and getters.
134
+
135
+ .. code-block:: cpp
136
+
137
+ class Pet {
138
+ public:
139
+ Pet(const std::string &name) : name(name) { }
140
+ void setName(const std::string &name_) { name = name_; }
141
+ const std::string &getName() const { return name; }
142
+ private:
143
+ std::string name;
144
+ };
145
+
146
+ In this case, the method :func:`class_::def_property`
147
+ (:func:`class_::def_property_readonly` for read-only data) can be used to
148
+ provide a field-like interface within Python that will transparently call
149
+ the setter and getter functions:
150
+
151
+ .. code-block:: cpp
152
+
153
+ py::class_<Pet>(m, "Pet")
154
+ .def(py::init<const std::string &>())
155
+ .def_property("name", &Pet::getName, &Pet::setName)
156
+ // ... remainder ...
157
+
158
+ Write only properties can be defined by passing ``nullptr`` as the
159
+ input for the read function.
160
+
161
+ .. seealso::
162
+
163
+ Similar functions :func:`class_::def_readwrite_static`,
164
+ :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
165
+ and :func:`class_::def_property_readonly_static` are provided for binding
166
+ static variables and properties. Please also see the section on
167
+ :ref:`static_properties` in the advanced part of the documentation.
168
+
169
+ Dynamic attributes
170
+ ==================
171
+
172
+ Native Python classes can pick up new attributes dynamically:
173
+
174
+ .. code-block:: pycon
175
+
176
+ >>> class Pet:
177
+ ... name = 'Molly'
178
+ ...
179
+ >>> p = Pet()
180
+ >>> p.name = 'Charly' # overwrite existing
181
+ >>> p.age = 2 # dynamically add a new attribute
182
+
183
+ By default, classes exported from C++ do not support this and the only writable
184
+ attributes are the ones explicitly defined using :func:`class_::def_readwrite`
185
+ or :func:`class_::def_property`.
186
+
187
+ .. code-block:: cpp
188
+
189
+ py::class_<Pet>(m, "Pet")
190
+ .def(py::init<>())
191
+ .def_readwrite("name", &Pet::name);
192
+
193
+ Trying to set any other attribute results in an error:
194
+
195
+ .. code-block:: pycon
196
+
197
+ >>> p = example.Pet()
198
+ >>> p.name = 'Charly' # OK, attribute defined in C++
199
+ >>> p.age = 2 # fail
200
+ AttributeError: 'Pet' object has no attribute 'age'
201
+
202
+ To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
203
+ must be added to the :class:`py::class_` constructor:
204
+
205
+ .. code-block:: cpp
206
+
207
+ py::class_<Pet>(m, "Pet", py::dynamic_attr())
208
+ .def(py::init<>())
209
+ .def_readwrite("name", &Pet::name);
210
+
211
+ Now everything works as expected:
212
+
213
+ .. code-block:: pycon
214
+
215
+ >>> p = example.Pet()
216
+ >>> p.name = 'Charly' # OK, overwrite value in C++
217
+ >>> p.age = 2 # OK, dynamically add a new attribute
218
+ >>> p.__dict__ # just like a native Python class
219
+ {'age': 2}
220
+
221
+ Note that there is a small runtime cost for a class with dynamic attributes.
222
+ Not only because of the addition of a ``__dict__``, but also because of more
223
+ expensive garbage collection tracking which must be activated to resolve
224
+ possible circular references. Native Python classes incur this same cost by
225
+ default, so this is not anything to worry about. By default, pybind11 classes
226
+ are more efficient than native Python classes. Enabling dynamic attributes
227
+ just brings them on par.
228
+
229
+ .. _inheritance:
230
+
231
+ Inheritance and automatic downcasting
232
+ =====================================
233
+
234
+ Suppose now that the example consists of two data structures with an
235
+ inheritance relationship:
236
+
237
+ .. code-block:: cpp
238
+
239
+ struct Pet {
240
+ Pet(const std::string &name) : name(name) { }
241
+ std::string name;
242
+ };
243
+
244
+ struct Dog : Pet {
245
+ Dog(const std::string &name) : Pet(name) { }
246
+ std::string bark() const { return "woof!"; }
247
+ };
248
+
249
+ There are two different ways of indicating a hierarchical relationship to
250
+ pybind11: the first specifies the C++ base class as an extra template
251
+ parameter of the :class:`class_`:
252
+
253
+ .. code-block:: cpp
254
+
255
+ py::class_<Pet>(m, "Pet")
256
+ .def(py::init<const std::string &>())
257
+ .def_readwrite("name", &Pet::name);
258
+
259
+ // Method 1: template parameter:
260
+ py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
261
+ .def(py::init<const std::string &>())
262
+ .def("bark", &Dog::bark);
263
+
264
+ Alternatively, we can also assign a name to the previously bound ``Pet``
265
+ :class:`class_` object and reference it when binding the ``Dog`` class:
266
+
267
+ .. code-block:: cpp
268
+
269
+ py::class_<Pet> pet(m, "Pet");
270
+ pet.def(py::init<const std::string &>())
271
+ .def_readwrite("name", &Pet::name);
272
+
273
+ // Method 2: pass parent class_ object:
274
+ py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
275
+ .def(py::init<const std::string &>())
276
+ .def("bark", &Dog::bark);
277
+
278
+ Functionality-wise, both approaches are equivalent. Afterwards, instances will
279
+ expose fields and methods of both types:
280
+
281
+ .. code-block:: pycon
282
+
283
+ >>> p = example.Dog('Molly')
284
+ >>> p.name
285
+ u'Molly'
286
+ >>> p.bark()
287
+ u'woof!'
288
+
289
+ The C++ classes defined above are regular non-polymorphic types with an
290
+ inheritance relationship. This is reflected in Python:
291
+
292
+ .. code-block:: cpp
293
+
294
+ // Return a base pointer to a derived instance
295
+ m.def("pet_store", []() { return std::unique_ptr<Pet>(new Dog("Molly")); });
296
+
297
+ .. code-block:: pycon
298
+
299
+ >>> p = example.pet_store()
300
+ >>> type(p) # `Dog` instance behind `Pet` pointer
301
+ Pet # no pointer downcasting for regular non-polymorphic types
302
+ >>> p.bark()
303
+ AttributeError: 'Pet' object has no attribute 'bark'
304
+
305
+ The function returned a ``Dog`` instance, but because it's a non-polymorphic
306
+ type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only
307
+ considered polymorphic if it has at least one virtual function and pybind11
308
+ will automatically recognize this:
309
+
310
+ .. code-block:: cpp
311
+
312
+ struct PolymorphicPet {
313
+ virtual ~PolymorphicPet() = default;
314
+ };
315
+
316
+ struct PolymorphicDog : PolymorphicPet {
317
+ std::string bark() const { return "woof!"; }
318
+ };
319
+
320
+ // Same binding code
321
+ py::class_<PolymorphicPet>(m, "PolymorphicPet");
322
+ py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
323
+ .def(py::init<>())
324
+ .def("bark", &PolymorphicDog::bark);
325
+
326
+ // Again, return a base pointer to a derived instance
327
+ m.def("pet_store2", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });
328
+
329
+ .. code-block:: pycon
330
+
331
+ >>> p = example.pet_store2()
332
+ >>> type(p)
333
+ PolymorphicDog # automatically downcast
334
+ >>> p.bark()
335
+ u'woof!'
336
+
337
+ Given a pointer to a polymorphic base, pybind11 performs automatic downcasting
338
+ to the actual derived type. Note that this goes beyond the usual situation in
339
+ C++: we don't just get access to the virtual functions of the base, we get the
340
+ concrete derived type including functions and attributes that the base type may
341
+ not even be aware of.
342
+
343
+ .. seealso::
344
+
345
+ For more information about polymorphic behavior see :ref:`overriding_virtuals`.
346
+
347
+
348
+ Overloaded methods
349
+ ==================
350
+
351
+ Sometimes there are several overloaded C++ methods with the same name taking
352
+ different kinds of input arguments:
353
+
354
+ .. code-block:: cpp
355
+
356
+ struct Pet {
357
+ Pet(const std::string &name, int age) : name(name), age(age) { }
358
+
359
+ void set(int age_) { age = age_; }
360
+ void set(const std::string &name_) { name = name_; }
361
+
362
+ std::string name;
363
+ int age;
364
+ };
365
+
366
+ Attempting to bind ``Pet::set`` will cause an error since the compiler does not
367
+ know which method the user intended to select. We can disambiguate by casting
368
+ them to function pointers. Binding multiple functions to the same Python name
369
+ automatically creates a chain of function overloads that will be tried in
370
+ sequence.
371
+
372
+ .. code-block:: cpp
373
+
374
+ py::class_<Pet>(m, "Pet")
375
+ .def(py::init<const std::string &, int>())
376
+ .def("set", static_cast<void (Pet::*)(int)>(&Pet::set), "Set the pet's age")
377
+ .def("set", static_cast<void (Pet::*)(const std::string &)>(&Pet::set), "Set the pet's name");
378
+
379
+ The overload signatures are also visible in the method's docstring:
380
+
381
+ .. code-block:: pycon
382
+
383
+ >>> help(example.Pet)
384
+
385
+ class Pet(__builtin__.object)
386
+ | Methods defined here:
387
+ |
388
+ | __init__(...)
389
+ | Signature : (Pet, str, int) -> NoneType
390
+ |
391
+ | set(...)
392
+ | 1. Signature : (Pet, int) -> NoneType
393
+ |
394
+ | Set the pet's age
395
+ |
396
+ | 2. Signature : (Pet, str) -> NoneType
397
+ |
398
+ | Set the pet's name
399
+
400
+ If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
401
+ syntax to cast the overloaded function:
402
+
403
+ .. code-block:: cpp
404
+
405
+ py::class_<Pet>(m, "Pet")
406
+ .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
407
+ .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
408
+
409
+ Here, ``py::overload_cast`` only requires the parameter types to be specified.
410
+ The return type and class are deduced. This avoids the additional noise of
411
+ ``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
412
+ on constness, the ``py::const_`` tag should be used:
413
+
414
+ .. code-block:: cpp
415
+
416
+ struct Widget {
417
+ int foo(int x, float y);
418
+ int foo(int x, float y) const;
419
+ };
420
+
421
+ py::class_<Widget>(m, "Widget")
422
+ .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
423
+ .def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
424
+
425
+ If you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only,
426
+ you can use ``py::detail::overload_cast_impl`` with an additional set of parentheses:
427
+
428
+ .. code-block:: cpp
429
+
430
+ template <typename... Args>
431
+ using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;
432
+
433
+ py::class_<Pet>(m, "Pet")
434
+ .def("set", overload_cast_<int>()(&Pet::set), "Set the pet's age")
435
+ .def("set", overload_cast_<const std::string &>()(&Pet::set), "Set the pet's name");
436
+
437
+ .. [#cpp14] A compiler which supports the ``-std=c++14`` flag
438
+ or Visual Studio 2015 Update 2 and newer.
439
+
440
+ .. note::
441
+
442
+ To define multiple overloaded constructors, simply declare one after the
443
+ other using the ``.def(py::init<...>())`` syntax. The existing machinery
444
+ for specifying keyword and default arguments also works.
445
+
446
+ Enumerations and internal types
447
+ ===============================
448
+
449
+ Let's now suppose that the example class contains an internal enumeration type,
450
+ e.g.:
451
+
452
+ .. code-block:: cpp
453
+
454
+ struct Pet {
455
+ enum Kind {
456
+ Dog = 0,
457
+ Cat
458
+ };
459
+
460
+ Pet(const std::string &name, Kind type) : name(name), type(type) { }
461
+
462
+ std::string name;
463
+ Kind type;
464
+ };
465
+
466
+ The binding code for this example looks as follows:
467
+
468
+ .. code-block:: cpp
469
+
470
+ py::class_<Pet> pet(m, "Pet");
471
+
472
+ pet.def(py::init<const std::string &, Pet::Kind>())
473
+ .def_readwrite("name", &Pet::name)
474
+ .def_readwrite("type", &Pet::type);
475
+
476
+ py::enum_<Pet::Kind>(pet, "Kind")
477
+ .value("Dog", Pet::Kind::Dog)
478
+ .value("Cat", Pet::Kind::Cat)
479
+ .export_values();
480
+
481
+ To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
482
+ ``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
483
+ constructor. The :func:`enum_::export_values` function exports the enum entries
484
+ into the parent scope, which should be skipped for newer C++11-style strongly
485
+ typed enums.
486
+
487
+ .. code-block:: pycon
488
+
489
+ >>> p = Pet('Lucy', Pet.Cat)
490
+ >>> p.type
491
+ Kind.Cat
492
+ >>> int(p.type)
493
+ 1L
494
+
495
+ The entries defined by the enumeration type are exposed in the ``__members__`` property:
496
+
497
+ .. code-block:: pycon
498
+
499
+ >>> Pet.Kind.__members__
500
+ {'Dog': Kind.Dog, 'Cat': Kind.Cat}
501
+
502
+ The ``name`` property returns the name of the enum value as a unicode string.
503
+
504
+ .. note::
505
+
506
+ It is also possible to use ``str(enum)``, however these accomplish different
507
+ goals. The following shows how these two approaches differ.
508
+
509
+ .. code-block:: pycon
510
+
511
+ >>> p = Pet( "Lucy", Pet.Cat )
512
+ >>> pet_type = p.type
513
+ >>> pet_type
514
+ Pet.Cat
515
+ >>> str(pet_type)
516
+ 'Pet.Cat'
517
+ >>> pet_type.name
518
+ 'Cat'
519
+
520
+ .. note::
521
+
522
+ When the special tag ``py::arithmetic()`` is specified to the ``enum_``
523
+ constructor, pybind11 creates an enumeration that also supports rudimentary
524
+ arithmetic and bit-level operations like comparisons, and, or, xor, negation,
525
+ etc.
526
+
527
+ .. code-block:: cpp
528
+
529
+ py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
530
+ ...
531
+
532
+ By default, these are omitted to conserve space.
third-party/DPVO/Pangolin/components/pango_python/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/Pangolin/components/pango_python/pybind11/docs/compiling.rst ADDED
@@ -0,0 +1,655 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
46
+ ...,
47
+ ext_modules=ext_modules
48
+ )
49
+
50
+ If you want to do an automatic search for the highest supported C++ standard,
51
+ that is supported via a ``build_ext`` command override; it will only affect
52
+ ``Pybind11Extensions``:
53
+
54
+ .. code-block:: python
55
+
56
+ from glob import glob
57
+ from setuptools import setup
58
+ from pybind11.setup_helpers import Pybind11Extension, build_ext
59
+
60
+ ext_modules = [
61
+ Pybind11Extension(
62
+ "python_example",
63
+ sorted(glob("src/*.cpp")),
64
+ ),
65
+ ]
66
+
67
+ setup(
68
+ ...,
69
+ cmdclass={"build_ext": build_ext},
70
+ ext_modules=ext_modules
71
+ )
72
+
73
+ If you have single-file extension modules that are directly stored in the
74
+ Python source tree (``foo.cpp`` in the same directory as where a ``foo.py``
75
+ would be located), you can also generate ``Pybind11Extensions`` using
76
+ ``setup_helpers.intree_extensions``: ``intree_extensions(["path/to/foo.cpp",
77
+ ...])`` returns a list of ``Pybind11Extensions`` which can be passed to
78
+ ``ext_modules``, possibly after further customizing their attributes
79
+ (``libraries``, ``include_dirs``, etc.). By doing so, a ``foo.*.so`` extension
80
+ module will be generated and made available upon installation.
81
+
82
+ ``intree_extension`` will automatically detect if you are using a ``src``-style
83
+ layout (as long as no namespace packages are involved), but you can also
84
+ explicitly pass ``package_dir`` to it (as in ``setuptools.setup``).
85
+
86
+ Since pybind11 does not require NumPy when building, a light-weight replacement
87
+ for NumPy's parallel compilation distutils tool is included. Use it like this:
88
+
89
+ .. code-block:: python
90
+
91
+ from pybind11.setup_helpers import ParallelCompile
92
+
93
+ # Optional multithreaded build
94
+ ParallelCompile("NPY_NUM_BUILD_JOBS").install()
95
+
96
+ setup(...)
97
+
98
+ The argument is the name of an environment variable to control the number of
99
+ threads, such as ``NPY_NUM_BUILD_JOBS`` (as used by NumPy), though you can set
100
+ something different if you want; ``CMAKE_BUILD_PARALLEL_LEVEL`` is another choice
101
+ a user might expect. You can also pass ``default=N`` to set the default number
102
+ of threads (0 will take the number of threads available) and ``max=N``, the
103
+ maximum number of threads; if you have a large extension you may want set this
104
+ to a memory dependent number.
105
+
106
+ If you are developing rapidly and have a lot of C++ files, you may want to
107
+ avoid rebuilding files that have not changed. For simple cases were you are
108
+ using ``pip install -e .`` and do not have local headers, you can skip the
109
+ rebuild if an object file is newer than its source (headers are not checked!)
110
+ with the following:
111
+
112
+ .. code-block:: python
113
+
114
+ from pybind11.setup_helpers import ParallelCompile, naive_recompile
115
+
116
+ SmartCompile("NPY_NUM_BUILD_JOBS", needs_recompile=naive_recompile).install()
117
+
118
+
119
+ If you have a more complex build, you can implement a smarter function and pass
120
+ it to ``needs_recompile``, or you can use [Ccache]_ instead. ``CXX="cache g++"
121
+ pip install -e .`` would be the way to use it with GCC, for example. Unlike the
122
+ simple solution, this even works even when not compiling in editable mode, but
123
+ it does require Ccache to be installed.
124
+
125
+ Keep in mind that Pip will not even attempt to rebuild if it thinks it has
126
+ already built a copy of your code, which it deduces from the version number.
127
+ One way to avoid this is to use [setuptools_scm]_, which will generate a
128
+ version number that includes the number of commits since your last tag and a
129
+ hash for a dirty directory. Another way to force a rebuild is purge your cache
130
+ or use Pip's ``--no-cache-dir`` option.
131
+
132
+ .. [Ccache] https://ccache.dev
133
+
134
+ .. [setuptools_scm] https://github.com/pypa/setuptools_scm
135
+
136
+ .. _setup_helpers-pep518:
137
+
138
+ PEP 518 requirements (Pip 10+ required)
139
+ ---------------------------------------
140
+
141
+ If you use `PEP 518's <https://www.python.org/dev/peps/pep-0518/>`_
142
+ ``pyproject.toml`` file, you can ensure that ``pybind11`` is available during
143
+ the compilation of your project. When this file exists, Pip will make a new
144
+ virtual environment, download just the packages listed here in ``requires=``,
145
+ and build a wheel (binary Python package). It will then throw away the
146
+ environment, and install your wheel.
147
+
148
+ Your ``pyproject.toml`` file will likely look something like this:
149
+
150
+ .. code-block:: toml
151
+
152
+ [build-system]
153
+ requires = ["setuptools>=42", "wheel", "pybind11~=2.6.1"]
154
+ build-backend = "setuptools.build_meta"
155
+
156
+ .. note::
157
+
158
+ The main drawback to this method is that a `PEP 517`_ compliant build tool,
159
+ such as Pip 10+, is required for this approach to work; older versions of
160
+ Pip completely ignore this file. If you distribute binaries (called wheels
161
+ in Python) using something like `cibuildwheel`_, remember that ``setup.py``
162
+ and ``pyproject.toml`` are not even contained in the wheel, so this high
163
+ Pip requirement is only for source builds, and will not affect users of
164
+ your binary wheels. If you are building SDists and wheels, then
165
+ `pypa-build`_ is the recommended official tool.
166
+
167
+ .. _PEP 517: https://www.python.org/dev/peps/pep-0517/
168
+ .. _cibuildwheel: https://cibuildwheel.readthedocs.io
169
+ .. _pypa-build: https://pypa-build.readthedocs.io/en/latest/
170
+
171
+ .. _setup_helpers-setup_requires:
172
+
173
+ Classic ``setup_requires``
174
+ --------------------------
175
+
176
+ If you want to support old versions of Pip with the classic
177
+ ``setup_requires=["pybind11"]`` keyword argument to setup, which triggers a
178
+ two-phase ``setup.py`` run, then you will need to use something like this to
179
+ ensure the first pass works (which has not yet installed the ``setup_requires``
180
+ packages, since it can't install something it does not know about):
181
+
182
+ .. code-block:: python
183
+
184
+ try:
185
+ from pybind11.setup_helpers import Pybind11Extension
186
+ except ImportError:
187
+ from setuptools import Extension as Pybind11Extension
188
+
189
+
190
+ It doesn't matter that the Extension class is not the enhanced subclass for the
191
+ first pass run; and the second pass will have the ``setup_requires``
192
+ requirements.
193
+
194
+ This is obviously more of a hack than the PEP 518 method, but it supports
195
+ ancient versions of Pip.
196
+
197
+ .. _setup_helpers-copy-manually:
198
+
199
+ Copy manually
200
+ -------------
201
+
202
+ You can also copy ``setup_helpers.py`` directly to your project; it was
203
+ designed to be usable standalone, like the old example ``setup.py``. You can
204
+ set ``include_pybind11=False`` to skip including the pybind11 package headers,
205
+ so you can use it with git submodules and a specific git version. If you use
206
+ this, you will need to import from a local file in ``setup.py`` and ensure the
207
+ helper file is part of your MANIFEST.
208
+
209
+
210
+ Closely related, if you include pybind11 as a subproject, you can run the
211
+ ``setup_helpers.py`` inplace. If loaded correctly, this should even pick up
212
+ the correct include for pybind11, though you can turn it off as shown above if
213
+ you want to input it manually.
214
+
215
+ Suggested usage if you have pybind11 as a submodule in ``extern/pybind11``:
216
+
217
+ .. code-block:: python
218
+
219
+ DIR = os.path.abspath(os.path.dirname(__file__))
220
+
221
+ sys.path.append(os.path.join(DIR, "extern", "pybind11"))
222
+ from pybind11.setup_helpers import Pybind11Extension # noqa: E402
223
+
224
+ del sys.path[-1]
225
+
226
+
227
+ .. versionchanged:: 2.6
228
+
229
+ Added ``setup_helpers`` file.
230
+
231
+ Building with cppimport
232
+ ========================
233
+
234
+ [cppimport]_ is a small Python import hook that determines whether there is a C++
235
+ source file whose name matches the requested module. If there is, the file is
236
+ compiled as a Python extension using pybind11 and placed in the same folder as
237
+ the C++ source file. Python is then able to find the module and load it.
238
+
239
+ .. [cppimport] https://github.com/tbenthompson/cppimport
240
+
241
+ .. _cmake:
242
+
243
+ Building with CMake
244
+ ===================
245
+
246
+ For C++ codebases that have an existing CMake-based build system, a Python
247
+ extension module can be created with just a few lines of code:
248
+
249
+ .. code-block:: cmake
250
+
251
+ cmake_minimum_required(VERSION 3.4...3.18)
252
+ project(example LANGUAGES CXX)
253
+
254
+ add_subdirectory(pybind11)
255
+ pybind11_add_module(example example.cpp)
256
+
257
+ This assumes that the pybind11 repository is located in a subdirectory named
258
+ :file:`pybind11` and that the code is located in a file named :file:`example.cpp`.
259
+ The CMake command ``add_subdirectory`` will import the pybind11 project which
260
+ provides the ``pybind11_add_module`` function. It will take care of all the
261
+ details needed to build a Python extension module on any platform.
262
+
263
+ A working sample project, including a way to invoke CMake from :file:`setup.py` for
264
+ PyPI integration, can be found in the [cmake_example]_ repository.
265
+
266
+ .. [cmake_example] https://github.com/pybind/cmake_example
267
+
268
+ .. versionchanged:: 2.6
269
+ CMake 3.4+ is required.
270
+
271
+ Further information can be found at :doc:`cmake/index`.
272
+
273
+ pybind11_add_module
274
+ -------------------
275
+
276
+ To ease the creation of Python extension modules, pybind11 provides a CMake
277
+ function with the following signature:
278
+
279
+ .. code-block:: cmake
280
+
281
+ pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]
282
+ [NO_EXTRAS] [THIN_LTO] [OPT_SIZE] source1 [source2 ...])
283
+
284
+ This function behaves very much like CMake's builtin ``add_library`` (in fact,
285
+ it's a wrapper function around that command). It will add a library target
286
+ called ``<name>`` to be built from the listed source files. In addition, it
287
+ will take care of all the Python-specific compiler and linker flags as well
288
+ as the OS- and Python-version-specific file extension. The produced target
289
+ ``<name>`` can be further manipulated with regular CMake commands.
290
+
291
+ ``MODULE`` or ``SHARED`` may be given to specify the type of library. If no
292
+ type is given, ``MODULE`` is used by default which ensures the creation of a
293
+ Python-exclusive module. Specifying ``SHARED`` will create a more traditional
294
+ dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL``
295
+ removes this target from the default build (see CMake docs for details).
296
+
297
+ Since pybind11 is a template library, ``pybind11_add_module`` adds compiler
298
+ flags to ensure high quality code generation without bloat arising from long
299
+ symbol names and duplication of code in different translation units. It
300
+ sets default visibility to *hidden*, which is required for some pybind11
301
+ features and functionality when attempting to load multiple pybind11 modules
302
+ compiled under different pybind11 versions. It also adds additional flags
303
+ enabling LTO (Link Time Optimization) and strip unneeded symbols. See the
304
+ :ref:`FAQ entry <faq:symhidden>` for a more detailed explanation. These
305
+ latter optimizations are never applied in ``Debug`` mode. If ``NO_EXTRAS`` is
306
+ given, they will always be disabled, even in ``Release`` mode. However, this
307
+ will result in code bloat and is generally not recommended.
308
+
309
+ As stated above, LTO is enabled by default. Some newer compilers also support
310
+ different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause
311
+ the function to prefer this flavor if available. The function falls back to
312
+ regular LTO if ``-flto=thin`` is not available. If
313
+ ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is set (either ``ON`` or ``OFF``), then
314
+ that will be respected instead of the built-in flag search.
315
+
316
+ .. note::
317
+
318
+ If you want to set the property form on targets or the
319
+ ``CMAKE_INTERPROCEDURAL_OPTIMIZATION_<CONFIG>`` versions of this, you should
320
+ still use ``set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF)`` (otherwise a
321
+ no-op) to disable pybind11's ipo flags.
322
+
323
+ The ``OPT_SIZE`` flag enables size-based optimization equivalent to the
324
+ standard ``/Os`` or ``-Os`` compiler flags and the ``MinSizeRel`` build type,
325
+ which avoid optimizations that that can substantially increase the size of the
326
+ resulting binary. This flag is particularly useful in projects that are split
327
+ into performance-critical parts and associated bindings. In this case, we can
328
+ compile the project in release mode (and hence, optimize performance globally),
329
+ and specify ``OPT_SIZE`` for the binding target, where size might be the main
330
+ concern as performance is often less critical here. A ~25% size reduction has
331
+ been observed in practice. This flag only changes the optimization behavior at
332
+ a per-target level and takes precedence over the global CMake build type
333
+ (``Release``, ``RelWithDebInfo``) except for ``Debug`` builds, where
334
+ optimizations remain disabled.
335
+
336
+ .. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html
337
+
338
+ Configuration variables
339
+ -----------------------
340
+
341
+ By default, pybind11 will compile modules with the compiler default or the
342
+ minimum standard required by pybind11, whichever is higher. You can set the
343
+ standard explicitly with
344
+ `CMAKE_CXX_STANDARD <https://cmake.org/cmake/help/latest/variable/CMAKE_CXX_STANDARD.html>`_:
345
+
346
+ .. code-block:: cmake
347
+
348
+ set(CMAKE_CXX_STANDARD 14 CACHE STRING "C++ version selection") # or 11, 14, 17, 20
349
+ set(CMAKE_CXX_STANDARD_REQUIRED ON) # optional, ensure standard is supported
350
+ set(CMAKE_CXX_EXTENSIONS OFF) # optional, keep compiler extensionsn off
351
+
352
+ The variables can also be set when calling CMake from the command line using
353
+ the ``-D<variable>=<value>`` flag. You can also manually set ``CXX_STANDARD``
354
+ on a target or use ``target_compile_features`` on your targets - anything that
355
+ CMake supports.
356
+
357
+ Classic Python support: The target Python version can be selected by setting
358
+ ``PYBIND11_PYTHON_VERSION`` or an exact Python installation can be specified
359
+ with ``PYTHON_EXECUTABLE``. For example:
360
+
361
+ .. code-block:: bash
362
+
363
+ cmake -DPYBIND11_PYTHON_VERSION=3.6 ..
364
+
365
+ # Another method:
366
+ cmake -DPYTHON_EXECUTABLE=/path/to/python ..
367
+
368
+ # This often is a good way to get the current Python, works in environments:
369
+ cmake -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)") ..
370
+
371
+
372
+ find_package vs. add_subdirectory
373
+ ---------------------------------
374
+
375
+ For CMake-based projects that don't include the pybind11 repository internally,
376
+ an external installation can be detected through ``find_package(pybind11)``.
377
+ See the `Config file`_ docstring for details of relevant CMake variables.
378
+
379
+ .. code-block:: cmake
380
+
381
+ cmake_minimum_required(VERSION 3.4...3.18)
382
+ project(example LANGUAGES CXX)
383
+
384
+ find_package(pybind11 REQUIRED)
385
+ pybind11_add_module(example example.cpp)
386
+
387
+ Note that ``find_package(pybind11)`` will only work correctly if pybind11
388
+ has been correctly installed on the system, e. g. after downloading or cloning
389
+ the pybind11 repository :
390
+
391
+ .. code-block:: bash
392
+
393
+ # Classic CMake
394
+ cd pybind11
395
+ mkdir build
396
+ cd build
397
+ cmake ..
398
+ make install
399
+
400
+ # CMake 3.15+
401
+ cd pybind11
402
+ cmake -S . -B build
403
+ cmake --build build -j 2 # Build on 2 cores
404
+ cmake --install build
405
+
406
+ Once detected, the aforementioned ``pybind11_add_module`` can be employed as
407
+ before. The function usage and configuration variables are identical no matter
408
+ if pybind11 is added as a subdirectory or found as an installed package. You
409
+ can refer to the same [cmake_example]_ repository for a full sample project
410
+ -- just swap out ``add_subdirectory`` for ``find_package``.
411
+
412
+ .. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in
413
+
414
+
415
+ .. _find-python-mode:
416
+
417
+ FindPython mode
418
+ ---------------
419
+
420
+ CMake 3.12+ (3.15+ recommended, 3.18.2+ ideal) added a new module called
421
+ FindPython that had a highly improved search algorithm and modern targets
422
+ and tools. If you use FindPython, pybind11 will detect this and use the
423
+ existing targets instead:
424
+
425
+ .. code-block:: cmake
426
+
427
+ cmake_minimum_required(VERSION 3.15...3.19)
428
+ project(example LANGUAGES CXX)
429
+
430
+ find_package(Python COMPONENTS Interpreter Development REQUIRED)
431
+ find_package(pybind11 CONFIG REQUIRED)
432
+ # or add_subdirectory(pybind11)
433
+
434
+ pybind11_add_module(example example.cpp)
435
+
436
+ You can also use the targets (as listed below) with FindPython. If you define
437
+ ``PYBIND11_FINDPYTHON``, pybind11 will perform the FindPython step for you
438
+ (mostly useful when building pybind11's own tests, or as a way to change search
439
+ algorithms from the CMake invocation, with ``-DPYBIND11_FINDPYTHON=ON``.
440
+
441
+ .. warning::
442
+
443
+ If you use FindPython2 and FindPython3 to dual-target Python, use the
444
+ individual targets listed below, and avoid targets that directly include
445
+ Python parts.
446
+
447
+ There are `many ways to hint or force a discovery of a specific Python
448
+ installation <https://cmake.org/cmake/help/latest/module/FindPython.html>`_),
449
+ setting ``Python_ROOT_DIR`` may be the most common one (though with
450
+ virtualenv/venv support, and Conda support, this tends to find the correct
451
+ Python version more often than the old system did).
452
+
453
+ .. warning::
454
+
455
+ When the Python libraries (i.e. ``libpythonXX.a`` and ``libpythonXX.so``
456
+ on Unix) are not available, as is the case on a manylinux image, the
457
+ ``Development`` component will not be resolved by ``FindPython``. When not
458
+ using the embedding functionality, CMake 3.18+ allows you to specify
459
+ ``Development.Module`` instead of ``Development`` to resolve this issue.
460
+
461
+ .. versionadded:: 2.6
462
+
463
+ Advanced: interface library targets
464
+ -----------------------------------
465
+
466
+ Pybind11 supports modern CMake usage patterns with a set of interface targets,
467
+ available in all modes. The targets provided are:
468
+
469
+ ``pybind11::headers``
470
+ Just the pybind11 headers and minimum compile requirements
471
+
472
+ ``pybind11::python2_no_register``
473
+ Quiets the warning/error when mixing C++14 or higher and Python 2
474
+
475
+ ``pybind11::pybind11``
476
+ Python headers + ``pybind11::headers`` + ``pybind11::python2_no_register`` (Python 2 only)
477
+
478
+ ``pybind11::python_link_helper``
479
+ Just the "linking" part of pybind11:module
480
+
481
+ ``pybind11::module``
482
+ Everything for extension modules - ``pybind11::pybind11`` + ``Python::Module`` (FindPython CMake 3.15+) or ``pybind11::python_link_helper``
483
+
484
+ ``pybind11::embed``
485
+ Everything for embedding the Python interpreter - ``pybind11::pybind11`` + ``Python::Embed`` (FindPython) or Python libs
486
+
487
+ ``pybind11::lto`` / ``pybind11::thin_lto``
488
+ An alternative to `INTERPROCEDURAL_OPTIMIZATION` for adding link-time optimization.
489
+
490
+ ``pybind11::windows_extras``
491
+ ``/bigobj`` and ``/mp`` for MSVC.
492
+
493
+ ``pybind11::opt_size``
494
+ ``/Os`` for MSVC, ``-Os`` for other compilers. Does nothing for debug builds.
495
+
496
+ Two helper functions are also provided:
497
+
498
+ ``pybind11_strip(target)``
499
+ Strips a target (uses ``CMAKE_STRIP`` after the target is built)
500
+
501
+ ``pybind11_extension(target)``
502
+ Sets the correct extension (with SOABI) for a target.
503
+
504
+ You can use these targets to build complex applications. For example, the
505
+ ``add_python_module`` function is identical to:
506
+
507
+ .. code-block:: cmake
508
+
509
+ cmake_minimum_required(VERSION 3.4)
510
+ project(example LANGUAGES CXX)
511
+
512
+ find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
513
+
514
+ add_library(example MODULE main.cpp)
515
+
516
+ target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras)
517
+
518
+ pybind11_extension(example)
519
+ pybind11_strip(example)
520
+
521
+ set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden"
522
+ CUDA_VISIBILITY_PRESET "hidden")
523
+
524
+ Instead of setting properties, you can set ``CMAKE_*`` variables to initialize these correctly.
525
+
526
+ .. warning::
527
+
528
+ Since pybind11 is a metatemplate library, it is crucial that certain
529
+ compiler flags are provided to ensure high quality code generation. In
530
+ contrast to the ``pybind11_add_module()`` command, the CMake interface
531
+ provides a *composable* set of targets to ensure that you retain flexibility.
532
+ It can be especially important to provide or set these properties; the
533
+ :ref:`FAQ <faq:symhidden>` contains an explanation on why these are needed.
534
+
535
+ .. versionadded:: 2.6
536
+
537
+ .. _nopython-mode:
538
+
539
+ Advanced: NOPYTHON mode
540
+ -----------------------
541
+
542
+ If you want complete control, you can set ``PYBIND11_NOPYTHON`` to completely
543
+ disable Python integration (this also happens if you run ``FindPython2`` and
544
+ ``FindPython3`` without running ``FindPython``). This gives you complete
545
+ freedom to integrate into an existing system (like `Scikit-Build's
546
+ <https://scikit-build.readthedocs.io>`_ ``PythonExtensions``).
547
+ ``pybind11_add_module`` and ``pybind11_extension`` will be unavailable, and the
548
+ targets will be missing any Python specific behavior.
549
+
550
+ .. versionadded:: 2.6
551
+
552
+ Embedding the Python interpreter
553
+ --------------------------------
554
+
555
+ In addition to extension modules, pybind11 also supports embedding Python into
556
+ a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
557
+ target. It provides everything needed to get the interpreter running. The Python
558
+ headers and libraries are attached to the target. Unlike ``pybind11::module``,
559
+ there is no need to manually set any additional properties here. For more
560
+ information about usage in C++, see :doc:`/advanced/embedding`.
561
+
562
+ .. code-block:: cmake
563
+
564
+ cmake_minimum_required(VERSION 3.4...3.18)
565
+ project(example LANGUAGES CXX)
566
+
567
+ find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
568
+
569
+ add_executable(example main.cpp)
570
+ target_link_libraries(example PRIVATE pybind11::embed)
571
+
572
+ .. _building_manually:
573
+
574
+ Building manually
575
+ =================
576
+
577
+ pybind11 is a header-only library, hence it is not necessary to link against
578
+ any special libraries and there are no intermediate (magic) translation steps.
579
+
580
+ On Linux, you can compile an example such as the one given in
581
+ :ref:`simple_example` using the following command:
582
+
583
+ .. code-block:: bash
584
+
585
+ $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
586
+
587
+ The flags given here assume that you're using Python 3. For Python 2, just
588
+ change the executable appropriately (to ``python`` or ``python2``).
589
+
590
+ The ``python3 -m pybind11 --includes`` command fetches the include paths for
591
+ both pybind11 and Python headers. This assumes that pybind11 has been installed
592
+ using ``pip`` or ``conda``. If it hasn't, you can also manually specify
593
+ ``-I <path-to-pybind11>/include`` together with the Python includes path
594
+ ``python3-config --includes``.
595
+
596
+ Note that Python 2.7 modules don't use a special suffix, so you should simply
597
+ use ``example.so`` instead of ``example$(python3-config --extension-suffix)``.
598
+ Besides, the ``--extension-suffix`` option may or may not be available, depending
599
+ on the distribution; in the latter case, the module extension can be manually
600
+ set to ``.so``.
601
+
602
+ On macOS: the build command is almost the same but it also requires passing
603
+ the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
604
+ building the module:
605
+
606
+ .. code-block:: bash
607
+
608
+ $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
609
+
610
+ In general, it is advisable to include several additional build parameters
611
+ that can considerably reduce the size of the created binary. Refer to section
612
+ :ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
613
+ build system that works on all platforms including Windows.
614
+
615
+ .. note::
616
+
617
+ On Linux and macOS, it's better to (intentionally) not link against
618
+ ``libpython``. The symbols will be resolved when the extension library
619
+ is loaded into a Python binary. This is preferable because you might
620
+ have several different installations of a given Python version (e.g. the
621
+ system-provided Python, and one that ships with a piece of commercial
622
+ software). In this way, the plugin will work with both versions, instead
623
+ of possibly importing a second Python library into a process that already
624
+ contains one (which will lead to a segfault).
625
+
626
+
627
+ Building with Bazel
628
+ ===================
629
+
630
+ You can build with the Bazel build system using the `pybind11_bazel
631
+ <https://github.com/pybind/pybind11_bazel>`_ repository.
632
+
633
+ Generating binding code automatically
634
+ =====================================
635
+
636
+ The ``Binder`` project is a tool for automatic generation of pybind11 binding
637
+ code by introspecting existing C++ codebases using LLVM/Clang. See the
638
+ [binder]_ documentation for details.
639
+
640
+ .. [binder] http://cppbinder.readthedocs.io/en/latest/about.html
641
+
642
+ [AutoWIG]_ is a Python library that wraps automatically compiled libraries into
643
+ high-level languages. It parses C++ code using LLVM/Clang technologies and
644
+ generates the wrappers using the Mako templating engine. The approach is automatic,
645
+ extensible, and applies to very complex C++ libraries, composed of thousands of
646
+ classes or incorporating modern meta-programming constructs.
647
+
648
+ .. [AutoWIG] https://github.com/StatisKit/AutoWIG
649
+
650
+ [robotpy-build]_ is a is a pure python, cross platform build tool that aims to
651
+ simplify creation of python wheels for pybind11 projects, and provide
652
+ cross-project dependency management. Additionally, it is able to autogenerate
653
+ customizable pybind11-based wrappers by parsing C++ header files.
654
+
655
+ .. [robotpy-build] https://robotpy-build.readthedocs.io
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/conf.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # pybind11 documentation build configuration file, created by
5
+ # sphinx-quickstart on Sun Oct 11 19:23:48 2015.
6
+ #
7
+ # This file is execfile()d with the current directory set to its
8
+ # containing dir.
9
+ #
10
+ # Note that not all possible configuration values are present in this
11
+ # autogenerated file.
12
+ #
13
+ # All configuration values have a default; values that are commented out
14
+ # serve to show the default.
15
+
16
+ import sys
17
+ import os
18
+ import shlex
19
+ import subprocess
20
+ from pathlib import Path
21
+ import re
22
+
23
+ DIR = Path(__file__).parent.resolve()
24
+
25
+ # If extensions (or modules to document with autodoc) are in another directory,
26
+ # add these directories to sys.path here. If the directory is relative to the
27
+ # documentation root, use os.path.abspath to make it absolute, like shown here.
28
+ # sys.path.insert(0, os.path.abspath('.'))
29
+
30
+ # -- General configuration ------------------------------------------------
31
+
32
+ # If your documentation needs a minimal Sphinx version, state it here.
33
+ # needs_sphinx = '1.0'
34
+
35
+ # Add any Sphinx extension module names here, as strings. They can be
36
+ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
37
+ # ones.
38
+ extensions = [
39
+ "breathe",
40
+ "sphinxcontrib.rsvgconverter",
41
+ "sphinxcontrib.moderncmakedomain",
42
+ ]
43
+
44
+ breathe_projects = {"pybind11": ".build/doxygenxml/"}
45
+ breathe_default_project = "pybind11"
46
+ breathe_domain_by_extension = {"h": "cpp"}
47
+
48
+ # Add any paths that contain templates here, relative to this directory.
49
+ templates_path = [".templates"]
50
+
51
+ # The suffix(es) of source filenames.
52
+ # You can specify multiple suffix as a list of string:
53
+ # source_suffix = ['.rst', '.md']
54
+ source_suffix = ".rst"
55
+
56
+ # The encoding of source files.
57
+ # source_encoding = 'utf-8-sig'
58
+
59
+ # The master toctree document.
60
+ master_doc = "index"
61
+
62
+ # General information about the project.
63
+ project = "pybind11"
64
+ copyright = "2017, Wenzel Jakob"
65
+ author = "Wenzel Jakob"
66
+
67
+ # The version info for the project you're documenting, acts as replacement for
68
+ # |version| and |release|, also used in various other places throughout the
69
+ # built documents.
70
+
71
+ # Read the listed version
72
+ with open("../pybind11/_version.py") as f:
73
+ code = compile(f.read(), "../pybind11/_version.py", "exec")
74
+ loc = {}
75
+ exec(code, loc)
76
+
77
+ # The full version, including alpha/beta/rc tags.
78
+ version = loc["__version__"]
79
+
80
+ # The language for content autogenerated by Sphinx. Refer to documentation
81
+ # for a list of supported languages.
82
+ #
83
+ # This is also used if you do content translation via gettext catalogs.
84
+ # Usually you set "language" from the command line for these cases.
85
+ language = None
86
+
87
+ # There are two options for replacing |today|: either, you set today to some
88
+ # non-false value, then it is used:
89
+ # today = ''
90
+ # Else, today_fmt is used as the format for a strftime call.
91
+ # today_fmt = '%B %d, %Y'
92
+
93
+ # List of patterns, relative to source directory, that match files and
94
+ # directories to ignore when looking for source files.
95
+ exclude_patterns = [".build", "release.rst"]
96
+
97
+ # The reST default role (used for this markup: `text`) to use for all
98
+ # documents.
99
+ default_role = "any"
100
+
101
+ # If true, '()' will be appended to :func: etc. cross-reference text.
102
+ # add_function_parentheses = True
103
+
104
+ # If true, the current module name will be prepended to all description
105
+ # unit titles (such as .. function::).
106
+ # add_module_names = True
107
+
108
+ # If true, sectionauthor and moduleauthor directives will be shown in the
109
+ # output. They are ignored by default.
110
+ # show_authors = False
111
+
112
+ # The name of the Pygments (syntax highlighting) style to use.
113
+ # pygments_style = 'monokai'
114
+
115
+ # A list of ignored prefixes for module index sorting.
116
+ # modindex_common_prefix = []
117
+
118
+ # If true, keep warnings as "system message" paragraphs in the built documents.
119
+ # keep_warnings = False
120
+
121
+ # If true, `todo` and `todoList` produce output, else they produce nothing.
122
+ todo_include_todos = False
123
+
124
+
125
+ # -- Options for HTML output ----------------------------------------------
126
+
127
+ # The theme to use for HTML and HTML Help pages. See the documentation for
128
+ # a list of builtin themes.
129
+
130
+ on_rtd = os.environ.get("READTHEDOCS", None) == "True"
131
+
132
+ if not on_rtd: # only import and set the theme if we're building docs locally
133
+ import sphinx_rtd_theme
134
+
135
+ html_theme = "sphinx_rtd_theme"
136
+ html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
137
+
138
+ html_context = {"css_files": ["_static/theme_overrides.css"]}
139
+ else:
140
+ html_context = {
141
+ "css_files": [
142
+ "//media.readthedocs.org/css/sphinx_rtd_theme.css",
143
+ "//media.readthedocs.org/css/readthedocs-doc-embed.css",
144
+ "_static/theme_overrides.css",
145
+ ]
146
+ }
147
+
148
+ # Theme options are theme-specific and customize the look and feel of a theme
149
+ # further. For a list of options available for each theme, see the
150
+ # documentation.
151
+ # html_theme_options = {}
152
+
153
+ # Add any paths that contain custom themes here, relative to this directory.
154
+ # html_theme_path = []
155
+
156
+ # The name for this set of Sphinx documents. If None, it defaults to
157
+ # "<project> v<version> documentation".
158
+ # html_title = None
159
+
160
+ # A shorter title for the navigation bar. Default is the same as html_title.
161
+ # html_short_title = None
162
+
163
+ # The name of an image file (relative to this directory) to place at the top
164
+ # of the sidebar.
165
+ # html_logo = None
166
+
167
+ # The name of an image file (within the static path) to use as favicon of the
168
+ # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
169
+ # pixels large.
170
+ # html_favicon = None
171
+
172
+ # Add any paths that contain custom static files (such as style sheets) here,
173
+ # relative to this directory. They are copied after the builtin static files,
174
+ # so a file named "default.css" will overwrite the builtin "default.css".
175
+ html_static_path = ["_static"]
176
+
177
+ # Add any extra paths that contain custom files (such as robots.txt or
178
+ # .htaccess) here, relative to this directory. These files are copied
179
+ # directly to the root of the documentation.
180
+ # html_extra_path = []
181
+
182
+ # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
183
+ # using the given strftime format.
184
+ # html_last_updated_fmt = '%b %d, %Y'
185
+
186
+ # If true, SmartyPants will be used to convert quotes and dashes to
187
+ # typographically correct entities.
188
+ # html_use_smartypants = True
189
+
190
+ # Custom sidebar templates, maps document names to template names.
191
+ # html_sidebars = {}
192
+
193
+ # Additional templates that should be rendered to pages, maps page names to
194
+ # template names.
195
+ # html_additional_pages = {}
196
+
197
+ # If false, no module index is generated.
198
+ # html_domain_indices = True
199
+
200
+ # If false, no index is generated.
201
+ # html_use_index = True
202
+
203
+ # If true, the index is split into individual pages for each letter.
204
+ # html_split_index = False
205
+
206
+ # If true, links to the reST sources are added to the pages.
207
+ # html_show_sourcelink = True
208
+
209
+ # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
210
+ # html_show_sphinx = True
211
+
212
+ # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
213
+ # html_show_copyright = True
214
+
215
+ # If true, an OpenSearch description file will be output, and all pages will
216
+ # contain a <link> tag referring to it. The value of this option must be the
217
+ # base URL from which the finished HTML is served.
218
+ # html_use_opensearch = ''
219
+
220
+ # This is the file name suffix for HTML files (e.g. ".xhtml").
221
+ # html_file_suffix = None
222
+
223
+ # Language to be used for generating the HTML full-text search index.
224
+ # Sphinx supports the following languages:
225
+ # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
226
+ # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
227
+ # html_search_language = 'en'
228
+
229
+ # A dictionary with options for the search language support, empty by default.
230
+ # Now only 'ja' uses this config value
231
+ # html_search_options = {'type': 'default'}
232
+
233
+ # The name of a javascript file (relative to the configuration directory) that
234
+ # implements a search results scorer. If empty, the default will be used.
235
+ # html_search_scorer = 'scorer.js'
236
+
237
+ # Output file base name for HTML help builder.
238
+ htmlhelp_basename = "pybind11doc"
239
+
240
+ # -- Options for LaTeX output ---------------------------------------------
241
+
242
+ latex_engine = "pdflatex"
243
+
244
+ latex_elements = {
245
+ # The paper size ('letterpaper' or 'a4paper').
246
+ # 'papersize': 'letterpaper',
247
+ #
248
+ # The font size ('10pt', '11pt' or '12pt').
249
+ # 'pointsize': '10pt',
250
+ #
251
+ # Additional stuff for the LaTeX preamble.
252
+ # remove blank pages (between the title page and the TOC, etc.)
253
+ "classoptions": ",openany,oneside",
254
+ "preamble": r"""
255
+ \usepackage{fontawesome}
256
+ \usepackage{textgreek}
257
+ \DeclareUnicodeCharacter{00A0}{}
258
+ \DeclareUnicodeCharacter{2194}{\faArrowsH}
259
+ \DeclareUnicodeCharacter{1F382}{\faBirthdayCake}
260
+ \DeclareUnicodeCharacter{1F355}{\faAdjust}
261
+ \DeclareUnicodeCharacter{0301}{'}
262
+ \DeclareUnicodeCharacter{03C0}{\textpi}
263
+
264
+ """,
265
+ # Latex figure (float) alignment
266
+ # 'figure_align': 'htbp',
267
+ }
268
+
269
+ # Grouping the document tree into LaTeX files. List of tuples
270
+ # (source start file, target name, title,
271
+ # author, documentclass [howto, manual, or own class]).
272
+ latex_documents = [
273
+ (master_doc, "pybind11.tex", "pybind11 Documentation", "Wenzel Jakob", "manual"),
274
+ ]
275
+
276
+ # The name of an image file (relative to this directory) to place at the top of
277
+ # the title page.
278
+ # latex_logo = 'pybind11-logo.png'
279
+
280
+ # For "manual" documents, if this is true, then toplevel headings are parts,
281
+ # not chapters.
282
+ # latex_use_parts = False
283
+
284
+ # If true, show page references after internal links.
285
+ # latex_show_pagerefs = False
286
+
287
+ # If true, show URL addresses after external links.
288
+ # latex_show_urls = False
289
+
290
+ # Documents to append as an appendix to all manuals.
291
+ # latex_appendices = []
292
+
293
+ # If false, no module index is generated.
294
+ # latex_domain_indices = True
295
+
296
+
297
+ # -- Options for manual page output ---------------------------------------
298
+
299
+ # One entry per manual page. List of tuples
300
+ # (source start file, name, description, authors, manual section).
301
+ man_pages = [(master_doc, "pybind11", "pybind11 Documentation", [author], 1)]
302
+
303
+ # If true, show URL addresses after external links.
304
+ # man_show_urls = False
305
+
306
+
307
+ # -- Options for Texinfo output -------------------------------------------
308
+
309
+ # Grouping the document tree into Texinfo files. List of tuples
310
+ # (source start file, target name, title, author,
311
+ # dir menu entry, description, category)
312
+ texinfo_documents = [
313
+ (
314
+ master_doc,
315
+ "pybind11",
316
+ "pybind11 Documentation",
317
+ author,
318
+ "pybind11",
319
+ "One line description of project.",
320
+ "Miscellaneous",
321
+ ),
322
+ ]
323
+
324
+ # Documents to append as an appendix to all manuals.
325
+ # texinfo_appendices = []
326
+
327
+ # If false, no module index is generated.
328
+ # texinfo_domain_indices = True
329
+
330
+ # How to display URL addresses: 'footnote', 'no', or 'inline'.
331
+ # texinfo_show_urls = 'footnote'
332
+
333
+ # If true, do not generate a @detailmenu in the "Top" node's menu.
334
+ # texinfo_no_detailmenu = False
335
+
336
+ primary_domain = "cpp"
337
+ highlight_language = "cpp"
338
+
339
+
340
+ def generate_doxygen_xml(app):
341
+ build_dir = os.path.join(app.confdir, ".build")
342
+ if not os.path.exists(build_dir):
343
+ os.mkdir(build_dir)
344
+
345
+ try:
346
+ subprocess.call(["doxygen", "--version"])
347
+ retcode = subprocess.call(["doxygen"], cwd=app.confdir)
348
+ if retcode < 0:
349
+ sys.stderr.write("doxygen error code: {}\n".format(-retcode))
350
+ except OSError as e:
351
+ sys.stderr.write("doxygen execution failed: {}\n".format(e))
352
+
353
+
354
+ def prepare(app):
355
+ with open(DIR.parent / "README.rst") as f:
356
+ contents = f.read()
357
+
358
+ if app.builder.name == "latex":
359
+ # Remove badges and stuff from start
360
+ contents = contents[contents.find(r".. start") :]
361
+
362
+ # Filter out section titles for index.rst for LaTeX
363
+ contents = re.sub(r"^(.*)\n[-~]{3,}$", r"**\1**", contents, flags=re.MULTILINE)
364
+
365
+ with open(DIR / "readme.rst", "w") as f:
366
+ f.write(contents)
367
+
368
+
369
+ def clean_up(app, exception):
370
+ (DIR / "readme.rst").unlink()
371
+
372
+
373
+ def setup(app):
374
+
375
+ # Add hook for building doxygen xml when needed
376
+ app.connect("builder-inited", generate_doxygen_xml)
377
+
378
+ # Copy the readme in
379
+ app.connect("builder-inited", prepare)
380
+
381
+ # Clean up the generated readme
382
+ app.connect("build-finished", clean_up)
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/faq.rst ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Frequently asked questions
2
+ ##########################
3
+
4
+ "ImportError: dynamic module does not define init function"
5
+ ===========================================================
6
+
7
+ 1. Make sure that the name specified in PYBIND11_MODULE is identical to the
8
+ filename of the extension library (without suffixes such as ``.so``).
9
+
10
+ 2. If the above did not fix the issue, you are likely using an incompatible
11
+ version of Python (for instance, the extension library was compiled against
12
+ Python 2, while the interpreter is running on top of some version of Python
13
+ 3, or vice versa).
14
+
15
+ "Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
16
+ ========================================================================
17
+
18
+ See the first answer.
19
+
20
+ "SystemError: dynamic module not initialized properly"
21
+ ======================================================
22
+
23
+ See the first answer.
24
+
25
+ The Python interpreter immediately crashes when importing my module
26
+ ===================================================================
27
+
28
+ See the first answer.
29
+
30
+ .. _faq_reference_arguments:
31
+
32
+ Limitations involving reference arguments
33
+ =========================================
34
+
35
+ In C++, it's fairly common to pass arguments using mutable references or
36
+ mutable pointers, which allows both read and write access to the value
37
+ supplied by the caller. This is sometimes done for efficiency reasons, or to
38
+ realize functions that have multiple return values. Here are two very basic
39
+ examples:
40
+
41
+ .. code-block:: cpp
42
+
43
+ void increment(int &i) { i++; }
44
+ void increment_ptr(int *i) { (*i)++; }
45
+
46
+ In Python, all arguments are passed by reference, so there is no general
47
+ issue in binding such code from Python.
48
+
49
+ However, certain basic Python types (like ``str``, ``int``, ``bool``,
50
+ ``float``, etc.) are **immutable**. This means that the following attempt
51
+ to port the function to Python doesn't have the same effect on the value
52
+ provided by the caller -- in fact, it does nothing at all.
53
+
54
+ .. code-block:: python
55
+
56
+ def increment(i):
57
+ i += 1 # nope..
58
+
59
+ pybind11 is also affected by such language-level conventions, which means that
60
+ binding ``increment`` or ``increment_ptr`` will also create Python functions
61
+ that don't modify their arguments.
62
+
63
+ Although inconvenient, one workaround is to encapsulate the immutable types in
64
+ a custom type that does allow modifications.
65
+
66
+ An other alternative involves binding a small wrapper lambda function that
67
+ returns a tuple with all output arguments (see the remainder of the
68
+ documentation for examples on binding lambda functions). An example:
69
+
70
+ .. code-block:: cpp
71
+
72
+ int foo(int &i) { i++; return 123; }
73
+
74
+ and the binding code
75
+
76
+ .. code-block:: cpp
77
+
78
+ m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
79
+
80
+
81
+ How can I reduce the build time?
82
+ ================================
83
+
84
+ It's good practice to split binding code over multiple files, as in the
85
+ following example:
86
+
87
+ :file:`example.cpp`:
88
+
89
+ .. code-block:: cpp
90
+
91
+ void init_ex1(py::module_ &);
92
+ void init_ex2(py::module_ &);
93
+ /* ... */
94
+
95
+ PYBIND11_MODULE(example, m) {
96
+ init_ex1(m);
97
+ init_ex2(m);
98
+ /* ... */
99
+ }
100
+
101
+ :file:`ex1.cpp`:
102
+
103
+ .. code-block:: cpp
104
+
105
+ void init_ex1(py::module_ &m) {
106
+ m.def("add", [](int a, int b) { return a + b; });
107
+ }
108
+
109
+ :file:`ex2.cpp`:
110
+
111
+ .. code-block:: cpp
112
+
113
+ void init_ex2(py::module_ &m) {
114
+ m.def("sub", [](int a, int b) { return a - b; });
115
+ }
116
+
117
+ :command:`python`:
118
+
119
+ .. code-block:: pycon
120
+
121
+ >>> import example
122
+ >>> example.add(1, 2)
123
+ 3
124
+ >>> example.sub(1, 1)
125
+ 0
126
+
127
+ As shown above, the various ``init_ex`` functions should be contained in
128
+ separate files that can be compiled independently from one another, and then
129
+ linked together into the same final shared object. Following this approach
130
+ will:
131
+
132
+ 1. reduce memory requirements per compilation unit.
133
+
134
+ 2. enable parallel builds (if desired).
135
+
136
+ 3. allow for faster incremental builds. For instance, when a single class
137
+ definition is changed, only a subset of the binding code will generally need
138
+ to be recompiled.
139
+
140
+ "recursive template instantiation exceeded maximum depth of 256"
141
+ ================================================================
142
+
143
+ If you receive an error about excessive recursive template evaluation, try
144
+ specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The
145
+ culprit is generally the generation of function signatures at compile time
146
+ using C++14 template metaprogramming.
147
+
148
+ .. _`faq:hidden_visibility`:
149
+
150
+ "‘SomeClass’ declared with greater visibility than the type of its field ‘SomeClass::member’ [-Wattributes]"
151
+ ============================================================================================================
152
+
153
+ This error typically indicates that you are compiling without the required
154
+ ``-fvisibility`` flag. pybind11 code internally forces hidden visibility on
155
+ all internal code, but if non-hidden (and thus *exported*) code attempts to
156
+ include a pybind type (for example, ``py::object`` or ``py::list``) you can run
157
+ into this warning.
158
+
159
+ To avoid it, make sure you are specifying ``-fvisibility=hidden`` when
160
+ compiling pybind code.
161
+
162
+ As to why ``-fvisibility=hidden`` is necessary, because pybind modules could
163
+ have been compiled under different versions of pybind itself, it is also
164
+ important that the symbols defined in one module do not clash with the
165
+ potentially-incompatible symbols defined in another. While Python extension
166
+ modules are usually loaded with localized symbols (under POSIX systems
167
+ typically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default
168
+ can be changed, but even if it isn't it is not always enough to guarantee
169
+ complete independence of the symbols involved when not using
170
+ ``-fvisibility=hidden``.
171
+
172
+ Additionally, ``-fvisibility=hidden`` can deliver considerably binary size
173
+ savings. (See the following section for more details.)
174
+
175
+
176
+ .. _`faq:symhidden`:
177
+
178
+ How can I create smaller binaries?
179
+ ==================================
180
+
181
+ To do its job, pybind11 extensively relies on a programming technique known as
182
+ *template metaprogramming*, which is a way of performing computation at compile
183
+ time using type information. Template metaprogramming usually instantiates code
184
+ involving significant numbers of deeply nested types that are either completely
185
+ removed or reduced to just a few instructions during the compiler's optimization
186
+ phase. However, due to the nested nature of these types, the resulting symbol
187
+ names in the compiled extension library can be extremely long. For instance,
188
+ the included test suite contains the following symbol:
189
+
190
+ .. only:: html
191
+
192
+ .. code-block:: none
193
+
194
+ _​_​Z​N​8​p​y​b​i​n​d​1​1​1​2​c​p​p​_​f​u​n​c​t​i​o​n​C​1​I​v​8​E​x​a​m​p​l​e​2​J​R​N​S​t​3​_​_​1​6​v​e​c​t​o​r​I​N​S​3​_​1​2​b​a​s​i​c​_​s​t​r​i​n​g​I​w​N​S​3​_​1​1​c​h​a​r​_​t​r​a​i​t​s​I​w​E​E​N​S​3​_​9​a​l​l​o​c​a​t​o​r​I​w​E​E​E​E​N​S​8​_​I​S​A​_​E​E​E​E​E​J​N​S​_​4​n​a​m​e​E​N​S​_​7​s​i​b​l​i​n​g​E​N​S​_​9​i​s​_​m​e​t​h​o​d​E​A​2​8​_​c​E​E​E​M​T​0​_​F​T​_​D​p​T​1​_​E​D​p​R​K​T​2​_
195
+
196
+ .. only:: not html
197
+
198
+ .. code-block:: cpp
199
+
200
+ __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
201
+
202
+ which is the mangled form of the following function type:
203
+
204
+ .. code-block:: cpp
205
+
206
+ pybind11::cpp_function::cpp_function<void, Example2, std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28])
207
+
208
+ The memory needed to store just the mangled name of this function (196 bytes)
209
+ is larger than the actual piece of code (111 bytes) it represents! On the other
210
+ hand, it's silly to even give this function a name -- after all, it's just a
211
+ tiny cog in a bigger piece of machinery that is not exposed to the outside
212
+ world. So we'll generally only want to export symbols for those functions which
213
+ are actually called from the outside.
214
+
215
+ This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
216
+ and Clang, which sets the default symbol visibility to *hidden*, which has a
217
+ tremendous impact on the final binary size of the resulting extension library.
218
+ (On Visual Studio, symbols are already hidden by default, so nothing needs to
219
+ be done there.)
220
+
221
+ In addition to decreasing binary size, ``-fvisibility=hidden`` also avoids
222
+ potential serious issues when loading multiple modules and is required for
223
+ proper pybind operation. See the previous FAQ entry for more details.
224
+
225
+ Working with ancient Visual Studio 2008 builds on Windows
226
+ =========================================================
227
+
228
+ The official Windows distributions of Python are compiled using truly
229
+ ancient versions of Visual Studio that lack good C++11 support. Some users
230
+ implicitly assume that it would be impossible to load a plugin built with
231
+ Visual Studio 2015 into a Python distribution that was compiled using Visual
232
+ Studio 2008. However, no such issue exists: it's perfectly legitimate to
233
+ interface DLLs that are built with different compilers and/or C libraries.
234
+ Common gotchas to watch out for involve not ``free()``-ing memory region
235
+ that that were ``malloc()``-ed in another shared library, using data
236
+ structures with incompatible ABIs, and so on. pybind11 is very careful not
237
+ to make these types of mistakes.
238
+
239
+ How can I properly handle Ctrl-C in long-running functions?
240
+ ===========================================================
241
+
242
+ Ctrl-C is received by the Python interpreter, and holds it until the GIL
243
+ is released, so a long-running function won't be interrupted.
244
+
245
+ To interrupt from inside your function, you can use the ``PyErr_CheckSignals()``
246
+ function, that will tell if a signal has been raised on the Python side. This
247
+ function merely checks a flag, so its impact is negligible. When a signal has
248
+ been received, you must either explicitly interrupt execution by throwing
249
+ ``py::error_already_set`` (which will propagate the existing
250
+ ``KeyboardInterrupt``), or clear the error (which you usually will not want):
251
+
252
+ .. code-block:: cpp
253
+
254
+ PYBIND11_MODULE(example, m)
255
+ {
256
+ m.def("long running_func", []()
257
+ {
258
+ for (;;) {
259
+ if (PyErr_CheckSignals() != 0)
260
+ throw py::error_already_set();
261
+ // Long running iteration
262
+ }
263
+ });
264
+ }
265
+
266
+ CMake doesn't detect the right Python version
267
+ =============================================
268
+
269
+ The CMake-based build system will try to automatically detect the installed
270
+ version of Python and link against that. When this fails, or when there are
271
+ multiple versions of Python and it finds the wrong one, delete
272
+ ``CMakeCache.txt`` and then add ``-DPYTHON_EXECUTABLE=$(which python)`` to your
273
+ CMake configure line. (Replace ``$(which python)`` with a path to python if
274
+ your prefer.)
275
+
276
+ You can alternatively try ``-DPYBIND11_FINDPYTHON=ON``, which will activate the
277
+ new CMake FindPython support instead of pybind11's custom search. Requires
278
+ CMake 3.12+, and 3.15+ or 3.18.2+ are even better. You can set this in your
279
+ ``CMakeLists.txt`` before adding or finding pybind11, as well.
280
+
281
+ Inconsistent detection of Python version in CMake and pybind11
282
+ ==============================================================
283
+
284
+ The functions ``find_package(PythonInterp)`` and ``find_package(PythonLibs)``
285
+ provided by CMake for Python version detection are modified by pybind11 due to
286
+ unreliability and limitations that make them unsuitable for pybind11's needs.
287
+ Instead pybind11 provides its own, more reliable Python detection CMake code.
288
+ Conflicts can arise, however, when using pybind11 in a project that *also* uses
289
+ the CMake Python detection in a system with several Python versions installed.
290
+
291
+ This difference may cause inconsistencies and errors if *both* mechanisms are
292
+ used in the same project. Consider the following CMake code executed in a
293
+ system with Python 2.7 and 3.x installed:
294
+
295
+ .. code-block:: cmake
296
+
297
+ find_package(PythonInterp)
298
+ find_package(PythonLibs)
299
+ find_package(pybind11)
300
+
301
+ It will detect Python 2.7 and pybind11 will pick it as well.
302
+
303
+ In contrast this code:
304
+
305
+ .. code-block:: cmake
306
+
307
+ find_package(pybind11)
308
+ find_package(PythonInterp)
309
+ find_package(PythonLibs)
310
+
311
+ will detect Python 3.x for pybind11 and may crash on
312
+ ``find_package(PythonLibs)`` afterwards.
313
+
314
+ There are three possible solutions:
315
+
316
+ 1. Avoid using ``find_package(PythonInterp)`` and ``find_package(PythonLibs)``
317
+ from CMake and rely on pybind11 in detecting Python version. If this is not
318
+ possible, the CMake machinery should be called *before* including pybind11.
319
+ 2. Set ``PYBIND11_FINDPYTHON`` to ``True`` or use ``find_package(Python
320
+ COMPONENTS Interpreter Development)`` on modern CMake (3.12+, 3.15+ better,
321
+ 3.18.2+ best). Pybind11 in these cases uses the new CMake FindPython instead
322
+ of the old, deprecated search tools, and these modules are much better at
323
+ finding the correct Python.
324
+ 3. Set ``PYBIND11_NOPYTHON`` to ``TRUE``. Pybind11 will not search for Python.
325
+ However, you will have to use the target-based system, and do more setup
326
+ yourself, because it does not know about or include things that depend on
327
+ Python, like ``pybind11_add_module``. This might be ideal for integrating
328
+ into an existing system, like scikit-build's Python helpers.
329
+
330
+ How to cite this project?
331
+ =========================
332
+
333
+ We suggest the following BibTeX template to cite pybind11 in scientific
334
+ discourse:
335
+
336
+ .. code-block:: bash
337
+
338
+ @misc{pybind11,
339
+ author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan},
340
+ year = {2017},
341
+ note = {https://github.com/pybind/pybind11},
342
+ title = {pybind11 -- Seamless operability between C++11 and Python}
343
+ }
third-party/DPVO/Pangolin/components/pango_python/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/Pangolin/components/pango_python/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/Pangolin/components/pango_python/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/Pangolin/components/pango_python/pybind11/docs/pybind11-logo.png ADDED
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/pybind11_vs_boost_python1.png ADDED
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/pybind11_vs_boost_python1.svg ADDED
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/pybind11_vs_boost_python2.png ADDED
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/pybind11_vs_boost_python2.svg ADDED
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/reference.rst ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ .. _extras:
67
+
68
+ Passing extra arguments to ``def`` or ``class_``
69
+ ================================================
70
+
71
+ .. doxygengroup:: annotations
72
+ :members:
73
+
74
+ Embedding the interpreter
75
+ =========================
76
+
77
+ .. doxygendefine:: PYBIND11_EMBEDDED_MODULE
78
+
79
+ .. doxygenfunction:: initialize_interpreter
80
+
81
+ .. doxygenfunction:: finalize_interpreter
82
+
83
+ .. doxygenclass:: scoped_interpreter
84
+
85
+ Redirecting C++ streams
86
+ =======================
87
+
88
+ .. doxygenclass:: scoped_ostream_redirect
89
+
90
+ .. doxygenclass:: scoped_estream_redirect
91
+
92
+ .. doxygenfunction:: add_ostream_redirect
93
+
94
+ Python built-in functions
95
+ =========================
96
+
97
+ .. doxygengroup:: python_builtins
98
+ :members:
99
+
100
+ Inheritance
101
+ ===========
102
+
103
+ See :doc:`/classes` and :doc:`/advanced/classes` for more detail.
104
+
105
+ .. doxygendefine:: PYBIND11_OVERRIDE
106
+
107
+ .. doxygendefine:: PYBIND11_OVERRIDE_PURE
108
+
109
+ .. doxygendefine:: PYBIND11_OVERRIDE_NAME
110
+
111
+ .. doxygendefine:: PYBIND11_OVERRIDE_PURE_NAME
112
+
113
+ .. doxygenfunction:: get_override
114
+
115
+ Exceptions
116
+ ==========
117
+
118
+ .. doxygenclass:: error_already_set
119
+ :members:
120
+
121
+ .. doxygenclass:: builtin_exception
122
+ :members:
123
+
124
+ Literals
125
+ ========
126
+
127
+ .. doxygennamespace:: literals
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/release.rst ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ - Update the version number
26
+ - Update ``PYBIND11_VERSION_MAJOR`` etc. in
27
+ ``include/pybind11/detail/common.h``. PATCH should be a simple integer.
28
+ - Update the version HEX just below, as well.
29
+ - Update ``pybind11/_version.py`` (match above)
30
+ - Ensure that all the information in ``setup.cfg`` is up-to-date, like
31
+ supported Python versions.
32
+ - Add release date in ``docs/changelog.rst``.
33
+ - Check to make sure
34
+ `needs-changelog <https://github.com/pybind/pybind11/pulls?q=is%3Apr+is%3Aclosed+label%3A%22needs+changelog%22>`_
35
+ issues are entered in the changelog (clear the label when done).
36
+ - ``git add`` and ``git commit``, ``git push``. **Ensure CI passes**. (If it
37
+ fails due to a known flake issue, either ignore or restart CI.)
38
+ - Add a release branch if this is a new minor version, or update the existing release branch if it is a patch version
39
+ - New branch: ``git checkout -b vX.Y``, ``git push -u origin vX.Y``
40
+ - Update branch: ``git checkout vX.Y``, ``git merge <release branch>``, ``git push``
41
+ - Update tags (optional; if you skip this, the GitHub release makes a
42
+ non-annotated tag for you)
43
+ - ``git tag -a vX.Y.Z -m 'vX.Y.Z release'``.
44
+ - ``git push --tags``.
45
+ - Update stable
46
+ - ``git checkout stable``
47
+ - ``git merge master``
48
+ - ``git push``
49
+ - Make a GitHub release (this shows up in the UI, sends new release
50
+ notifications to users watching releases, and also uploads PyPI packages).
51
+ (Note: if you do not use an existing tag, this creates a new lightweight tag
52
+ for you, so you could skip the above step).
53
+ - GUI method: click "Create a new release" on the far right, fill in the tag
54
+ name (if you didn't tag above, it will be made here), fill in a release
55
+ name like "Version X.Y.Z", and optionally copy-and-paste the changelog into
56
+ the description (processed as markdown by Pandoc). Check "pre-release" if
57
+ this is a beta/RC. You can get partway there with
58
+ ``cat docs/changelog.rst | pandoc -f rst -t gfm``.
59
+ - CLI method: with ``gh`` installed, run ``gh release create vX.Y.Z -t "Version X.Y.Z"``
60
+ If this is a pre-release, add ``-p``.
61
+
62
+ - Get back to work
63
+ - Make sure you are on master, not somewhere else: ``git checkout master``
64
+ - Update version macros in ``include/pybind11/detail/common.h`` (set PATCH to
65
+ ``0.dev1`` and increment MINOR).
66
+ - Update ``_version.py`` to match
67
+ - Add a spot for in-development updates in ``docs/changelog.rst``.
68
+ - ``git add``, ``git commit``, ``git push``
69
+
70
+ If a version branch is updated, remember to set PATCH to ``1.dev1``.
71
+
72
+ If you'd like to bump homebrew, run:
73
+
74
+ .. code-block::
75
+
76
+ brew bump-formula-pr --url https://github.com/pybind/pybind11/archive/vX.Y.Z.tar.gz
77
+
78
+ Conda-forge should automatically make a PR in a few hours, and automatically
79
+ merge it if there are no issues.
80
+
81
+
82
+ Manual packaging
83
+ ^^^^^^^^^^^^^^^^
84
+
85
+ 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:
86
+
87
+ .. code-block:: bash
88
+
89
+ python3 -m pip install build
90
+ python3 -m build
91
+ PYBIND11_SDIST_GLOBAL=1 python3 -m build
92
+ twine upload dist/*
93
+
94
+ This makes SDists and wheels, and the final line uploads them.
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ breathe==4.26.1
2
+ # docutils 0.17 breaks HTML tags & RTD theme
3
+ # https://github.com/sphinx-doc/sphinx/issues/9001
4
+ docutils==0.16
5
+ sphinx==3.3.1
6
+ sphinx_rtd_theme==0.5.0
7
+ sphinxcontrib-moderncmakedomain==3.17
8
+ sphinxcontrib-svg2pdfconverter==1.1.0
third-party/DPVO/Pangolin/components/pango_python/pybind11/docs/upgrade.rst ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.6:
12
+
13
+ v2.7
14
+ ====
15
+
16
+ *Before* v2.7, ``py::str`` can hold ``PyUnicodeObject`` or ``PyBytesObject``,
17
+ and ``py::isinstance<str>()`` is ``true`` for both ``py::str`` and
18
+ ``py::bytes``. Starting with v2.7, ``py::str`` exclusively holds
19
+ ``PyUnicodeObject`` (`#2409 <https://github.com/pybind/pybind11/pull/2409>`_),
20
+ and ``py::isinstance<str>()`` is ``true`` only for ``py::str``. To help in
21
+ the transition of user code, the ``PYBIND11_STR_LEGACY_PERMISSIVE`` macro
22
+ is provided as an escape hatch to go back to the legacy behavior. This macro
23
+ will be removed in future releases. Two types of required fixes are expected
24
+ to be common:
25
+
26
+ * Accidental use of ``py::str`` instead of ``py::bytes``, masked by the legacy
27
+ behavior. These are probably very easy to fix, by changing from
28
+ ``py::str`` to ``py::bytes``.
29
+
30
+ * Reliance on py::isinstance<str>(obj) being ``true`` for
31
+ ``py::bytes``. This is likely to be easy to fix in most cases by adding
32
+ ``|| py::isinstance<bytes>(obj)``, but a fix may be more involved, e.g. if
33
+ ``py::isinstance<T>`` appears in a template. Such situations will require
34
+ careful review and custom fixes.
35
+
36
+
37
+
38
+ v2.6
39
+ ====
40
+
41
+ Usage of the ``PYBIND11_OVERLOAD*`` macros and ``get_overload`` function should
42
+ be replaced by ``PYBIND11_OVERRIDE*`` and ``get_override``. In the future, the
43
+ old macros may be deprecated and removed.
44
+
45
+ ``py::module`` has been renamed ``py::module_``, but a backward compatible
46
+ typedef has been included. This change was to avoid a language change in C++20
47
+ that requires unqualified ``module`` not be placed at the start of a logical
48
+ line. Qualified usage is unaffected and the typedef will remain unless the
49
+ C++ language rules change again.
50
+
51
+ The public constructors of ``py::module_`` have been deprecated. Use
52
+ ``PYBIND11_MODULE`` or ``module_::create_extension_module`` instead.
53
+
54
+ An error is now thrown when ``__init__`` is forgotten on subclasses. This was
55
+ incorrect before, but was not checked. Add a call to ``__init__`` if it is
56
+ missing.
57
+
58
+ A ``py::type_error`` is now thrown when casting to a subclass (like
59
+ ``py::bytes`` from ``py::object``) if the conversion is not valid. Make a valid
60
+ conversion instead.
61
+
62
+ The undocumented ``h.get_type()`` method has been deprecated and replaced by
63
+ ``py::type::of(h)``.
64
+
65
+ Enums now have a ``__str__`` method pre-defined; if you want to override it,
66
+ the simplest fix is to add the new ``py::prepend()`` tag when defining
67
+ ``"__str__"``.
68
+
69
+ If ``__eq__`` defined but not ``__hash__``, ``__hash__`` is now set to
70
+ ``None``, as in normal CPython. You should add ``__hash__`` if you intended the
71
+ class to be hashable, possibly using the new ``py::hash`` shortcut.
72
+
73
+ The constructors for ``py::array`` now always take signed integers for size,
74
+ for consistency. This may lead to compiler warnings on some systems. Cast to
75
+ ``py::ssize_t`` instead of ``std::size_t``.
76
+
77
+ The ``tools/clang`` submodule and ``tools/mkdoc.py`` have been moved to a
78
+ standalone package, `pybind11-mkdoc`_. If you were using those tools, please
79
+ use them via a pip install from the new location.
80
+
81
+ The ``pybind11`` package on PyPI no longer fills the wheel "headers" slot - if
82
+ you were using the headers from this slot, they are available by requesting the
83
+ ``global`` extra, that is, ``pip install "pybind11[global]"``. (Most users will
84
+ be unaffected, as the ``pybind11/include`` location is reported by ``python -m
85
+ pybind11 --includes`` and ``pybind11.get_include()`` is still correct and has
86
+ not changed since 2.5).
87
+
88
+ .. _pybind11-mkdoc: https://github.com/pybind/pybind11-mkdoc
89
+
90
+ CMake support:
91
+ --------------
92
+
93
+ The minimum required version of CMake is now 3.4. Several details of the CMake
94
+ support have been deprecated; warnings will be shown if you need to change
95
+ something. The changes are:
96
+
97
+ * ``PYBIND11_CPP_STANDARD=<platform-flag>`` is deprecated, please use
98
+ ``CMAKE_CXX_STANDARD=<number>`` instead, or any other valid CMake CXX or CUDA
99
+ standard selection method, like ``target_compile_features``.
100
+
101
+ * If you do not request a standard, pybind11 targets will compile with the
102
+ compiler default, but not less than C++11, instead of forcing C++14 always.
103
+ If you depend on the old behavior, please use ``set(CMAKE_CXX_STANDARD 14 CACHE STRING "")``
104
+ instead.
105
+
106
+ * Direct ``pybind11::module`` usage should always be accompanied by at least
107
+ ``set(CMAKE_CXX_VISIBILITY_PRESET hidden)`` or similar - it used to try to
108
+ manually force this compiler flag (but not correctly on all compilers or with
109
+ CUDA).
110
+
111
+ * ``pybind11_add_module``'s ``SYSTEM`` argument is deprecated and does nothing;
112
+ linking now behaves like other imported libraries consistently in both
113
+ config and submodule mode, and behaves like a ``SYSTEM`` library by
114
+ default.
115
+
116
+ * If ``PYTHON_EXECUTABLE`` is not set, virtual environments (``venv``,
117
+ ``virtualenv``, and ``conda``) are prioritized over the standard search
118
+ (similar to the new FindPython mode).
119
+
120
+ In addition, the following changes may be of interest:
121
+
122
+ * ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` will be respected by
123
+ ``pybind11_add_module`` if set instead of linking to ``pybind11::lto`` or
124
+ ``pybind11::thin_lto``.
125
+
126
+ * Using ``find_package(Python COMPONENTS Interpreter Development)`` before
127
+ pybind11 will cause pybind11 to use the new Python mechanisms instead of its
128
+ own custom search, based on a patched version of classic ``FindPythonInterp``
129
+ / ``FindPythonLibs``. In the future, this may become the default. A recent
130
+ (3.15+ or 3.18.2+) version of CMake is recommended.
131
+
132
+
133
+
134
+ v2.5
135
+ ====
136
+
137
+ The Python package now includes the headers as data in the package itself, as
138
+ well as in the "headers" wheel slot. ``pybind11 --includes`` and
139
+ ``pybind11.get_include()`` report the new location, which is always correct
140
+ regardless of how pybind11 was installed, making the old ``user=`` argument
141
+ meaningless. If you are not using the function to get the location already, you
142
+ are encouraged to switch to the package location.
143
+
144
+
145
+ v2.2
146
+ ====
147
+
148
+ Deprecation of the ``PYBIND11_PLUGIN`` macro
149
+ --------------------------------------------
150
+
151
+ ``PYBIND11_MODULE`` is now the preferred way to create module entry points.
152
+ The old macro emits a compile-time deprecation warning.
153
+
154
+ .. code-block:: cpp
155
+
156
+ // old
157
+ PYBIND11_PLUGIN(example) {
158
+ py::module m("example", "documentation string");
159
+
160
+ m.def("add", [](int a, int b) { return a + b; });
161
+
162
+ return m.ptr();
163
+ }
164
+
165
+ // new
166
+ PYBIND11_MODULE(example, m) {
167
+ m.doc() = "documentation string"; // optional
168
+
169
+ m.def("add", [](int a, int b) { return a + b; });
170
+ }
171
+
172
+
173
+ New API for defining custom constructors and pickling functions
174
+ ---------------------------------------------------------------
175
+
176
+ The old placement-new custom constructors have been deprecated. The new approach
177
+ uses ``py::init()`` and factory functions to greatly improve type safety.
178
+
179
+ Placement-new can be called accidentally with an incompatible type (without any
180
+ compiler errors or warnings), or it can initialize the same object multiple times
181
+ if not careful with the Python-side ``__init__`` calls. The new-style custom
182
+ constructors prevent such mistakes. See :ref:`custom_constructors` for details.
183
+
184
+ .. code-block:: cpp
185
+
186
+ // old -- deprecated (runtime warning shown only in debug mode)
187
+ py::class<Foo>(m, "Foo")
188
+ .def("__init__", [](Foo &self, ...) {
189
+ new (&self) Foo(...); // uses placement-new
190
+ });
191
+
192
+ // new
193
+ py::class<Foo>(m, "Foo")
194
+ .def(py::init([](...) { // Note: no `self` argument
195
+ return new Foo(...); // return by raw pointer
196
+ // or: return std::make_unique<Foo>(...); // return by holder
197
+ // or: return Foo(...); // return by value (move constructor)
198
+ }));
199
+
200
+ Mirroring the custom constructor changes, ``py::pickle()`` is now the preferred
201
+ way to get and set object state. See :ref:`pickling` for details.
202
+
203
+ .. code-block:: cpp
204
+
205
+ // old -- deprecated (runtime warning shown only in debug mode)
206
+ py::class<Foo>(m, "Foo")
207
+ ...
208
+ .def("__getstate__", [](const Foo &self) {
209
+ return py::make_tuple(self.value1(), self.value2(), ...);
210
+ })
211
+ .def("__setstate__", [](Foo &self, py::tuple t) {
212
+ new (&self) Foo(t[0].cast<std::string>(), ...);
213
+ });
214
+
215
+ // new
216
+ py::class<Foo>(m, "Foo")
217
+ ...
218
+ .def(py::pickle(
219
+ [](const Foo &self) { // __getstate__
220
+ return py::make_tuple(self.value1(), self.value2(), ...); // unchanged
221
+ },
222
+ [](py::tuple t) { // __setstate__, note: no `self` argument
223
+ return new Foo(t[0].cast<std::string>(), ...);
224
+ // or: return std::make_unique<Foo>(...); // return by holder
225
+ // or: return Foo(...); // return by value (move constructor)
226
+ }
227
+ ));
228
+
229
+ For both the constructors and pickling, warnings are shown at module
230
+ initialization time (on import, not when the functions are called).
231
+ They're only visible when compiled in debug mode. Sample warning:
232
+
233
+ .. code-block:: none
234
+
235
+ pybind11-bound class 'mymodule.Foo' is using an old-style placement-new '__init__'
236
+ which has been deprecated. See the upgrade guide in pybind11's docs.
237
+
238
+
239
+ Stricter enforcement of hidden symbol visibility for pybind11 modules
240
+ ---------------------------------------------------------------------
241
+
242
+ pybind11 now tries to actively enforce hidden symbol visibility for modules.
243
+ If you're using either one of pybind11's :doc:`CMake or Python build systems
244
+ <compiling>` (the two example repositories) and you haven't been exporting any
245
+ symbols, there's nothing to be concerned about. All the changes have been done
246
+ transparently in the background. If you were building manually or relied on
247
+ specific default visibility, read on.
248
+
249
+ Setting default symbol visibility to *hidden* has always been recommended for
250
+ pybind11 (see :ref:`faq:symhidden`). On Linux and macOS, hidden symbol
251
+ visibility (in conjunction with the ``strip`` utility) yields much smaller
252
+ module binaries. `CPython's extension docs`_ also recommend hiding symbols
253
+ by default, with the goal of avoiding symbol name clashes between modules.
254
+ Starting with v2.2, pybind11 enforces this more strictly: (1) by declaring
255
+ all symbols inside the ``pybind11`` namespace as hidden and (2) by including
256
+ the ``-fvisibility=hidden`` flag on Linux and macOS (only for extension
257
+ modules, not for embedding the interpreter).
258
+
259
+ .. _CPython's extension docs: https://docs.python.org/3/extending/extending.html#providing-a-c-api-for-an-extension-module
260
+
261
+ The namespace-scope hidden visibility is done automatically in pybind11's
262
+ headers and it's generally transparent to users. It ensures that:
263
+
264
+ * Modules compiled with different pybind11 versions don't clash with each other.
265
+
266
+ * Some new features, like ``py::module_local`` bindings, can work as intended.
267
+
268
+ The ``-fvisibility=hidden`` flag applies the same visibility to user bindings
269
+ outside of the ``pybind11`` namespace. It's now set automatic by pybind11's
270
+ CMake and Python build systems, but this needs to be done manually by users
271
+ of other build systems. Adding this flag:
272
+
273
+ * Minimizes the chances of symbol conflicts between modules. E.g. if two
274
+ unrelated modules were statically linked to different (ABI-incompatible)
275
+ versions of the same third-party library, a symbol clash would be likely
276
+ (and would end with unpredictable results).
277
+
278
+ * Produces smaller binaries on Linux and macOS, as pointed out previously.
279
+
280
+ Within pybind11's CMake build system, ``pybind11_add_module`` has always been
281
+ setting the ``-fvisibility=hidden`` flag in release mode. From now on, it's
282
+ being applied unconditionally, even in debug mode and it can no longer be opted
283
+ out of with the ``NO_EXTRAS`` option. The ``pybind11::module`` target now also
284
+ adds this flag to its interface. The ``pybind11::embed`` target is unchanged.
285
+
286
+ The most significant change here is for the ``pybind11::module`` target. If you
287
+ were previously relying on default visibility, i.e. if your Python module was
288
+ doubling as a shared library with dependents, you'll need to either export
289
+ symbols manually (recommended for cross-platform libraries) or factor out the
290
+ shared library (and have the Python module link to it like the other
291
+ dependents). As a temporary workaround, you can also restore default visibility
292
+ using the CMake code below, but this is not recommended in the long run:
293
+
294
+ .. code-block:: cmake
295
+
296
+ target_link_libraries(mymodule PRIVATE pybind11::module)
297
+
298
+ add_library(restore_default_visibility INTERFACE)
299
+ target_compile_options(restore_default_visibility INTERFACE -fvisibility=default)
300
+ target_link_libraries(mymodule PRIVATE restore_default_visibility)
301
+
302
+
303
+ Local STL container bindings
304
+ ----------------------------
305
+
306
+ Previous pybind11 versions could only bind types globally -- all pybind11
307
+ modules, even unrelated ones, would have access to the same exported types.
308
+ However, this would also result in a conflict if two modules exported the
309
+ same C++ type, which is especially problematic for very common types, e.g.
310
+ ``std::vector<int>``. :ref:`module_local` were added to resolve this (see
311
+ that section for a complete usage guide).
312
+
313
+ ``py::class_`` still defaults to global bindings (because these types are
314
+ usually unique across modules), however in order to avoid clashes of opaque
315
+ types, ``py::bind_vector`` and ``py::bind_map`` will now bind STL containers
316
+ as ``py::module_local`` if their elements are: builtins (``int``, ``float``,
317
+ etc.), not bound using ``py::class_``, or bound as ``py::module_local``. For
318
+ example, this change allows multiple modules to bind ``std::vector<int>``
319
+ without causing conflicts. See :ref:`stl_bind` for more details.
320
+
321
+ When upgrading to this version, if you have multiple modules which depend on
322
+ a single global binding of an STL container, note that all modules can still
323
+ accept foreign ``py::module_local`` types in the direction of Python-to-C++.
324
+ The locality only affects the C++-to-Python direction. If this is needed in
325
+ multiple modules, you'll need to either:
326
+
327
+ * Add a copy of the same STL binding to all of the modules which need it.
328
+
329
+ * Restore the global status of that single binding by marking it
330
+ ``py::module_local(false)``.
331
+
332
+ The latter is an easy workaround, but in the long run it would be best to
333
+ localize all common type bindings in order to avoid conflicts with
334
+ third-party modules.
335
+
336
+
337
+ Negative strides for Python buffer objects and numpy arrays
338
+ -----------------------------------------------------------
339
+
340
+ Support for negative strides required changing the integer type from unsigned
341
+ to signed in the interfaces of ``py::buffer_info`` and ``py::array``. If you
342
+ have compiler warnings enabled, you may notice some new conversion warnings
343
+ after upgrading. These can be resolved using ``static_cast``.
344
+
345
+
346
+ Deprecation of some ``py::object`` APIs
347
+ ---------------------------------------
348
+
349
+ To compare ``py::object`` instances by pointer, you should now use
350
+ ``obj1.is(obj2)`` which is equivalent to ``obj1 is obj2`` in Python.
351
+ Previously, pybind11 used ``operator==`` for this (``obj1 == obj2``), but
352
+ that could be confusing and is now deprecated (so that it can eventually
353
+ be replaced with proper rich object comparison in a future release).
354
+
355
+ For classes which inherit from ``py::object``, ``borrowed`` and ``stolen``
356
+ were previously available as protected constructor tags. Now the types
357
+ should be used directly instead: ``borrowed_t{}`` and ``stolen_t{}``
358
+ (`#771 <https://github.com/pybind/pybind11/pull/771>`_).
359
+
360
+
361
+ Stricter compile-time error checking
362
+ ------------------------------------
363
+
364
+ Some error checks have been moved from run time to compile time. Notably,
365
+ automatic conversion of ``std::shared_ptr<T>`` is not possible when ``T`` is
366
+ not directly registered with ``py::class_<T>`` (e.g. ``std::shared_ptr<int>``
367
+ or ``std::shared_ptr<std::vector<T>>`` are not automatically convertible).
368
+ Attempting to bind a function with such arguments now results in a compile-time
369
+ error instead of waiting to fail at run time.
370
+
371
+ ``py::init<...>()`` constructor definitions are also stricter and now prevent
372
+ bindings which could cause unexpected behavior:
373
+
374
+ .. code-block:: cpp
375
+
376
+ struct Example {
377
+ Example(int &);
378
+ };
379
+
380
+ py::class_<Example>(m, "Example")
381
+ .def(py::init<int &>()); // OK, exact match
382
+ // .def(py::init<int>()); // compile-time error, mismatch
383
+
384
+ A non-``const`` lvalue reference is not allowed to bind to an rvalue. However,
385
+ note that a constructor taking ``const T &`` can still be registered using
386
+ ``py::init<T>()`` because a ``const`` lvalue reference can bind to an rvalue.
387
+
388
+ v2.1
389
+ ====
390
+
391
+ Minimum compiler versions are enforced at compile time
392
+ ------------------------------------------------------
393
+
394
+ The minimums also apply to v2.0 but the check is now explicit and a compile-time
395
+ error is raised if the compiler does not meet the requirements:
396
+
397
+ * GCC >= 4.8
398
+ * clang >= 3.3 (appleclang >= 5.0)
399
+ * MSVC >= 2015u3
400
+ * Intel C++ >= 15.0
401
+
402
+
403
+ The ``py::metaclass`` attribute is not required for static properties
404
+ ---------------------------------------------------------------------
405
+
406
+ Binding classes with static properties is now possible by default. The
407
+ zero-parameter version of ``py::metaclass()`` is deprecated. However, a new
408
+ one-parameter ``py::metaclass(python_type)`` version was added for rare
409
+ cases when a custom metaclass is needed to override pybind11's default.
410
+
411
+ .. code-block:: cpp
412
+
413
+ // old -- emits a deprecation warning
414
+ py::class_<Foo>(m, "Foo", py::metaclass())
415
+ .def_property_readonly_static("foo", ...);
416
+
417
+ // new -- static properties work without the attribute
418
+ py::class_<Foo>(m, "Foo")
419
+ .def_property_readonly_static("foo", ...);
420
+
421
+ // new -- advanced feature, override pybind11's default metaclass
422
+ py::class_<Bar>(m, "Bar", py::metaclass(custom_python_type))
423
+ ...
424
+
425
+
426
+ v2.0
427
+ ====
428
+
429
+ Breaking changes in ``py::class_``
430
+ ----------------------------------
431
+
432
+ These changes were necessary to make type definitions in pybind11
433
+ future-proof, to support PyPy via its ``cpyext`` mechanism (`#527
434
+ <https://github.com/pybind/pybind11/pull/527>`_), and to improve efficiency
435
+ (`rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_).
436
+
437
+ 1. Declarations of types that provide access via the buffer protocol must
438
+ now include the ``py::buffer_protocol()`` annotation as an argument to
439
+ the ``py::class_`` constructor.
440
+
441
+ .. code-block:: cpp
442
+
443
+ py::class_<Matrix>("Matrix", py::buffer_protocol())
444
+ .def(py::init<...>())
445
+ .def_buffer(...);
446
+
447
+ 2. Classes which include static properties (e.g. ``def_readwrite_static()``)
448
+ must now include the ``py::metaclass()`` attribute. Note: this requirement
449
+ has since been removed in v2.1. If you're upgrading from 1.x, it's
450
+ recommended to skip directly to v2.1 or newer.
451
+
452
+ 3. This version of pybind11 uses a redesigned mechanism for instantiating
453
+ trampoline classes that are used to override virtual methods from within
454
+ Python. This led to the following user-visible syntax change:
455
+
456
+ .. code-block:: cpp
457
+
458
+ // old v1.x syntax
459
+ py::class_<TrampolineClass>("MyClass")
460
+ .alias<MyClass>()
461
+ ...
462
+
463
+ // new v2.x syntax
464
+ py::class_<MyClass, TrampolineClass>("MyClass")
465
+ ...
466
+
467
+ Importantly, both the original and the trampoline class are now specified
468
+ as arguments to the ``py::class_`` template, and the ``alias<..>()`` call
469
+ is gone. The new scheme has zero overhead in cases when Python doesn't
470
+ override any functions of the underlying C++ class.
471
+ `rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_.
472
+
473
+ The class type must be the first template argument given to ``py::class_``
474
+ while the trampoline can be mixed in arbitrary order with other arguments
475
+ (see the following section).
476
+
477
+
478
+ Deprecation of the ``py::base<T>()`` attribute
479
+ ----------------------------------------------
480
+
481
+ ``py::base<T>()`` was deprecated in favor of specifying ``T`` as a template
482
+ argument to ``py::class_``. This new syntax also supports multiple inheritance.
483
+ Note that, while the type being exported must be the first argument in the
484
+ ``py::class_<Class, ...>`` template, the order of the following types (bases,
485
+ holder and/or trampoline) is not important.
486
+
487
+ .. code-block:: cpp
488
+
489
+ // old v1.x
490
+ py::class_<Derived>("Derived", py::base<Base>());
491
+
492
+ // new v2.x
493
+ py::class_<Derived, Base>("Derived");
494
+
495
+ // new -- multiple inheritance
496
+ py::class_<Derived, Base1, Base2>("Derived");
497
+
498
+ // new -- apart from `Derived` the argument order can be arbitrary
499
+ py::class_<Derived, Base1, Holder, Base2, Trampoline>("Derived");
500
+
501
+
502
+ Out-of-the-box support for ``std::shared_ptr``
503
+ ----------------------------------------------
504
+
505
+ The relevant type caster is now built in, so it's no longer necessary to
506
+ include a declaration of the form:
507
+
508
+ .. code-block:: cpp
509
+
510
+ PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
511
+
512
+ Continuing to do so won’t cause an error or even a deprecation warning,
513
+ but it's completely redundant.
514
+
515
+
516
+ Deprecation of a few ``py::object`` APIs
517
+ ----------------------------------------
518
+
519
+ All of the old-style calls emit deprecation warnings.
520
+
521
+ +---------------------------------------+---------------------------------------------+
522
+ | Old syntax | New syntax |
523
+ +=======================================+=============================================+
524
+ | ``obj.call(args...)`` | ``obj(args...)`` |
525
+ +---------------------------------------+---------------------------------------------+
526
+ | ``obj.str()`` | ``py::str(obj)`` |
527
+ +---------------------------------------+---------------------------------------------+
528
+ | ``auto l = py::list(obj); l.check()`` | ``py::isinstance<py::list>(obj)`` |
529
+ +---------------------------------------+---------------------------------------------+
530
+ | ``py::object(ptr, true)`` | ``py::reinterpret_borrow<py::object>(ptr)`` |
531
+ +---------------------------------------+---------------------------------------------+
532
+ | ``py::object(ptr, false)`` | ``py::reinterpret_steal<py::object>(ptr)`` |
533
+ +---------------------------------------+---------------------------------------------+
534
+ | ``if (obj.attr("foo"))`` | ``if (py::hasattr(obj, "foo"))`` |
535
+ +---------------------------------------+---------------------------------------------+
536
+ | ``if (obj["bar"])`` | ``if (obj.contains("bar"))`` |
537
+ +---------------------------------------+---------------------------------------------+
third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/attr.h ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/attr.h: Infrastructure for processing custom
3
+ type and function attributes
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <[email protected]>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "cast.h"
14
+
15
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
16
+
17
+ /// \addtogroup annotations
18
+ /// @{
19
+
20
+ /// Annotation for methods
21
+ struct is_method { handle class_; is_method(const handle &c) : class_(c) { } };
22
+
23
+ /// Annotation for operators
24
+ struct is_operator { };
25
+
26
+ /// Annotation for classes that cannot be subclassed
27
+ struct is_final { };
28
+
29
+ /// Annotation for parent scope
30
+ struct scope { handle value; scope(const handle &s) : value(s) { } };
31
+
32
+ /// Annotation for documentation
33
+ struct doc { const char *value; doc(const char *value) : value(value) { } };
34
+
35
+ /// Annotation for function names
36
+ struct name { const char *value; name(const char *value) : value(value) { } };
37
+
38
+ /// Annotation indicating that a function is an overload associated with a given "sibling"
39
+ struct sibling { handle value; sibling(const handle &value) : value(value.ptr()) { } };
40
+
41
+ /// Annotation indicating that a class derives from another given type
42
+ template <typename T> struct base {
43
+
44
+ PYBIND11_DEPRECATED("base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
45
+ base() { } // NOLINT(modernize-use-equals-default): breaks MSVC 2015 when adding an attribute
46
+ };
47
+
48
+ /// Keep patient alive while nurse lives
49
+ template <size_t Nurse, size_t Patient> struct keep_alive { };
50
+
51
+ /// Annotation indicating that a class is involved in a multiple inheritance relationship
52
+ struct multiple_inheritance { };
53
+
54
+ /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
55
+ struct dynamic_attr { };
56
+
57
+ /// Annotation which enables the buffer protocol for a type
58
+ struct buffer_protocol { };
59
+
60
+ /// Annotation which requests that a special metaclass is created for a type
61
+ struct metaclass {
62
+ handle value;
63
+
64
+ PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
65
+ // NOLINTNEXTLINE(modernize-use-equals-default): breaks MSVC 2015 when adding an attribute
66
+ metaclass() {}
67
+
68
+ /// Override pybind11's default metaclass
69
+ explicit metaclass(handle value) : value(value) { }
70
+ };
71
+
72
+ /// Annotation that marks a class as local to the module:
73
+ struct module_local { const bool value; constexpr module_local(bool v = true) : value(v) { } };
74
+
75
+ /// Annotation to mark enums as an arithmetic type
76
+ struct arithmetic { };
77
+
78
+ /// Mark a function for addition at the beginning of the existing overload chain instead of the end
79
+ struct prepend { };
80
+
81
+ /** \rst
82
+ A call policy which places one or more guard variables (``Ts...``) around the function call.
83
+
84
+ For example, this definition:
85
+
86
+ .. code-block:: cpp
87
+
88
+ m.def("foo", foo, py::call_guard<T>());
89
+
90
+ is equivalent to the following pseudocode:
91
+
92
+ .. code-block:: cpp
93
+
94
+ m.def("foo", [](args...) {
95
+ T scope_guard;
96
+ return foo(args...); // forwarded arguments
97
+ });
98
+ \endrst */
99
+ template <typename... Ts> struct call_guard;
100
+
101
+ template <> struct call_guard<> { using type = detail::void_type; };
102
+
103
+ template <typename T>
104
+ struct call_guard<T> {
105
+ static_assert(std::is_default_constructible<T>::value,
106
+ "The guard type must be default constructible");
107
+
108
+ using type = T;
109
+ };
110
+
111
+ template <typename T, typename... Ts>
112
+ struct call_guard<T, Ts...> {
113
+ struct type {
114
+ T guard{}; // Compose multiple guard types with left-to-right default-constructor order
115
+ typename call_guard<Ts...>::type next{};
116
+ };
117
+ };
118
+
119
+ /// @} annotations
120
+
121
+ PYBIND11_NAMESPACE_BEGIN(detail)
122
+ /* Forward declarations */
123
+ enum op_id : int;
124
+ enum op_type : int;
125
+ struct undefined_t;
126
+ template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
127
+ inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
128
+
129
+ /// Internal data structure which holds metadata about a keyword argument
130
+ struct argument_record {
131
+ const char *name; ///< Argument name
132
+ const char *descr; ///< Human-readable version of the argument value
133
+ handle value; ///< Associated Python object
134
+ bool convert : 1; ///< True if the argument is allowed to convert when loading
135
+ bool none : 1; ///< True if None is allowed when loading
136
+
137
+ argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
138
+ : name(name), descr(descr), value(value), convert(convert), none(none) { }
139
+ };
140
+
141
+ /// Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
142
+ struct function_record {
143
+ function_record()
144
+ : is_constructor(false), is_new_style_constructor(false), is_stateless(false),
145
+ is_operator(false), is_method(false), has_args(false),
146
+ has_kwargs(false), has_kw_only_args(false), prepend(false) { }
147
+
148
+ /// Function name
149
+ char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
150
+
151
+ // User-specified documentation string
152
+ char *doc = nullptr;
153
+
154
+ /// Human-readable version of the function signature
155
+ char *signature = nullptr;
156
+
157
+ /// List of registered keyword arguments
158
+ std::vector<argument_record> args;
159
+
160
+ /// Pointer to lambda function which converts arguments and performs the actual call
161
+ handle (*impl) (function_call &) = nullptr;
162
+
163
+ /// Storage for the wrapped function pointer and captured data, if any
164
+ void *data[3] = { };
165
+
166
+ /// Pointer to custom destructor for 'data' (if needed)
167
+ void (*free_data) (function_record *ptr) = nullptr;
168
+
169
+ /// Return value policy associated with this function
170
+ return_value_policy policy = return_value_policy::automatic;
171
+
172
+ /// True if name == '__init__'
173
+ bool is_constructor : 1;
174
+
175
+ /// True if this is a new-style `__init__` defined in `detail/init.h`
176
+ bool is_new_style_constructor : 1;
177
+
178
+ /// True if this is a stateless function pointer
179
+ bool is_stateless : 1;
180
+
181
+ /// True if this is an operator (__add__), etc.
182
+ bool is_operator : 1;
183
+
184
+ /// True if this is a method
185
+ bool is_method : 1;
186
+
187
+ /// True if the function has a '*args' argument
188
+ bool has_args : 1;
189
+
190
+ /// True if the function has a '**kwargs' argument
191
+ bool has_kwargs : 1;
192
+
193
+ /// True once a 'py::kw_only' is encountered (any following args are keyword-only)
194
+ bool has_kw_only_args : 1;
195
+
196
+ /// True if this function is to be inserted at the beginning of the overload resolution chain
197
+ bool prepend : 1;
198
+
199
+ /// Number of arguments (including py::args and/or py::kwargs, if present)
200
+ std::uint16_t nargs;
201
+
202
+ /// Number of trailing arguments (counted in `nargs`) that are keyword-only
203
+ std::uint16_t nargs_kw_only = 0;
204
+
205
+ /// Number of leading arguments (counted in `nargs`) that are positional-only
206
+ std::uint16_t nargs_pos_only = 0;
207
+
208
+ /// Python method object
209
+ PyMethodDef *def = nullptr;
210
+
211
+ /// Python handle to the parent scope (a class or a module)
212
+ handle scope;
213
+
214
+ /// Python handle to the sibling function representing an overload chain
215
+ handle sibling;
216
+
217
+ /// Pointer to next overload
218
+ function_record *next = nullptr;
219
+ };
220
+
221
+ /// Special data structure which (temporarily) holds metadata about a bound class
222
+ struct type_record {
223
+ PYBIND11_NOINLINE type_record()
224
+ : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),
225
+ default_holder(true), module_local(false), is_final(false) { }
226
+
227
+ /// Handle to the parent scope
228
+ handle scope;
229
+
230
+ /// Name of the class
231
+ const char *name = nullptr;
232
+
233
+ // Pointer to RTTI type_info data structure
234
+ const std::type_info *type = nullptr;
235
+
236
+ /// How large is the underlying C++ type?
237
+ size_t type_size = 0;
238
+
239
+ /// What is the alignment of the underlying C++ type?
240
+ size_t type_align = 0;
241
+
242
+ /// How large is the type's holder?
243
+ size_t holder_size = 0;
244
+
245
+ /// The global operator new can be overridden with a class-specific variant
246
+ void *(*operator_new)(size_t) = nullptr;
247
+
248
+ /// Function pointer to class_<..>::init_instance
249
+ void (*init_instance)(instance *, const void *) = nullptr;
250
+
251
+ /// Function pointer to class_<..>::dealloc
252
+ void (*dealloc)(detail::value_and_holder &) = nullptr;
253
+
254
+ /// List of base classes of the newly created type
255
+ list bases;
256
+
257
+ /// Optional docstring
258
+ const char *doc = nullptr;
259
+
260
+ /// Custom metaclass (optional)
261
+ handle metaclass;
262
+
263
+ /// Multiple inheritance marker
264
+ bool multiple_inheritance : 1;
265
+
266
+ /// Does the class manage a __dict__?
267
+ bool dynamic_attr : 1;
268
+
269
+ /// Does the class implement the buffer protocol?
270
+ bool buffer_protocol : 1;
271
+
272
+ /// Is the default (unique_ptr) holder type used?
273
+ bool default_holder : 1;
274
+
275
+ /// Is the class definition local to the module shared object?
276
+ bool module_local : 1;
277
+
278
+ /// Is the class inheritable from python classes?
279
+ bool is_final : 1;
280
+
281
+ PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *)) {
282
+ auto base_info = detail::get_type_info(base, false);
283
+ if (!base_info) {
284
+ std::string tname(base.name());
285
+ detail::clean_type_id(tname);
286
+ pybind11_fail("generic_type: type \"" + std::string(name) +
287
+ "\" referenced unknown base type \"" + tname + "\"");
288
+ }
289
+
290
+ if (default_holder != base_info->default_holder) {
291
+ std::string tname(base.name());
292
+ detail::clean_type_id(tname);
293
+ pybind11_fail("generic_type: type \"" + std::string(name) + "\" " +
294
+ (default_holder ? "does not have" : "has") +
295
+ " a non-default holder type while its base \"" + tname + "\" " +
296
+ (base_info->default_holder ? "does not" : "does"));
297
+ }
298
+
299
+ bases.append((PyObject *) base_info->type);
300
+
301
+ if (base_info->type->tp_dictoffset != 0)
302
+ dynamic_attr = true;
303
+
304
+ if (caster)
305
+ base_info->implicit_casts.emplace_back(type, caster);
306
+ }
307
+ };
308
+
309
+ inline function_call::function_call(const function_record &f, handle p) :
310
+ func(f), parent(p) {
311
+ args.reserve(f.nargs);
312
+ args_convert.reserve(f.nargs);
313
+ }
314
+
315
+ /// Tag for a new-style `__init__` defined in `detail/init.h`
316
+ struct is_new_style_constructor { };
317
+
318
+ /**
319
+ * Partial template specializations to process custom attributes provided to
320
+ * cpp_function_ and class_. These are either used to initialize the respective
321
+ * fields in the type_record and function_record data structures or executed at
322
+ * runtime to deal with custom call policies (e.g. keep_alive).
323
+ */
324
+ template <typename T, typename SFINAE = void> struct process_attribute;
325
+
326
+ template <typename T> struct process_attribute_default {
327
+ /// Default implementation: do nothing
328
+ static void init(const T &, function_record *) { }
329
+ static void init(const T &, type_record *) { }
330
+ static void precall(function_call &) { }
331
+ static void postcall(function_call &, handle) { }
332
+ };
333
+
334
+ /// Process an attribute specifying the function's name
335
+ template <> struct process_attribute<name> : process_attribute_default<name> {
336
+ static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
337
+ };
338
+
339
+ /// Process an attribute specifying the function's docstring
340
+ template <> struct process_attribute<doc> : process_attribute_default<doc> {
341
+ static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
342
+ };
343
+
344
+ /// Process an attribute specifying the function's docstring (provided as a C-style string)
345
+ template <> struct process_attribute<const char *> : process_attribute_default<const char *> {
346
+ static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
347
+ static void init(const char *d, type_record *r) { r->doc = const_cast<char *>(d); }
348
+ };
349
+ template <> struct process_attribute<char *> : process_attribute<const char *> { };
350
+
351
+ /// Process an attribute indicating the function's return value policy
352
+ template <> struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
353
+ static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
354
+ };
355
+
356
+ /// Process an attribute which indicates that this is an overloaded function associated with a given sibling
357
+ template <> struct process_attribute<sibling> : process_attribute_default<sibling> {
358
+ static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
359
+ };
360
+
361
+ /// Process an attribute which indicates that this function is a method
362
+ template <> struct process_attribute<is_method> : process_attribute_default<is_method> {
363
+ static void init(const is_method &s, function_record *r) { r->is_method = true; r->scope = s.class_; }
364
+ };
365
+
366
+ /// Process an attribute which indicates the parent scope of a method
367
+ template <> struct process_attribute<scope> : process_attribute_default<scope> {
368
+ static void init(const scope &s, function_record *r) { r->scope = s.value; }
369
+ };
370
+
371
+ /// Process an attribute which indicates that this function is an operator
372
+ template <> struct process_attribute<is_operator> : process_attribute_default<is_operator> {
373
+ static void init(const is_operator &, function_record *r) { r->is_operator = true; }
374
+ };
375
+
376
+ template <> struct process_attribute<is_new_style_constructor> : process_attribute_default<is_new_style_constructor> {
377
+ static void init(const is_new_style_constructor &, function_record *r) { r->is_new_style_constructor = true; }
378
+ };
379
+
380
+ inline void process_kw_only_arg(const arg &a, function_record *r) {
381
+ if (!a.name || a.name[0] == '\0')
382
+ pybind11_fail("arg(): cannot specify an unnamed argument after an kw_only() annotation");
383
+ ++r->nargs_kw_only;
384
+ }
385
+
386
+ /// Process a keyword argument attribute (*without* a default value)
387
+ template <> struct process_attribute<arg> : process_attribute_default<arg> {
388
+ static void init(const arg &a, function_record *r) {
389
+ if (r->is_method && r->args.empty())
390
+ r->args.emplace_back("self", nullptr, handle(), true /*convert*/, false /*none not allowed*/);
391
+ r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
392
+
393
+ if (r->has_kw_only_args) process_kw_only_arg(a, r);
394
+ }
395
+ };
396
+
397
+ /// Process a keyword argument attribute (*with* a default value)
398
+ template <> struct process_attribute<arg_v> : process_attribute_default<arg_v> {
399
+ static void init(const arg_v &a, function_record *r) {
400
+ if (r->is_method && r->args.empty())
401
+ r->args.emplace_back("self", nullptr /*descr*/, handle() /*parent*/, true /*convert*/, false /*none not allowed*/);
402
+
403
+ if (!a.value) {
404
+ #if !defined(NDEBUG)
405
+ std::string descr("'");
406
+ if (a.name) descr += std::string(a.name) + ": ";
407
+ descr += a.type + "'";
408
+ if (r->is_method) {
409
+ if (r->name)
410
+ descr += " in method '" + (std::string) str(r->scope) + "." + (std::string) r->name + "'";
411
+ else
412
+ descr += " in method of '" + (std::string) str(r->scope) + "'";
413
+ } else if (r->name) {
414
+ descr += " in function '" + (std::string) r->name + "'";
415
+ }
416
+ pybind11_fail("arg(): could not convert default argument "
417
+ + descr + " into a Python object (type not registered yet?)");
418
+ #else
419
+ pybind11_fail("arg(): could not convert default argument "
420
+ "into a Python object (type not registered yet?). "
421
+ "Compile in debug mode for more information.");
422
+ #endif
423
+ }
424
+ r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
425
+
426
+ if (r->has_kw_only_args) process_kw_only_arg(a, r);
427
+ }
428
+ };
429
+
430
+ /// Process a keyword-only-arguments-follow pseudo argument
431
+ template <> struct process_attribute<kw_only> : process_attribute_default<kw_only> {
432
+ static void init(const kw_only &, function_record *r) {
433
+ r->has_kw_only_args = true;
434
+ }
435
+ };
436
+
437
+ /// Process a positional-only-argument maker
438
+ template <> struct process_attribute<pos_only> : process_attribute_default<pos_only> {
439
+ static void init(const pos_only &, function_record *r) {
440
+ r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
441
+ }
442
+ };
443
+
444
+ /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees that)
445
+ template <typename T>
446
+ struct process_attribute<T, enable_if_t<is_pyobject<T>::value>> : process_attribute_default<handle> {
447
+ static void init(const handle &h, type_record *r) { r->bases.append(h); }
448
+ };
449
+
450
+ /// Process a parent class attribute (deprecated, does not support multiple inheritance)
451
+ template <typename T>
452
+ struct process_attribute<base<T>> : process_attribute_default<base<T>> {
453
+ static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
454
+ };
455
+
456
+ /// Process a multiple inheritance attribute
457
+ template <>
458
+ struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
459
+ static void init(const multiple_inheritance &, type_record *r) { r->multiple_inheritance = true; }
460
+ };
461
+
462
+ template <>
463
+ struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
464
+ static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
465
+ };
466
+
467
+ template <>
468
+ struct process_attribute<is_final> : process_attribute_default<is_final> {
469
+ static void init(const is_final &, type_record *r) { r->is_final = true; }
470
+ };
471
+
472
+ template <>
473
+ struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
474
+ static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
475
+ };
476
+
477
+ template <>
478
+ struct process_attribute<metaclass> : process_attribute_default<metaclass> {
479
+ static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
480
+ };
481
+
482
+ template <>
483
+ struct process_attribute<module_local> : process_attribute_default<module_local> {
484
+ static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
485
+ };
486
+
487
+ /// Process a 'prepend' attribute, putting this at the beginning of the overload chain
488
+ template <>
489
+ struct process_attribute<prepend> : process_attribute_default<prepend> {
490
+ static void init(const prepend &, function_record *r) { r->prepend = true; }
491
+ };
492
+
493
+ /// Process an 'arithmetic' attribute for enums (does nothing here)
494
+ template <>
495
+ struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
496
+
497
+ template <typename... Ts>
498
+ struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> { };
499
+
500
+ /**
501
+ * Process a keep_alive call policy -- invokes keep_alive_impl during the
502
+ * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
503
+ * otherwise
504
+ */
505
+ template <size_t Nurse, size_t Patient> struct process_attribute<keep_alive<Nurse, Patient>> : public process_attribute_default<keep_alive<Nurse, Patient>> {
506
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
507
+ static void precall(function_call &call) { keep_alive_impl(Nurse, Patient, call, handle()); }
508
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
509
+ static void postcall(function_call &, handle) { }
510
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
511
+ static void precall(function_call &) { }
512
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
513
+ static void postcall(function_call &call, handle ret) { keep_alive_impl(Nurse, Patient, call, ret); }
514
+ };
515
+
516
+ /// Recursively iterate over variadic template arguments
517
+ template <typename... Args> struct process_attributes {
518
+ static void init(const Args&... args, function_record *r) {
519
+ int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
520
+ ignore_unused(unused);
521
+ }
522
+ static void init(const Args&... args, type_record *r) {
523
+ int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
524
+ ignore_unused(unused);
525
+ }
526
+ static void precall(function_call &call) {
527
+ int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::precall(call), 0) ... };
528
+ ignore_unused(unused);
529
+ }
530
+ static void postcall(function_call &call, handle fn_ret) {
531
+ int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0) ... };
532
+ ignore_unused(unused);
533
+ }
534
+ };
535
+
536
+ template <typename T>
537
+ using is_call_guard = is_instantiation<call_guard, T>;
538
+
539
+ /// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
540
+ template <typename... Extra>
541
+ using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
542
+
543
+ /// Check the number of named arguments at compile time
544
+ template <typename... Extra,
545
+ size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
546
+ size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
547
+ constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
548
+ return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs;
549
+ }
550
+
551
+ PYBIND11_NAMESPACE_END(detail)
552
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/buffer_info.h ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ return strides;
26
+ }
27
+
28
+ // F-style strides; default when constructing an array_t with `ExtraFlags & f_style`
29
+ inline std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
30
+ auto ndim = shape.size();
31
+ std::vector<ssize_t> strides(ndim, itemsize);
32
+ for (size_t i = 1; i < ndim; ++i)
33
+ strides[i] = strides[i - 1] * shape[i - 1];
34
+ return strides;
35
+ }
36
+
37
+ PYBIND11_NAMESPACE_END(detail)
38
+
39
+ /// Information record describing a Python buffer object
40
+ struct buffer_info {
41
+ void *ptr = nullptr; // Pointer to the underlying storage
42
+ ssize_t itemsize = 0; // Size of individual items in bytes
43
+ ssize_t size = 0; // Total number of entries
44
+ std::string format; // For homogeneous buffers, this should be set to format_descriptor<T>::format()
45
+ ssize_t ndim = 0; // Number of dimensions
46
+ std::vector<ssize_t> shape; // Shape of the tensor (1 entry per dimension)
47
+ std::vector<ssize_t> strides; // Number of bytes between adjacent entries (for each per dimension)
48
+ bool readonly = false; // flag to indicate if the underlying storage may be written to
49
+
50
+ buffer_info() = default;
51
+
52
+ buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim,
53
+ detail::any_container<ssize_t> shape_in, detail::any_container<ssize_t> strides_in, bool readonly=false)
54
+ : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim),
55
+ shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) {
56
+ if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size())
57
+ pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length");
58
+ for (size_t i = 0; i < (size_t) ndim; ++i)
59
+ size *= shape[i];
60
+ }
61
+
62
+ template <typename T>
63
+ buffer_info(T *ptr, detail::any_container<ssize_t> shape_in, detail::any_container<ssize_t> strides_in, bool readonly=false)
64
+ : buffer_info(private_ctr_tag(), ptr, sizeof(T), format_descriptor<T>::format(), static_cast<ssize_t>(shape_in->size()), std::move(shape_in), std::move(strides_in), readonly) { }
65
+
66
+ buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t size, bool readonly=false)
67
+ : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) { }
68
+
69
+ template <typename T>
70
+ buffer_info(T *ptr, ssize_t size, bool readonly=false)
71
+ : buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size, readonly) { }
72
+
73
+ template <typename T>
74
+ buffer_info(const T *ptr, ssize_t size, bool readonly=true)
75
+ : buffer_info(const_cast<T*>(ptr), sizeof(T), format_descriptor<T>::format(), size, readonly) { }
76
+
77
+ explicit buffer_info(Py_buffer *view, bool ownview = true)
78
+ : buffer_info(view->buf, view->itemsize, view->format, view->ndim,
79
+ {view->shape, view->shape + view->ndim},
80
+ /* Though buffer::request() requests PyBUF_STRIDES, ctypes objects
81
+ * ignore this flag and return a view with NULL strides.
82
+ * When strides are NULL, build them manually. */
83
+ view->strides
84
+ ? std::vector<ssize_t>(view->strides, view->strides + view->ndim)
85
+ : detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize),
86
+ (view->readonly != 0)) {
87
+ this->m_view = view;
88
+ this->ownview = ownview;
89
+ }
90
+
91
+ buffer_info(const buffer_info &) = delete;
92
+ buffer_info& operator=(const buffer_info &) = delete;
93
+
94
+ buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); }
95
+
96
+ buffer_info &operator=(buffer_info &&rhs) noexcept {
97
+ ptr = rhs.ptr;
98
+ itemsize = rhs.itemsize;
99
+ size = rhs.size;
100
+ format = std::move(rhs.format);
101
+ ndim = rhs.ndim;
102
+ shape = std::move(rhs.shape);
103
+ strides = std::move(rhs.strides);
104
+ std::swap(m_view, rhs.m_view);
105
+ std::swap(ownview, rhs.ownview);
106
+ readonly = rhs.readonly;
107
+ return *this;
108
+ }
109
+
110
+ ~buffer_info() {
111
+ if (m_view && ownview) { PyBuffer_Release(m_view); delete m_view; }
112
+ }
113
+
114
+ Py_buffer *view() const { return m_view; }
115
+ Py_buffer *&view() { return m_view; }
116
+ private:
117
+ struct private_ctr_tag { };
118
+
119
+ buffer_info(private_ctr_tag, void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim,
120
+ detail::any_container<ssize_t> &&shape_in, detail::any_container<ssize_t> &&strides_in, bool readonly)
121
+ : buffer_info(ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) { }
122
+
123
+ Py_buffer *m_view = nullptr;
124
+ bool ownview = false;
125
+ };
126
+
127
+ PYBIND11_NAMESPACE_BEGIN(detail)
128
+
129
+ template <typename T, typename SFINAE = void> struct compare_buffer_info {
130
+ static bool compare(const buffer_info& b) {
131
+ return b.format == format_descriptor<T>::format() && b.itemsize == (ssize_t) sizeof(T);
132
+ }
133
+ };
134
+
135
+ template <typename T> struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
136
+ static bool compare(const buffer_info& b) {
137
+ return (size_t) b.itemsize == sizeof(T) && (b.format == format_descriptor<T>::value ||
138
+ ((sizeof(T) == sizeof(long)) && b.format == (std::is_unsigned<T>::value ? "L" : "l")) ||
139
+ ((sizeof(T) == sizeof(size_t)) && b.format == (std::is_unsigned<T>::value ? "N" : "n")));
140
+ }
141
+ };
142
+
143
+ PYBIND11_NAMESPACE_END(detail)
144
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/cast.h ADDED
@@ -0,0 +1,1408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 "pytypes.h"
14
+ #include "detail/common.h"
15
+ #include "detail/descr.h"
16
+ #include "detail/type_caster_base.h"
17
+ #include "detail/typeid.h"
18
+ #include <array>
19
+ #include <cstring>
20
+ #include <functional>
21
+ #include <iosfwd>
22
+ #include <iterator>
23
+ #include <memory>
24
+ #include <string>
25
+ #include <tuple>
26
+ #include <type_traits>
27
+ #include <utility>
28
+ #include <vector>
29
+
30
+ #if defined(PYBIND11_CPP17)
31
+ # if defined(__has_include)
32
+ # if __has_include(<string_view>)
33
+ # define PYBIND11_HAS_STRING_VIEW
34
+ # endif
35
+ # elif defined(_MSC_VER)
36
+ # define PYBIND11_HAS_STRING_VIEW
37
+ # endif
38
+ #endif
39
+ #ifdef PYBIND11_HAS_STRING_VIEW
40
+ #include <string_view>
41
+ #endif
42
+
43
+ #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
44
+ # define PYBIND11_HAS_U8STRING
45
+ #endif
46
+
47
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
48
+ PYBIND11_NAMESPACE_BEGIN(detail)
49
+
50
+ template <typename type, typename SFINAE = void> class type_caster : public type_caster_base<type> { };
51
+ template <typename type> using make_caster = type_caster<intrinsic_t<type>>;
52
+
53
+ // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
54
+ template <typename T> typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
55
+ return caster.operator typename make_caster<T>::template cast_op_type<T>();
56
+ }
57
+ template <typename T> typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
58
+ cast_op(make_caster<T> &&caster) {
59
+ return std::move(caster).operator
60
+ typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>();
61
+ }
62
+
63
+ template <typename type> class type_caster<std::reference_wrapper<type>> {
64
+ private:
65
+ using caster_t = make_caster<type>;
66
+ caster_t subcaster;
67
+ using reference_t = type&;
68
+ using subcaster_cast_op_type =
69
+ typename caster_t::template cast_op_type<reference_t>;
70
+
71
+ static_assert(std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value ||
72
+ std::is_same<reference_t, subcaster_cast_op_type>::value,
73
+ "std::reference_wrapper<T> caster requires T to have a caster with an "
74
+ "`operator T &()` or `operator const T &()`");
75
+ public:
76
+ bool load(handle src, bool convert) { return subcaster.load(src, convert); }
77
+ static constexpr auto name = caster_t::name;
78
+ static handle cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
79
+ // It is definitely wrong to take ownership of this pointer, so mask that rvp
80
+ if (policy == return_value_policy::take_ownership || policy == return_value_policy::automatic)
81
+ policy = return_value_policy::automatic_reference;
82
+ return caster_t::cast(&src.get(), policy, parent);
83
+ }
84
+ template <typename T> using cast_op_type = std::reference_wrapper<type>;
85
+ operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
86
+ };
87
+
88
+ #define PYBIND11_TYPE_CASTER(type, py_name) \
89
+ protected: \
90
+ type value; \
91
+ \
92
+ public: \
93
+ static constexpr auto name = py_name; \
94
+ template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0> \
95
+ static handle cast(T_ *src, return_value_policy policy, handle parent) { \
96
+ if (!src) \
97
+ return none().release(); \
98
+ if (policy == return_value_policy::take_ownership) { \
99
+ auto h = cast(std::move(*src), policy, parent); \
100
+ delete src; \
101
+ return h; \
102
+ } \
103
+ return cast(*src, policy, parent); \
104
+ } \
105
+ operator type *() { return &value; } \
106
+ operator type &() { return value; } \
107
+ operator type &&() && { return std::move(value); } \
108
+ template <typename T_> \
109
+ using cast_op_type = pybind11::detail::movable_cast_op_type<T_>
110
+
111
+ template <typename CharT> using is_std_char_type = any_of<
112
+ std::is_same<CharT, char>, /* std::string */
113
+ #if defined(PYBIND11_HAS_U8STRING)
114
+ std::is_same<CharT, char8_t>, /* std::u8string */
115
+ #endif
116
+ std::is_same<CharT, char16_t>, /* std::u16string */
117
+ std::is_same<CharT, char32_t>, /* std::u32string */
118
+ std::is_same<CharT, wchar_t> /* std::wstring */
119
+ >;
120
+
121
+
122
+ template <typename T>
123
+ struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
124
+ using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
125
+ using _py_type_1 = conditional_t<std::is_signed<T>::value, _py_type_0, typename std::make_unsigned<_py_type_0>::type>;
126
+ using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
127
+ public:
128
+
129
+ bool load(handle src, bool convert) {
130
+ py_type py_value;
131
+
132
+ if (!src)
133
+ return false;
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
+ } else if (PyFloat_Check(src.ptr())) {
149
+ return false;
150
+ } else if (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr())) {
151
+ return false;
152
+ } else {
153
+ handle src_or_index = src;
154
+ #if PY_VERSION_HEX < 0x03080000
155
+ object index;
156
+ if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
157
+ index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
158
+ if (!index) {
159
+ PyErr_Clear();
160
+ if (!convert)
161
+ return false;
162
+ }
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 || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T) && py_value != (py_type) (T) py_value)) {
183
+ PyErr_Clear();
184
+ if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
185
+ auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
186
+ ? PyNumber_Float(src.ptr())
187
+ : PyNumber_Long(src.ptr()));
188
+ PyErr_Clear();
189
+ return load(tmp, false);
190
+ }
191
+ return false;
192
+ }
193
+
194
+ value = (T) py_value;
195
+ return true;
196
+ }
197
+
198
+ template<typename U = T>
199
+ static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
200
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
201
+ return PyFloat_FromDouble((double) src);
202
+ }
203
+
204
+ template<typename U = T>
205
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) <= sizeof(long)), handle>::type
206
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
207
+ return PYBIND11_LONG_FROM_SIGNED((long) src);
208
+ }
209
+
210
+ template<typename U = T>
211
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) <= sizeof(unsigned long)), handle>::type
212
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
213
+ return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
214
+ }
215
+
216
+ template<typename U = T>
217
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) > sizeof(long)), handle>::type
218
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
219
+ return PyLong_FromLongLong((long long) src);
220
+ }
221
+
222
+ template<typename U = T>
223
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) > sizeof(unsigned long)), handle>::type
224
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
225
+ return PyLong_FromUnsignedLongLong((unsigned long long) src);
226
+ }
227
+
228
+ PYBIND11_TYPE_CASTER(T, _<std::is_integral<T>::value>("int", "float"));
229
+ };
230
+
231
+ template<typename T> struct void_caster {
232
+ public:
233
+ bool load(handle src, bool) {
234
+ if (src && src.is_none())
235
+ return true;
236
+ return false;
237
+ }
238
+ static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
239
+ return none().inc_ref();
240
+ }
241
+ PYBIND11_TYPE_CASTER(T, _("None"));
242
+ };
243
+
244
+ template <> class type_caster<void_type> : public void_caster<void_type> {};
245
+
246
+ template <> class type_caster<void> : public type_caster<void_type> {
247
+ public:
248
+ using type_caster<void_type>::cast;
249
+
250
+ bool load(handle h, bool) {
251
+ if (!h) {
252
+ return false;
253
+ }
254
+ if (h.is_none()) {
255
+ value = nullptr;
256
+ return true;
257
+ }
258
+
259
+ /* Check if this is a capsule */
260
+ if (isinstance<capsule>(h)) {
261
+ value = reinterpret_borrow<capsule>(h);
262
+ return true;
263
+ }
264
+
265
+ /* Check if this is a C++ type */
266
+ auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
267
+ if (bases.size() == 1) { // Only allowing loading from a single-value type
268
+ value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
269
+ return true;
270
+ }
271
+
272
+ /* Fail */
273
+ return false;
274
+ }
275
+
276
+ static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
277
+ if (ptr)
278
+ return capsule(ptr).release();
279
+ return none().inc_ref();
280
+ }
281
+
282
+ template <typename T> using cast_op_type = void*&;
283
+ operator void *&() { return value; }
284
+ static constexpr auto name = _("capsule");
285
+ private:
286
+ void *value = nullptr;
287
+ };
288
+
289
+ template <> class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> { };
290
+
291
+ template <> class type_caster<bool> {
292
+ public:
293
+ bool load(handle src, bool convert) {
294
+ if (!src) return false;
295
+ if (src.ptr() == Py_True) {
296
+ value = true;
297
+ return true;
298
+ }
299
+ if (src.ptr() == Py_False) {
300
+ value = false;
301
+ return true;
302
+ }
303
+ if (convert || (std::strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name) == 0)) {
304
+ // (allow non-implicit conversion for numpy booleans)
305
+
306
+ Py_ssize_t res = -1;
307
+ if (src.is_none()) {
308
+ res = 0; // None is implicitly converted to False
309
+ }
310
+ #if defined(PYPY_VERSION)
311
+ // On PyPy, check that "__bool__" (or "__nonzero__" on Python 2.7) attr exists
312
+ else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
313
+ res = PyObject_IsTrue(src.ptr());
314
+ }
315
+ #else
316
+ // Alternate approach for CPython: this does the same as the above, but optimized
317
+ // using the CPython API so as to avoid an unneeded attribute lookup.
318
+ else if (auto tp_as_number = src.ptr()->ob_type->tp_as_number) {
319
+ if (PYBIND11_NB_BOOL(tp_as_number)) {
320
+ res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
321
+ }
322
+ }
323
+ #endif
324
+ if (res == 0 || res == 1) {
325
+ value = (res != 0);
326
+ return true;
327
+ }
328
+ PyErr_Clear();
329
+ }
330
+ return false;
331
+ }
332
+ static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
333
+ return handle(src ? Py_True : Py_False).inc_ref();
334
+ }
335
+ PYBIND11_TYPE_CASTER(bool, _("bool"));
336
+ };
337
+
338
+ // Helper class for UTF-{8,16,32} C++ stl strings:
339
+ template <typename StringType, bool IsView = false> struct string_caster {
340
+ using CharT = typename StringType::value_type;
341
+
342
+ // Simplify life by being able to assume standard char sizes (the standard only guarantees
343
+ // minimums, but Python requires exact sizes)
344
+ static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1, "Unsupported char size != 1");
345
+ #if defined(PYBIND11_HAS_U8STRING)
346
+ static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1, "Unsupported char8_t size != 1");
347
+ #endif
348
+ static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2, "Unsupported char16_t size != 2");
349
+ static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4, "Unsupported char32_t size != 4");
350
+ // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
351
+ static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
352
+ "Unsupported wchar_t size != 2/4");
353
+ static constexpr size_t UTF_N = 8 * sizeof(CharT);
354
+
355
+ bool load(handle src, bool) {
356
+ #if PY_MAJOR_VERSION < 3
357
+ object temp;
358
+ #endif
359
+ handle load_src = src;
360
+ if (!src) {
361
+ return false;
362
+ }
363
+ if (!PyUnicode_Check(load_src.ptr())) {
364
+ #if PY_MAJOR_VERSION >= 3
365
+ return load_bytes(load_src);
366
+ #else
367
+ if (std::is_same<CharT, char>::value) {
368
+ return load_bytes(load_src);
369
+ }
370
+
371
+ // The below is a guaranteed failure in Python 3 when PyUnicode_Check returns false
372
+ if (!PYBIND11_BYTES_CHECK(load_src.ptr()))
373
+ return false;
374
+
375
+ temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
376
+ if (!temp) { PyErr_Clear(); return false; }
377
+ load_src = temp;
378
+ #endif
379
+ }
380
+
381
+ auto utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
382
+ load_src.ptr(), UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr));
383
+ if (!utfNbytes) { PyErr_Clear(); return false; }
384
+
385
+ const auto *buffer = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
386
+ size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
387
+ if (UTF_N > 8) { buffer++; length--; } // Skip BOM for UTF-16/32
388
+ value = StringType(buffer, length);
389
+
390
+ // If we're loading a string_view we need to keep the encoded Python object alive:
391
+ if (IsView)
392
+ loader_life_support::add_patient(utfNbytes);
393
+
394
+ return true;
395
+ }
396
+
397
+ static handle cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
398
+ const char *buffer = reinterpret_cast<const char *>(src.data());
399
+ auto nbytes = ssize_t(src.size() * sizeof(CharT));
400
+ handle s = decode_utfN(buffer, nbytes);
401
+ if (!s) throw error_already_set();
402
+ return s;
403
+ }
404
+
405
+ PYBIND11_TYPE_CASTER(StringType, _(PYBIND11_STRING_NAME));
406
+
407
+ private:
408
+ static handle decode_utfN(const char *buffer, ssize_t nbytes) {
409
+ #if !defined(PYPY_VERSION)
410
+ return
411
+ UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr) :
412
+ UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr) :
413
+ PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
414
+ #else
415
+ // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as well),
416
+ // so bypass the whole thing by just passing the encoding as a string value, which works properly:
417
+ return PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr);
418
+ #endif
419
+ }
420
+
421
+ // When loading into a std::string or char*, accept a bytes object as-is (i.e.
422
+ // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
423
+ // which supports loading a unicode from a str, doesn't take this path.
424
+ template <typename C = CharT>
425
+ bool load_bytes(enable_if_t<std::is_same<C, char>::value, handle> src) {
426
+ if (PYBIND11_BYTES_CHECK(src.ptr())) {
427
+ // We were passed a Python 3 raw bytes; accept it into a std::string or char*
428
+ // without any encoding attempt.
429
+ const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
430
+ if (bytes) {
431
+ value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
432
+ return true;
433
+ }
434
+ }
435
+
436
+ return false;
437
+ }
438
+
439
+ template <typename C = CharT>
440
+ bool load_bytes(enable_if_t<!std::is_same<C, char>::value, handle>) { return false; }
441
+ };
442
+
443
+ template <typename CharT, class Traits, class Allocator>
444
+ struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_std_char_type<CharT>::value>>
445
+ : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
446
+
447
+ #ifdef PYBIND11_HAS_STRING_VIEW
448
+ template <typename CharT, class Traits>
449
+ struct type_caster<std::basic_string_view<CharT, Traits>, enable_if_t<is_std_char_type<CharT>::value>>
450
+ : string_caster<std::basic_string_view<CharT, Traits>, true> {};
451
+ #endif
452
+
453
+ // Type caster for C-style strings. We basically use a std::string type caster, but also add the
454
+ // ability to use None as a nullptr char* (which the string caster doesn't allow).
455
+ template <typename CharT> struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
456
+ using StringType = std::basic_string<CharT>;
457
+ using StringCaster = type_caster<StringType>;
458
+ StringCaster str_caster;
459
+ bool none = false;
460
+ CharT one_char = 0;
461
+ public:
462
+ bool load(handle src, bool convert) {
463
+ if (!src) return false;
464
+ if (src.is_none()) {
465
+ // Defer accepting None to other overloads (if we aren't in convert mode):
466
+ if (!convert) return false;
467
+ none = true;
468
+ return true;
469
+ }
470
+ return str_caster.load(src, convert);
471
+ }
472
+
473
+ static handle cast(const CharT *src, return_value_policy policy, handle parent) {
474
+ if (src == nullptr) return pybind11::none().inc_ref();
475
+ return StringCaster::cast(StringType(src), policy, parent);
476
+ }
477
+
478
+ static handle cast(CharT src, return_value_policy policy, handle parent) {
479
+ if (std::is_same<char, CharT>::value) {
480
+ handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
481
+ if (!s) throw error_already_set();
482
+ return s;
483
+ }
484
+ return StringCaster::cast(StringType(1, src), policy, parent);
485
+ }
486
+
487
+ operator CharT*() { return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str()); }
488
+ operator CharT&() {
489
+ if (none)
490
+ throw value_error("Cannot convert None to a character");
491
+
492
+ auto &value = static_cast<StringType &>(str_caster);
493
+ size_t str_len = value.size();
494
+ if (str_len == 0)
495
+ throw value_error("Cannot convert empty string to a character");
496
+
497
+ // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
498
+ // is too high, and one for multiple unicode characters (caught later), so we need to figure
499
+ // out how long the first encoded character is in bytes to distinguish between these two
500
+ // errors. We also allow want to allow unicode characters U+0080 through U+00FF, as those
501
+ // can fit into a single char value.
502
+ if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
503
+ auto v0 = static_cast<unsigned char>(value[0]);
504
+ // low bits only: 0-127
505
+ // 0b110xxxxx - start of 2-byte sequence
506
+ // 0b1110xxxx - start of 3-byte sequence
507
+ // 0b11110xxx - start of 4-byte sequence
508
+ size_t char0_bytes = (v0 & 0x80) == 0 ? 1
509
+ : (v0 & 0xE0) == 0xC0 ? 2
510
+ : (v0 & 0xF0) == 0xE0 ? 3
511
+ : 4;
512
+
513
+ if (char0_bytes == str_len) {
514
+ // If we have a 128-255 value, we can decode it into a single char:
515
+ if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
516
+ one_char = static_cast<CharT>(((v0 & 3) << 6) + (static_cast<unsigned char>(value[1]) & 0x3F));
517
+ return one_char;
518
+ }
519
+ // Otherwise we have a single character, but it's > U+00FF
520
+ throw value_error("Character code point not in range(0x100)");
521
+ }
522
+ }
523
+
524
+ // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
525
+ // surrogate pair with total length 2 instantly indicates a range error (but not a "your
526
+ // string was too long" error).
527
+ else if (StringCaster::UTF_N == 16 && str_len == 2) {
528
+ one_char = static_cast<CharT>(value[0]);
529
+ if (one_char >= 0xD800 && one_char < 0xE000)
530
+ throw value_error("Character code point not in range(0x10000)");
531
+ }
532
+
533
+ if (str_len != 1)
534
+ throw value_error("Expected a character, but multi-character string found");
535
+
536
+ one_char = value[0];
537
+ return one_char;
538
+ }
539
+
540
+ static constexpr auto name = _(PYBIND11_STRING_NAME);
541
+ template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>;
542
+ };
543
+
544
+ // Base implementation for std::tuple and std::pair
545
+ template <template<typename...> class Tuple, typename... Ts> class tuple_caster {
546
+ using type = Tuple<Ts...>;
547
+ static constexpr auto size = sizeof...(Ts);
548
+ using indices = make_index_sequence<size>;
549
+ public:
550
+
551
+ bool load(handle src, bool convert) {
552
+ if (!isinstance<sequence>(src))
553
+ return false;
554
+ const auto seq = reinterpret_borrow<sequence>(src);
555
+ if (seq.size() != size)
556
+ return false;
557
+ return load_impl(seq, convert, indices{});
558
+ }
559
+
560
+ template <typename T>
561
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
562
+ return cast_impl(std::forward<T>(src), policy, parent, indices{});
563
+ }
564
+
565
+ // copied from the PYBIND11_TYPE_CASTER macro
566
+ template <typename T>
567
+ static handle cast(T *src, return_value_policy policy, handle parent) {
568
+ if (!src) return none().release();
569
+ if (policy == return_value_policy::take_ownership) {
570
+ auto h = cast(std::move(*src), policy, parent);
571
+ delete src;
572
+ return h;
573
+ }
574
+ return cast(*src, policy, parent);
575
+ }
576
+
577
+ static constexpr auto name = _("Tuple[") + concat(make_caster<Ts>::name...) + _("]");
578
+
579
+ template <typename T> using cast_op_type = type;
580
+
581
+ operator type() & { return implicit_cast(indices{}); }
582
+ operator type() && { return std::move(*this).implicit_cast(indices{}); }
583
+
584
+ protected:
585
+ template <size_t... Is>
586
+ type implicit_cast(index_sequence<Is...>) & { return type(cast_op<Ts>(std::get<Is>(subcasters))...); }
587
+ template <size_t... Is>
588
+ type implicit_cast(index_sequence<Is...>) && { return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...); }
589
+
590
+ static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
591
+
592
+ template <size_t... Is>
593
+ bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
594
+ #ifdef __cpp_fold_expressions
595
+ if ((... || !std::get<Is>(subcasters).load(seq[Is], convert)))
596
+ return false;
597
+ #else
598
+ for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...})
599
+ if (!r)
600
+ return false;
601
+ #endif
602
+ return true;
603
+ }
604
+
605
+ /* Implementation: Convert a C++ tuple into a Python tuple */
606
+ template <typename T, size_t... Is>
607
+ static handle cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
608
+ std::array<object, size> entries{{
609
+ reinterpret_steal<object>(make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...
610
+ }};
611
+ for (const auto &entry: entries)
612
+ if (!entry)
613
+ return handle();
614
+ tuple result(size);
615
+ int counter = 0;
616
+ for (auto & entry: entries)
617
+ PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
618
+ return result.release();
619
+ }
620
+
621
+ Tuple<make_caster<Ts>...> subcasters;
622
+ };
623
+
624
+ template <typename T1, typename T2> class type_caster<std::pair<T1, T2>>
625
+ : public tuple_caster<std::pair, T1, T2> {};
626
+
627
+ template <typename... Ts> class type_caster<std::tuple<Ts...>>
628
+ : public tuple_caster<std::tuple, Ts...> {};
629
+
630
+ /// Helper class which abstracts away certain actions. Users can provide specializations for
631
+ /// custom holders, but it's only necessary if the type has a non-standard interface.
632
+ template <typename T>
633
+ struct holder_helper {
634
+ static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
635
+ };
636
+
637
+ /// Type caster for holder types like std::shared_ptr, etc.
638
+ /// The SFINAE hook is provided to help work around the current lack of support
639
+ /// for smart-pointer interoperability. Please consider it an implementation
640
+ /// detail that may change in the future, as formal support for smart-pointer
641
+ /// interoperability is added into pybind11.
642
+ template <typename type, typename holder_type, typename SFINAE = void>
643
+ struct copyable_holder_caster : public type_caster_base<type> {
644
+ public:
645
+ using base = type_caster_base<type>;
646
+ static_assert(std::is_base_of<base, type_caster<type>>::value,
647
+ "Holder classes are only supported for custom types");
648
+ using base::base;
649
+ using base::cast;
650
+ using base::typeinfo;
651
+ using base::value;
652
+
653
+ bool load(handle src, bool convert) {
654
+ return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
655
+ }
656
+
657
+ explicit operator type*() { return this->value; }
658
+ // static_cast works around compiler error with MSVC 17 and CUDA 10.2
659
+ // see issue #2180
660
+ explicit operator type&() { return *(static_cast<type *>(this->value)); }
661
+ explicit operator holder_type*() { return std::addressof(holder); }
662
+ explicit operator holder_type&() { return holder; }
663
+
664
+ static handle cast(const holder_type &src, return_value_policy, handle) {
665
+ const auto *ptr = holder_helper<holder_type>::get(src);
666
+ return type_caster_base<type>::cast_holder(ptr, &src);
667
+ }
668
+
669
+ protected:
670
+ friend class type_caster_generic;
671
+ void check_holder_compat() {
672
+ if (typeinfo->default_holder)
673
+ throw cast_error("Unable to load a custom holder type from a default-holder instance");
674
+ }
675
+
676
+ bool load_value(value_and_holder &&v_h) {
677
+ if (v_h.holder_constructed()) {
678
+ value = v_h.value_ptr();
679
+ holder = v_h.template holder<holder_type>();
680
+ return true;
681
+ }
682
+ throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
683
+ #if defined(NDEBUG)
684
+ "(compile in debug mode for type information)");
685
+ #else
686
+ "of type '"
687
+ + type_id<holder_type>() + "''");
688
+ #endif
689
+ }
690
+
691
+ template <typename T = holder_type, detail::enable_if_t<!std::is_constructible<T, const T &, type*>::value, int> = 0>
692
+ bool try_implicit_casts(handle, bool) { return false; }
693
+
694
+ template <typename T = holder_type, detail::enable_if_t<std::is_constructible<T, const T &, type*>::value, int> = 0>
695
+ bool try_implicit_casts(handle src, bool convert) {
696
+ for (auto &cast : typeinfo->implicit_casts) {
697
+ copyable_holder_caster sub_caster(*cast.first);
698
+ if (sub_caster.load(src, convert)) {
699
+ value = cast.second(sub_caster.value);
700
+ holder = holder_type(sub_caster.holder, (type *) value);
701
+ return true;
702
+ }
703
+ }
704
+ return false;
705
+ }
706
+
707
+ static bool try_direct_conversions(handle) { return false; }
708
+
709
+
710
+ holder_type holder;
711
+ };
712
+
713
+ /// Specialize for the common std::shared_ptr, so users don't need to
714
+ template <typename T>
715
+ class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> { };
716
+
717
+ /// Type caster for holder types like std::unique_ptr.
718
+ /// Please consider the SFINAE hook an implementation detail, as explained
719
+ /// in the comment for the copyable_holder_caster.
720
+ template <typename type, typename holder_type, typename SFINAE = void>
721
+ struct move_only_holder_caster {
722
+ static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
723
+ "Holder classes are only supported for custom types");
724
+
725
+ static handle cast(holder_type &&src, return_value_policy, handle) {
726
+ auto *ptr = holder_helper<holder_type>::get(src);
727
+ return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
728
+ }
729
+ static constexpr auto name = type_caster_base<type>::name;
730
+ };
731
+
732
+ template <typename type, typename deleter>
733
+ class type_caster<std::unique_ptr<type, deleter>>
734
+ : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> { };
735
+
736
+ template <typename type, typename holder_type>
737
+ using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
738
+ copyable_holder_caster<type, holder_type>,
739
+ move_only_holder_caster<type, holder_type>>;
740
+
741
+ template <typename T, bool Value = false> struct always_construct_holder { static constexpr bool value = Value; };
742
+
743
+ /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
744
+ #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
745
+ namespace pybind11 { namespace detail { \
746
+ template <typename type> \
747
+ struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { }; \
748
+ template <typename type> \
749
+ class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
750
+ : public type_caster_holder<type, holder_type> { }; \
751
+ }}
752
+
753
+ // PYBIND11_DECLARE_HOLDER_TYPE holder types:
754
+ template <typename base, typename holder> struct is_holder_type :
755
+ std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
756
+ // Specialization for always-supported unique_ptr holders:
757
+ template <typename base, typename deleter> struct is_holder_type<base, std::unique_ptr<base, deleter>> :
758
+ std::true_type {};
759
+
760
+ template <typename T> struct handle_type_name { static constexpr auto name = _<T>(); };
761
+ template <> struct handle_type_name<bytes> { static constexpr auto name = _(PYBIND11_BYTES_NAME); };
762
+ template <> struct handle_type_name<int_> { static constexpr auto name = _("int"); };
763
+ template <> struct handle_type_name<iterable> { static constexpr auto name = _("Iterable"); };
764
+ template <> struct handle_type_name<iterator> { static constexpr auto name = _("Iterator"); };
765
+ template <> struct handle_type_name<none> { static constexpr auto name = _("None"); };
766
+ template <> struct handle_type_name<args> { static constexpr auto name = _("*args"); };
767
+ template <> struct handle_type_name<kwargs> { static constexpr auto name = _("**kwargs"); };
768
+
769
+ template <typename type>
770
+ struct pyobject_caster {
771
+ template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
772
+ bool load(handle src, bool /* convert */) { value = src; return static_cast<bool>(value); }
773
+
774
+ template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
775
+ bool load(handle src, bool /* convert */) {
776
+ #if PY_MAJOR_VERSION < 3 && !defined(PYBIND11_STR_LEGACY_PERMISSIVE)
777
+ // For Python 2, without this implicit conversion, Python code would
778
+ // need to be cluttered with six.ensure_text() or similar, only to be
779
+ // un-cluttered later after Python 2 support is dropped.
780
+ if (std::is_same<T, str>::value && isinstance<bytes>(src)) {
781
+ PyObject *str_from_bytes = PyUnicode_FromEncodedObject(src.ptr(), "utf-8", nullptr);
782
+ if (!str_from_bytes) throw error_already_set();
783
+ value = reinterpret_steal<type>(str_from_bytes);
784
+ return true;
785
+ }
786
+ #endif
787
+ if (!isinstance<type>(src))
788
+ return false;
789
+ value = reinterpret_borrow<type>(src);
790
+ return true;
791
+ }
792
+
793
+ static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
794
+ return src.inc_ref();
795
+ }
796
+ PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
797
+ };
798
+
799
+ template <typename T>
800
+ class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> { };
801
+
802
+ // Our conditions for enabling moving are quite restrictive:
803
+ // At compile time:
804
+ // - T needs to be a non-const, non-pointer, non-reference type
805
+ // - type_caster<T>::operator T&() must exist
806
+ // - the type must be move constructible (obviously)
807
+ // At run-time:
808
+ // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
809
+ // must have ref_count() == 1)h
810
+ // If any of the above are not satisfied, we fall back to copying.
811
+ template <typename T> using move_is_plain_type = satisfies_none_of<T,
812
+ std::is_void, std::is_pointer, std::is_reference, std::is_const
813
+ >;
814
+ template <typename T, typename SFINAE = void> struct move_always : std::false_type {};
815
+ template <typename T> struct move_always<T, enable_if_t<all_of<
816
+ move_is_plain_type<T>,
817
+ negation<is_copy_constructible<T>>,
818
+ std::is_move_constructible<T>,
819
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
820
+ >::value>> : std::true_type {};
821
+ template <typename T, typename SFINAE = void> struct move_if_unreferenced : std::false_type {};
822
+ template <typename T> struct move_if_unreferenced<T, enable_if_t<all_of<
823
+ move_is_plain_type<T>,
824
+ negation<move_always<T>>,
825
+ std::is_move_constructible<T>,
826
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
827
+ >::value>> : std::true_type {};
828
+ template <typename T> using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
829
+
830
+ // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
831
+ // reference or pointer to a local variable of the type_caster. Basically, only
832
+ // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
833
+ // everything else returns a reference/pointer to a local variable.
834
+ template <typename type> using cast_is_temporary_value_reference = bool_constant<
835
+ (std::is_reference<type>::value || std::is_pointer<type>::value) &&
836
+ !std::is_base_of<type_caster_generic, make_caster<type>>::value &&
837
+ !std::is_same<intrinsic_t<type>, void>::value
838
+ >;
839
+
840
+ // When a value returned from a C++ function is being cast back to Python, we almost always want to
841
+ // force `policy = move`, regardless of the return value policy the function/method was declared
842
+ // with.
843
+ template <typename Return, typename SFINAE = void> struct return_value_policy_override {
844
+ static return_value_policy policy(return_value_policy p) { return p; }
845
+ };
846
+
847
+ template <typename Return> struct return_value_policy_override<Return,
848
+ detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
849
+ static return_value_policy policy(return_value_policy p) {
850
+ return !std::is_lvalue_reference<Return>::value &&
851
+ !std::is_pointer<Return>::value
852
+ ? return_value_policy::move : p;
853
+ }
854
+ };
855
+
856
+ // Basic python -> C++ casting; throws if casting fails
857
+ template <typename T, typename SFINAE> type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
858
+ if (!conv.load(handle, true)) {
859
+ #if defined(NDEBUG)
860
+ throw cast_error("Unable to cast Python instance to C++ type (compile in debug mode for details)");
861
+ #else
862
+ throw cast_error("Unable to cast Python instance of type " +
863
+ (std::string) str(type::handle_of(handle)) + " to C++ type '" + type_id<T>() + "'");
864
+ #endif
865
+ }
866
+ return conv;
867
+ }
868
+ // Wrapper around the above that also constructs and returns a type_caster
869
+ template <typename T> make_caster<T> load_type(const handle &handle) {
870
+ make_caster<T> conv;
871
+ load_type(conv, handle);
872
+ return conv;
873
+ }
874
+
875
+ PYBIND11_NAMESPACE_END(detail)
876
+
877
+ // pytype -> C++ type
878
+ template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
879
+ T cast(const handle &handle) {
880
+ using namespace detail;
881
+ static_assert(!cast_is_temporary_value_reference<T>::value,
882
+ "Unable to cast type to reference: value is local to type caster");
883
+ return cast_op<T>(load_type<T>(handle));
884
+ }
885
+
886
+ // pytype -> pytype (calls converting constructor)
887
+ template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
888
+ T cast(const handle &handle) { return T(reinterpret_borrow<object>(handle)); }
889
+
890
+ // C++ type -> py::object
891
+ template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
892
+ object cast(T &&value, return_value_policy policy = return_value_policy::automatic_reference,
893
+ handle parent = handle()) {
894
+ using no_ref_T = typename std::remove_reference<T>::type;
895
+ if (policy == return_value_policy::automatic)
896
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership :
897
+ std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move;
898
+ else if (policy == return_value_policy::automatic_reference)
899
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference :
900
+ std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move;
901
+ return reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
902
+ }
903
+
904
+ template <typename T> T handle::cast() const { return pybind11::cast<T>(*this); }
905
+ template <> inline void handle::cast() const { return; }
906
+
907
+ template <typename T>
908
+ detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
909
+ if (obj.ref_count() > 1)
910
+ #if defined(NDEBUG)
911
+ throw cast_error("Unable to cast Python instance to C++ rvalue: instance has multiple references"
912
+ " (compile in debug mode for details)");
913
+ #else
914
+ throw cast_error("Unable to move from Python " + (std::string) str(type::handle_of(obj)) +
915
+ " instance to C++ " + type_id<T>() + " instance: instance has multiple references");
916
+ #endif
917
+
918
+ // Move into a temporary and return that, because the reference may be a local value of `conv`
919
+ T ret = std::move(detail::load_type<T>(obj).operator T&());
920
+ return ret;
921
+ }
922
+
923
+ // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
924
+ // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
925
+ // object has multiple references, but trying to copy will fail to compile.
926
+ // - If both movable and copyable, check ref count: if 1, move; otherwise copy
927
+ // - Otherwise (not movable), copy.
928
+ template <typename T> detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) {
929
+ return move<T>(std::move(object));
930
+ }
931
+ template <typename T> detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) {
932
+ if (object.ref_count() > 1)
933
+ return cast<T>(object);
934
+ return move<T>(std::move(object));
935
+ }
936
+ template <typename T> detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) {
937
+ return cast<T>(object);
938
+ }
939
+
940
+ template <typename T> T object::cast() const & { return pybind11::cast<T>(*this); }
941
+ template <typename T> T object::cast() && { return pybind11::cast<T>(std::move(*this)); }
942
+ template <> inline void object::cast() const & { return; }
943
+ template <> inline void object::cast() && { return; }
944
+
945
+ PYBIND11_NAMESPACE_BEGIN(detail)
946
+
947
+ // Declared in pytypes.h:
948
+ template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
949
+ object object_or_cast(T &&o) { return pybind11::cast(std::forward<T>(o)); }
950
+
951
+ struct override_unused {}; // Placeholder type for the unneeded (and dead code) static variable in the PYBIND11_OVERRIDE_OVERRIDE macro
952
+ template <typename ret_type> using override_caster_t = conditional_t<
953
+ cast_is_temporary_value_reference<ret_type>::value, make_caster<ret_type>, override_unused>;
954
+
955
+ // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
956
+ // store the result in the given variable. For other types, this is a no-op.
957
+ template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o, make_caster<T> &caster) {
958
+ return cast_op<T>(load_type(caster, o));
959
+ }
960
+ template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&, override_unused &) {
961
+ pybind11_fail("Internal error: cast_ref fallback invoked"); }
962
+
963
+ // Trampoline use: Having a pybind11::cast with an invalid reference type is going to static_assert, even
964
+ // though if it's in dead code, so we provide a "trampoline" to pybind11::cast that only does anything in
965
+ // cases where pybind11::cast is valid.
966
+ template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&o) {
967
+ return pybind11::cast<T>(std::move(o)); }
968
+ template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
969
+ pybind11_fail("Internal error: cast_safe fallback invoked"); }
970
+ template <> inline void cast_safe<void>(object &&) {}
971
+
972
+ PYBIND11_NAMESPACE_END(detail)
973
+
974
+ // The overloads could coexist, i.e. the #if is not strictly speaking needed,
975
+ // but it is an easy minor optimization.
976
+ #if defined(NDEBUG)
977
+ inline cast_error cast_error_unable_to_convert_call_arg() {
978
+ return cast_error(
979
+ "Unable to convert call argument to Python object (compile in debug mode for details)");
980
+ }
981
+ #else
982
+ inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
983
+ const std::string &type) {
984
+ return cast_error("Unable to convert call argument '" + name + "' of type '" + type
985
+ + "' to Python object");
986
+ }
987
+ #endif
988
+
989
+ template <return_value_policy policy = return_value_policy::automatic_reference>
990
+ tuple make_tuple() { return tuple(0); }
991
+
992
+ template <return_value_policy policy = return_value_policy::automatic_reference,
993
+ typename... Args> tuple make_tuple(Args&&... args_) {
994
+ constexpr size_t size = sizeof...(Args);
995
+ std::array<object, size> args {
996
+ { reinterpret_steal<object>(detail::make_caster<Args>::cast(
997
+ std::forward<Args>(args_), policy, nullptr))... }
998
+ };
999
+ for (size_t i = 0; i < args.size(); i++) {
1000
+ if (!args[i]) {
1001
+ #if defined(NDEBUG)
1002
+ throw cast_error_unable_to_convert_call_arg();
1003
+ #else
1004
+ std::array<std::string, size> argtypes { {type_id<Args>()...} };
1005
+ throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
1006
+ #endif
1007
+ }
1008
+ }
1009
+ tuple result(size);
1010
+ int counter = 0;
1011
+ for (auto &arg_value : args)
1012
+ PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1013
+ return result;
1014
+ }
1015
+
1016
+ /// \ingroup annotations
1017
+ /// Annotation for arguments
1018
+ struct arg {
1019
+ /// Constructs an argument with the name of the argument; if null or omitted, this is a positional argument.
1020
+ constexpr explicit arg(const char *name = nullptr) : name(name), flag_noconvert(false), flag_none(true) { }
1021
+ /// Assign a value to this argument
1022
+ template <typename T> arg_v operator=(T &&value) const;
1023
+ /// Indicate that the type should not be converted in the type caster
1024
+ arg &noconvert(bool flag = true) { flag_noconvert = flag; return *this; }
1025
+ /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
1026
+ arg &none(bool flag = true) { flag_none = flag; return *this; }
1027
+
1028
+ const char *name; ///< If non-null, this is a named kwargs argument
1029
+ bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type caster!)
1030
+ bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
1031
+ };
1032
+
1033
+ /// \ingroup annotations
1034
+ /// Annotation for arguments with values
1035
+ struct arg_v : arg {
1036
+ private:
1037
+ template <typename T>
1038
+ arg_v(arg &&base, T &&x, const char *descr = nullptr)
1039
+ : arg(base),
1040
+ value(reinterpret_steal<object>(
1041
+ detail::make_caster<T>::cast(x, return_value_policy::automatic, {})
1042
+ )),
1043
+ descr(descr)
1044
+ #if !defined(NDEBUG)
1045
+ , type(type_id<T>())
1046
+ #endif
1047
+ {
1048
+ // Workaround! See:
1049
+ // https://github.com/pybind/pybind11/issues/2336
1050
+ // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
1051
+ if (PyErr_Occurred()) {
1052
+ PyErr_Clear();
1053
+ }
1054
+ }
1055
+
1056
+ public:
1057
+ /// Direct construction with name, default, and description
1058
+ template <typename T>
1059
+ arg_v(const char *name, T &&x, const char *descr = nullptr)
1060
+ : arg_v(arg(name), std::forward<T>(x), descr) { }
1061
+
1062
+ /// Called internally when invoking `py::arg("a") = value`
1063
+ template <typename T>
1064
+ arg_v(const arg &base, T &&x, const char *descr = nullptr)
1065
+ : arg_v(arg(base), std::forward<T>(x), descr) { }
1066
+
1067
+ /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
1068
+ arg_v &noconvert(bool flag = true) { arg::noconvert(flag); return *this; }
1069
+
1070
+ /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
1071
+ arg_v &none(bool flag = true) { arg::none(flag); return *this; }
1072
+
1073
+ /// The default value
1074
+ object value;
1075
+ /// The (optional) description of the default value
1076
+ const char *descr;
1077
+ #if !defined(NDEBUG)
1078
+ /// The C++ type name of the default value (only available when compiled in debug mode)
1079
+ std::string type;
1080
+ #endif
1081
+ };
1082
+
1083
+ /// \ingroup annotations
1084
+ /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of an
1085
+ /// unnamed '*' argument (in Python 3)
1086
+ struct kw_only {};
1087
+
1088
+ /// \ingroup annotations
1089
+ /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of an
1090
+ /// unnamed '/' argument (in Python 3.8)
1091
+ struct pos_only {};
1092
+
1093
+ template <typename T>
1094
+ arg_v arg::operator=(T &&value) const {
1095
+ return {*this, std::forward<T>(value)};
1096
+ }
1097
+
1098
+ /// Alias for backward compatibility -- to be removed in version 2.0
1099
+ template <typename /*unused*/> using arg_t = arg_v;
1100
+
1101
+ inline namespace literals {
1102
+ /** \rst
1103
+ String literal version of `arg`
1104
+ \endrst */
1105
+ constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
1106
+ } // namespace literals
1107
+
1108
+ PYBIND11_NAMESPACE_BEGIN(detail)
1109
+
1110
+ // forward declaration (definition in attr.h)
1111
+ struct function_record;
1112
+
1113
+ /// Internal data associated with a single function call
1114
+ struct function_call {
1115
+ function_call(const function_record &f, handle p); // Implementation in attr.h
1116
+
1117
+ /// The function data:
1118
+ const function_record &func;
1119
+
1120
+ /// Arguments passed to the function:
1121
+ std::vector<handle> args;
1122
+
1123
+ /// The `convert` value the arguments should be loaded with
1124
+ std::vector<bool> args_convert;
1125
+
1126
+ /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
1127
+ /// present, are also in `args` but without a reference).
1128
+ object args_ref, kwargs_ref;
1129
+
1130
+ /// The parent, if any
1131
+ handle parent;
1132
+
1133
+ /// If this is a call to an initializer, this argument contains `self`
1134
+ handle init_self;
1135
+ };
1136
+
1137
+
1138
+ /// Helper class which loads arguments for C++ functions called from Python
1139
+ template <typename... Args>
1140
+ class argument_loader {
1141
+ using indices = make_index_sequence<sizeof...(Args)>;
1142
+
1143
+ template <typename Arg> using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
1144
+ template <typename Arg> using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
1145
+ // Get args/kwargs argument positions relative to the end of the argument list:
1146
+ static constexpr auto args_pos = constexpr_first<argument_is_args, Args...>() - (int) sizeof...(Args),
1147
+ kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int) sizeof...(Args);
1148
+
1149
+ static constexpr bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1;
1150
+
1151
+ static_assert(args_kwargs_are_last, "py::args/py::kwargs are only permitted as the last argument(s) of a function");
1152
+
1153
+ public:
1154
+ static constexpr bool has_kwargs = kwargs_pos < 0;
1155
+ static constexpr bool has_args = args_pos < 0;
1156
+
1157
+ static constexpr auto arg_names = concat(type_descr(make_caster<Args>::name)...);
1158
+
1159
+ bool load_args(function_call &call) {
1160
+ return load_impl_sequence(call, indices{});
1161
+ }
1162
+
1163
+ template <typename Return, typename Guard, typename Func>
1164
+ enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
1165
+ return std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
1166
+ }
1167
+
1168
+ template <typename Return, typename Guard, typename Func>
1169
+ enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
1170
+ std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
1171
+ return void_type();
1172
+ }
1173
+
1174
+ private:
1175
+
1176
+ static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
1177
+
1178
+ template <size_t... Is>
1179
+ bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
1180
+ #ifdef __cpp_fold_expressions
1181
+ if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])))
1182
+ return false;
1183
+ #else
1184
+ for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...})
1185
+ if (!r)
1186
+ return false;
1187
+ #endif
1188
+ return true;
1189
+ }
1190
+
1191
+ template <typename Return, typename Func, size_t... Is, typename Guard>
1192
+ Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
1193
+ return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
1194
+ }
1195
+
1196
+ std::tuple<make_caster<Args>...> argcasters;
1197
+ };
1198
+
1199
+ /// Helper class which collects only positional arguments for a Python function call.
1200
+ /// A fancier version below can collect any argument, but this one is optimal for simple calls.
1201
+ template <return_value_policy policy>
1202
+ class simple_collector {
1203
+ public:
1204
+ template <typename... Ts>
1205
+ explicit simple_collector(Ts &&...values)
1206
+ : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) { }
1207
+
1208
+ const tuple &args() const & { return m_args; }
1209
+ dict kwargs() const { return {}; }
1210
+
1211
+ tuple args() && { return std::move(m_args); }
1212
+
1213
+ /// Call a Python function and pass the collected arguments
1214
+ object call(PyObject *ptr) const {
1215
+ PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
1216
+ if (!result)
1217
+ throw error_already_set();
1218
+ return reinterpret_steal<object>(result);
1219
+ }
1220
+
1221
+ private:
1222
+ tuple m_args;
1223
+ };
1224
+
1225
+ /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
1226
+ template <return_value_policy policy>
1227
+ class unpacking_collector {
1228
+ public:
1229
+ template <typename... Ts>
1230
+ explicit unpacking_collector(Ts &&...values) {
1231
+ // Tuples aren't (easily) resizable so a list is needed for collection,
1232
+ // but the actual function call strictly requires a tuple.
1233
+ auto args_list = list();
1234
+ int _[] = { 0, (process(args_list, std::forward<Ts>(values)), 0)... };
1235
+ ignore_unused(_);
1236
+
1237
+ m_args = std::move(args_list);
1238
+ }
1239
+
1240
+ const tuple &args() const & { return m_args; }
1241
+ const dict &kwargs() const & { return m_kwargs; }
1242
+
1243
+ tuple args() && { return std::move(m_args); }
1244
+ dict kwargs() && { return std::move(m_kwargs); }
1245
+
1246
+ /// Call a Python function and pass the collected arguments
1247
+ object call(PyObject *ptr) const {
1248
+ PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
1249
+ if (!result)
1250
+ throw error_already_set();
1251
+ return reinterpret_steal<object>(result);
1252
+ }
1253
+
1254
+ private:
1255
+ template <typename T>
1256
+ void process(list &args_list, T &&x) {
1257
+ auto o = reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
1258
+ if (!o) {
1259
+ #if defined(NDEBUG)
1260
+ throw cast_error_unable_to_convert_call_arg();
1261
+ #else
1262
+ throw cast_error_unable_to_convert_call_arg(
1263
+ std::to_string(args_list.size()), type_id<T>());
1264
+ #endif
1265
+ }
1266
+ args_list.append(o);
1267
+ }
1268
+
1269
+ void process(list &args_list, detail::args_proxy ap) {
1270
+ for (auto a : ap)
1271
+ args_list.append(a);
1272
+ }
1273
+
1274
+ void process(list &/*args_list*/, arg_v a) {
1275
+ if (!a.name)
1276
+ #if defined(NDEBUG)
1277
+ nameless_argument_error();
1278
+ #else
1279
+ nameless_argument_error(a.type);
1280
+ #endif
1281
+
1282
+ if (m_kwargs.contains(a.name)) {
1283
+ #if defined(NDEBUG)
1284
+ multiple_values_error();
1285
+ #else
1286
+ multiple_values_error(a.name);
1287
+ #endif
1288
+ }
1289
+ if (!a.value) {
1290
+ #if defined(NDEBUG)
1291
+ throw cast_error_unable_to_convert_call_arg();
1292
+ #else
1293
+ throw cast_error_unable_to_convert_call_arg(a.name, a.type);
1294
+ #endif
1295
+ }
1296
+ m_kwargs[a.name] = a.value;
1297
+ }
1298
+
1299
+ void process(list &/*args_list*/, detail::kwargs_proxy kp) {
1300
+ if (!kp)
1301
+ return;
1302
+ for (auto k : reinterpret_borrow<dict>(kp)) {
1303
+ if (m_kwargs.contains(k.first)) {
1304
+ #if defined(NDEBUG)
1305
+ multiple_values_error();
1306
+ #else
1307
+ multiple_values_error(str(k.first));
1308
+ #endif
1309
+ }
1310
+ m_kwargs[k.first] = k.second;
1311
+ }
1312
+ }
1313
+
1314
+ [[noreturn]] static void nameless_argument_error() {
1315
+ throw type_error("Got kwargs without a name; only named arguments "
1316
+ "may be passed via py::arg() to a python function call. "
1317
+ "(compile in debug mode for details)");
1318
+ }
1319
+ [[noreturn]] static void nameless_argument_error(const std::string &type) {
1320
+ throw type_error("Got kwargs without a name of type '" + type + "'; only named "
1321
+ "arguments may be passed via py::arg() to a python function call. ");
1322
+ }
1323
+ [[noreturn]] static void multiple_values_error() {
1324
+ throw type_error("Got multiple values for keyword argument "
1325
+ "(compile in debug mode for details)");
1326
+ }
1327
+
1328
+ [[noreturn]] static void multiple_values_error(const std::string &name) {
1329
+ throw type_error("Got multiple values for keyword argument '" + name + "'");
1330
+ }
1331
+
1332
+ private:
1333
+ tuple m_args;
1334
+ dict m_kwargs;
1335
+ };
1336
+
1337
+ // [workaround(intel)] Separate function required here
1338
+ // We need to put this into a separate function because the Intel compiler
1339
+ // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
1340
+ // (tested with ICC 2021.1 Beta 20200827).
1341
+ template <typename... Args>
1342
+ constexpr bool args_are_all_positional()
1343
+ {
1344
+ return all_of<is_positional<Args>...>::value;
1345
+ }
1346
+
1347
+ /// Collect only positional arguments for a Python function call
1348
+ template <return_value_policy policy, typename... Args,
1349
+ typename = enable_if_t<args_are_all_positional<Args...>()>>
1350
+ simple_collector<policy> collect_arguments(Args &&...args) {
1351
+ return simple_collector<policy>(std::forward<Args>(args)...);
1352
+ }
1353
+
1354
+ /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
1355
+ template <return_value_policy policy, typename... Args,
1356
+ typename = enable_if_t<!args_are_all_positional<Args...>()>>
1357
+ unpacking_collector<policy> collect_arguments(Args &&...args) {
1358
+ // Following argument order rules for generalized unpacking according to PEP 448
1359
+ static_assert(
1360
+ constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>()
1361
+ && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(),
1362
+ "Invalid function call: positional args must precede keywords and ** unpacking; "
1363
+ "* unpacking must precede ** unpacking"
1364
+ );
1365
+ return unpacking_collector<policy>(std::forward<Args>(args)...);
1366
+ }
1367
+
1368
+ template <typename Derived>
1369
+ template <return_value_policy policy, typename... Args>
1370
+ object object_api<Derived>::operator()(Args &&...args) const {
1371
+ #if !defined(NDEBUG) && PY_VERSION_HEX >= 0x03060000
1372
+ if (!PyGILState_Check()) {
1373
+ pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
1374
+ }
1375
+ #endif
1376
+ return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
1377
+ }
1378
+
1379
+ template <typename Derived>
1380
+ template <return_value_policy policy, typename... Args>
1381
+ object object_api<Derived>::call(Args &&...args) const {
1382
+ return operator()<policy>(std::forward<Args>(args)...);
1383
+ }
1384
+
1385
+ PYBIND11_NAMESPACE_END(detail)
1386
+
1387
+
1388
+ template<typename T>
1389
+ handle type::handle_of() {
1390
+ static_assert(
1391
+ std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
1392
+ "py::type::of<T> only supports the case where T is a registered C++ types."
1393
+ );
1394
+
1395
+ return detail::get_type_handle(typeid(T), true);
1396
+ }
1397
+
1398
+
1399
+ #define PYBIND11_MAKE_OPAQUE(...) \
1400
+ namespace pybind11 { namespace detail { \
1401
+ template<> class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { }; \
1402
+ }}
1403
+
1404
+ /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
1405
+ /// typedef, e.g.: `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
1406
+ #define PYBIND11_TYPE(...) __VA_ARGS__
1407
+
1408
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/chrono.h ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <mutex>
19
+
20
+ #include <time.h>
21
+
22
+ #include <datetime.h>
23
+
24
+ // Backport the PyDateTime_DELTA functions from Python3.3 if required
25
+ #ifndef PyDateTime_DELTA_GET_DAYS
26
+ #define PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta*)o)->days)
27
+ #endif
28
+ #ifndef PyDateTime_DELTA_GET_SECONDS
29
+ #define PyDateTime_DELTA_GET_SECONDS(o) (((PyDateTime_Delta*)o)->seconds)
30
+ #endif
31
+ #ifndef PyDateTime_DELTA_GET_MICROSECONDS
32
+ #define PyDateTime_DELTA_GET_MICROSECONDS(o) (((PyDateTime_Delta*)o)->microseconds)
33
+ #endif
34
+
35
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
36
+ PYBIND11_NAMESPACE_BEGIN(detail)
37
+
38
+ template <typename type> class duration_caster {
39
+ public:
40
+ using rep = typename type::rep;
41
+ using period = typename type::period;
42
+
43
+ using days = std::chrono::duration<int_least32_t, std::ratio<86400>>; // signed 25 bits required by the standard.
44
+
45
+ bool load(handle src, bool) {
46
+ using namespace std::chrono;
47
+
48
+ // Lazy initialise the PyDateTime import
49
+ if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
50
+
51
+ if (!src) return false;
52
+ // If invoked with datetime.delta object
53
+ if (PyDelta_Check(src.ptr())) {
54
+ value = type(duration_cast<duration<rep, period>>(
55
+ days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
56
+ + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
57
+ + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
58
+ return true;
59
+ }
60
+ // If invoked with a float we assume it is seconds and convert
61
+ if (PyFloat_Check(src.ptr())) {
62
+ value = type(duration_cast<duration<rep, period>>(duration<double>(PyFloat_AsDouble(src.ptr()))));
63
+ return true;
64
+ }
65
+ return false;
66
+ }
67
+
68
+ // If this is a duration just return it back
69
+ static const std::chrono::duration<rep, period>& get_duration(const std::chrono::duration<rep, period> &src) {
70
+ return src;
71
+ }
72
+
73
+ // If this is a time_point get the time_since_epoch
74
+ template <typename Clock> static std::chrono::duration<rep, period> get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
75
+ return src.time_since_epoch();
76
+ }
77
+
78
+ static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
79
+ using namespace std::chrono;
80
+
81
+ // Use overloaded function to get our duration from our source
82
+ // Works out if it is a duration or time_point and get the duration
83
+ auto d = get_duration(src);
84
+
85
+ // Lazy initialise the PyDateTime import
86
+ if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
87
+
88
+ // Declare these special duration types so the conversions happen with the correct primitive types (int)
89
+ using dd_t = duration<int, std::ratio<86400>>;
90
+ using ss_t = duration<int, std::ratio<1>>;
91
+ using us_t = duration<int, std::micro>;
92
+
93
+ auto dd = duration_cast<dd_t>(d);
94
+ auto subd = d - dd;
95
+ auto ss = duration_cast<ss_t>(subd);
96
+ auto us = duration_cast<us_t>(subd - ss);
97
+ return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
98
+ }
99
+
100
+ PYBIND11_TYPE_CASTER(type, _("datetime.timedelta"));
101
+ };
102
+
103
+ inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
104
+ #if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
105
+ if (localtime_s(buf, time))
106
+ return nullptr;
107
+ return buf;
108
+ #else
109
+ static std::mutex mtx;
110
+ std::lock_guard<std::mutex> lock(mtx);
111
+ std::tm *tm_ptr = localtime(time);
112
+ if (tm_ptr != nullptr) {
113
+ *buf = *tm_ptr;
114
+ }
115
+ return tm_ptr;
116
+ #endif
117
+ }
118
+
119
+ // This is for casting times on the system clock into datetime.datetime instances
120
+ template <typename Duration> 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) { PyDateTime_IMPORT; }
128
+
129
+ if (!src) return false;
130
+
131
+ std::tm cal;
132
+ microseconds msecs;
133
+
134
+ if (PyDateTime_Check(src.ptr())) {
135
+ cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
136
+ cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
137
+ cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
138
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
139
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
140
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
141
+ cal.tm_isdst = -1;
142
+ msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
143
+ } else if (PyDate_Check(src.ptr())) {
144
+ cal.tm_sec = 0;
145
+ cal.tm_min = 0;
146
+ cal.tm_hour = 0;
147
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
148
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
149
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
150
+ cal.tm_isdst = -1;
151
+ msecs = microseconds(0);
152
+ } else if (PyTime_Check(src.ptr())) {
153
+ cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
154
+ cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
155
+ cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
156
+ cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
157
+ cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
158
+ cal.tm_year = 70; // earliest available date for Python's datetime
159
+ cal.tm_isdst = -1;
160
+ msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
161
+ }
162
+ else return false;
163
+
164
+ value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
165
+ return true;
166
+ }
167
+
168
+ static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src, return_value_policy /* policy */, handle /* parent */) {
169
+ using namespace std::chrono;
170
+
171
+ // Lazy initialise the PyDateTime import
172
+ if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
173
+
174
+ // Get out microseconds, and make sure they are positive, to avoid bug in eastern hemisphere time zones
175
+ // (cfr. https://github.com/pybind/pybind11/issues/2417)
176
+ using us_t = duration<int, std::micro>;
177
+ auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
178
+ if (us.count() < 0)
179
+ us += seconds(1);
180
+
181
+ // Subtract microseconds BEFORE `system_clock::to_time_t`, because:
182
+ // > If std::time_t has lower precision, it is implementation-defined whether the value is rounded or truncated.
183
+ // (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
184
+ std::time_t tt = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
185
+
186
+ std::tm localtime;
187
+ std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
188
+ if (!localtime_ptr)
189
+ throw cast_error("Unable to represent system_clock in local time");
190
+ return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
191
+ localtime.tm_mon + 1,
192
+ localtime.tm_mday,
193
+ localtime.tm_hour,
194
+ localtime.tm_min,
195
+ localtime.tm_sec,
196
+ us.count());
197
+ }
198
+ PYBIND11_TYPE_CASTER(type, _("datetime.datetime"));
199
+ };
200
+
201
+ // Other clocks that are not the system clock are not measured as datetime.datetime objects
202
+ // since they are not measured on calendar time. So instead we just make them timedeltas
203
+ // Or if they have passed us a time as a float we convert that
204
+ template <typename Clock, typename Duration> class type_caster<std::chrono::time_point<Clock, Duration>>
205
+ : public duration_caster<std::chrono::time_point<Clock, Duration>> {
206
+ };
207
+
208
+ template <typename Rep, typename Period> class type_caster<std::chrono::duration<Rep, Period>>
209
+ : public duration_caster<std::chrono::duration<Rep, Period>> {
210
+ };
211
+
212
+ PYBIND11_NAMESPACE_END(detail)
213
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/Pangolin/components/pango_python/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/Pangolin/components/pango_python/pybind11/include/pybind11/complex.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #include <complex>
14
+
15
+ /// glibc defines I as a macro which breaks things, e.g., boost template names
16
+ #ifdef I
17
+ # undef I
18
+ #endif
19
+
20
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
21
+
22
+ template <typename T> struct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
23
+ static constexpr const char c = format_descriptor<T>::c;
24
+ static constexpr const char value[3] = { 'Z', c, '\0' };
25
+ static std::string format() { return std::string(value); }
26
+ };
27
+
28
+ #ifndef PYBIND11_CPP17
29
+
30
+ template <typename T> constexpr const char format_descriptor<
31
+ std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>>::value[3];
32
+
33
+ #endif
34
+
35
+ PYBIND11_NAMESPACE_BEGIN(detail)
36
+
37
+ template <typename T> struct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
38
+ static constexpr bool value = true;
39
+ static constexpr int index = is_fmt_numeric<T>::index + 3;
40
+ };
41
+
42
+ template <typename T> class type_caster<std::complex<T>> {
43
+ public:
44
+ bool load(handle src, bool convert) {
45
+ if (!src)
46
+ return false;
47
+ if (!convert && !PyComplex_Check(src.ptr()))
48
+ return false;
49
+ Py_complex result = PyComplex_AsCComplex(src.ptr());
50
+ if (result.real == -1.0 && PyErr_Occurred()) {
51
+ PyErr_Clear();
52
+ return false;
53
+ }
54
+ value = std::complex<T>((T) result.real, (T) result.imag);
55
+ return true;
56
+ }
57
+
58
+ static handle cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
59
+ return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
60
+ }
61
+
62
+ PYBIND11_TYPE_CASTER(std::complex<T>, _("complex"));
63
+ };
64
+ PYBIND11_NAMESPACE_END(detail)
65
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/detail/class.h ADDED
@@ -0,0 +1,707 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/class.h: Python C API implementation details for py::class_
3
+
4
+ Copyright (c) 2017 Wenzel Jakob <[email protected]>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "../attr.h"
13
+ #include "../options.h"
14
+
15
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
16
+ PYBIND11_NAMESPACE_BEGIN(detail)
17
+
18
+ #if PY_VERSION_HEX >= 0x03030000 && !defined(PYPY_VERSION)
19
+ # define PYBIND11_BUILTIN_QUALNAME
20
+ # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
21
+ #else
22
+ // In pre-3.3 Python, we still set __qualname__ so that we can produce reliable function type
23
+ // signatures; in 3.3+ this macro expands to nothing:
24
+ # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) setattr((PyObject *) obj, "__qualname__", nameobj)
25
+ #endif
26
+
27
+ inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
28
+ #if !defined(PYPY_VERSION)
29
+ return type->tp_name;
30
+ #else
31
+ auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
32
+ if (module_name == PYBIND11_BUILTINS_MODULE)
33
+ return type->tp_name;
34
+ else
35
+ return std::move(module_name) + "." + type->tp_name;
36
+ #endif
37
+ }
38
+
39
+ inline PyTypeObject *type_incref(PyTypeObject *type) {
40
+ Py_INCREF(type);
41
+ return type;
42
+ }
43
+
44
+ #if !defined(PYPY_VERSION)
45
+
46
+ /// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
47
+ extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
48
+ return PyProperty_Type.tp_descr_get(self, cls, cls);
49
+ }
50
+
51
+ /// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
52
+ extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
53
+ PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
54
+ return PyProperty_Type.tp_descr_set(self, cls, value);
55
+ }
56
+
57
+ /** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
58
+ methods are modified to always use the object type instead of a concrete instance.
59
+ Return value: New reference. */
60
+ inline PyTypeObject *make_static_property_type() {
61
+ constexpr auto *name = "pybind11_static_property";
62
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
63
+
64
+ /* Danger zone: from now (and until PyType_Ready), make sure to
65
+ issue no Python C API calls which could potentially invoke the
66
+ garbage collector (the GC will call type_traverse(), which will in
67
+ turn find the newly constructed type in an invalid state) */
68
+ auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
69
+ if (!heap_type)
70
+ pybind11_fail("make_static_property_type(): error allocating type!");
71
+
72
+ heap_type->ht_name = name_obj.inc_ref().ptr();
73
+ #ifdef PYBIND11_BUILTIN_QUALNAME
74
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
75
+ #endif
76
+
77
+ auto type = &heap_type->ht_type;
78
+ type->tp_name = name;
79
+ type->tp_base = type_incref(&PyProperty_Type);
80
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
81
+ type->tp_descr_get = pybind11_static_get;
82
+ type->tp_descr_set = pybind11_static_set;
83
+
84
+ if (PyType_Ready(type) < 0)
85
+ pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
86
+
87
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
88
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
89
+
90
+ return type;
91
+ }
92
+
93
+ #else // PYPY
94
+
95
+ /** PyPy has some issues with the above C API, so we evaluate Python code instead.
96
+ This function will only be called once so performance isn't really a concern.
97
+ Return value: New reference. */
98
+ inline PyTypeObject *make_static_property_type() {
99
+ auto d = dict();
100
+ PyObject *result = PyRun_String(R"(\
101
+ class pybind11_static_property(property):
102
+ def __get__(self, obj, cls):
103
+ return property.__get__(self, cls, cls)
104
+
105
+ def __set__(self, obj, value):
106
+ cls = obj if isinstance(obj, type) else type(obj)
107
+ property.__set__(self, cls, value)
108
+ )", Py_file_input, d.ptr(), d.ptr()
109
+ );
110
+ if (result == nullptr)
111
+ throw error_already_set();
112
+ Py_DECREF(result);
113
+ return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
114
+ }
115
+
116
+ #endif // PYPY
117
+
118
+ /** Types with static properties need to handle `Type.static_prop = x` in a specific way.
119
+ By default, Python replaces the `static_property` itself, but for wrapped C++ types
120
+ we need to call `static_property.__set__()` in order to propagate the new value to
121
+ the underlying C++ data structure. */
122
+ extern "C" inline int pybind11_meta_setattro(PyObject* obj, PyObject* name, PyObject* value) {
123
+ // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
124
+ // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
125
+ PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
126
+
127
+ // The following assignment combinations are possible:
128
+ // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
129
+ // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
130
+ // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
131
+ const auto static_prop = (PyObject *) get_internals().static_property_type;
132
+ const auto call_descr_set = (descr != nullptr) && (value != nullptr)
133
+ && (PyObject_IsInstance(descr, static_prop) != 0)
134
+ && (PyObject_IsInstance(value, static_prop) == 0);
135
+ if (call_descr_set) {
136
+ // Call `static_property.__set__()` instead of replacing the `static_property`.
137
+ #if !defined(PYPY_VERSION)
138
+ return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
139
+ #else
140
+ if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
141
+ Py_DECREF(result);
142
+ return 0;
143
+ } else {
144
+ return -1;
145
+ }
146
+ #endif
147
+ } else {
148
+ // Replace existing attribute.
149
+ return PyType_Type.tp_setattro(obj, name, value);
150
+ }
151
+ }
152
+
153
+ #if PY_MAJOR_VERSION >= 3
154
+ /**
155
+ * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
156
+ * methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
157
+ * when called on a class, or a PyMethod, when called on an instance. Override that behaviour here
158
+ * to do a special case bypass for PyInstanceMethod_Types.
159
+ */
160
+ extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
161
+ PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
162
+ if (descr && PyInstanceMethod_Check(descr)) {
163
+ Py_INCREF(descr);
164
+ return descr;
165
+ }
166
+ return PyType_Type.tp_getattro(obj, name);
167
+ }
168
+ #endif
169
+
170
+ /// metaclass `__call__` function that is used to create all pybind11 objects.
171
+ extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
172
+
173
+ // use the default metaclass call to create/initialize the object
174
+ PyObject *self = PyType_Type.tp_call(type, args, kwargs);
175
+ if (self == nullptr) {
176
+ return nullptr;
177
+ }
178
+
179
+ // This must be a pybind11 instance
180
+ auto instance = reinterpret_cast<detail::instance *>(self);
181
+
182
+ // Ensure that the base __init__ function(s) were called
183
+ for (const auto &vh : values_and_holders(instance)) {
184
+ if (!vh.holder_constructed()) {
185
+ PyErr_Format(PyExc_TypeError, "%.200s.__init__() must be called when overriding __init__",
186
+ get_fully_qualified_tp_name(vh.type->type).c_str());
187
+ Py_DECREF(self);
188
+ return nullptr;
189
+ }
190
+ }
191
+
192
+ return self;
193
+ }
194
+
195
+ /// Cleanup the type-info for a pybind11-registered type.
196
+ extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
197
+ auto *type = (PyTypeObject *) obj;
198
+ auto &internals = get_internals();
199
+
200
+ // A pybind11-registered type will:
201
+ // 1) be found in internals.registered_types_py
202
+ // 2) have exactly one associated `detail::type_info`
203
+ auto found_type = internals.registered_types_py.find(type);
204
+ if (found_type != internals.registered_types_py.end() &&
205
+ found_type->second.size() == 1 &&
206
+ found_type->second[0]->type == type) {
207
+
208
+ auto *tinfo = found_type->second[0];
209
+ auto tindex = std::type_index(*tinfo->cpptype);
210
+ internals.direct_conversions.erase(tindex);
211
+
212
+ if (tinfo->module_local)
213
+ registered_local_types_cpp().erase(tindex);
214
+ else
215
+ internals.registered_types_cpp.erase(tindex);
216
+ internals.registered_types_py.erase(tinfo->type);
217
+
218
+ // Actually just `std::erase_if`, but that's only available in C++20
219
+ auto &cache = internals.inactive_override_cache;
220
+ for (auto it = cache.begin(), last = cache.end(); it != last; ) {
221
+ if (it->first == (PyObject *) tinfo->type)
222
+ it = cache.erase(it);
223
+ else
224
+ ++it;
225
+ }
226
+
227
+ delete tinfo;
228
+ }
229
+
230
+ PyType_Type.tp_dealloc(obj);
231
+ }
232
+
233
+ /** This metaclass is assigned by default to all pybind11 types and is required in order
234
+ for static properties to function correctly. Users may override this using `py::metaclass`.
235
+ Return value: New reference. */
236
+ inline PyTypeObject* make_default_metaclass() {
237
+ constexpr auto *name = "pybind11_type";
238
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
239
+
240
+ /* Danger zone: from now (and until PyType_Ready), make sure to
241
+ issue no Python C API calls which could potentially invoke the
242
+ garbage collector (the GC will call type_traverse(), which will in
243
+ turn find the newly constructed type in an invalid state) */
244
+ auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
245
+ if (!heap_type)
246
+ pybind11_fail("make_default_metaclass(): error allocating metaclass!");
247
+
248
+ heap_type->ht_name = name_obj.inc_ref().ptr();
249
+ #ifdef PYBIND11_BUILTIN_QUALNAME
250
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
251
+ #endif
252
+
253
+ auto type = &heap_type->ht_type;
254
+ type->tp_name = name;
255
+ type->tp_base = type_incref(&PyType_Type);
256
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
257
+
258
+ type->tp_call = pybind11_meta_call;
259
+
260
+ type->tp_setattro = pybind11_meta_setattro;
261
+ #if PY_MAJOR_VERSION >= 3
262
+ type->tp_getattro = pybind11_meta_getattro;
263
+ #endif
264
+
265
+ type->tp_dealloc = pybind11_meta_dealloc;
266
+
267
+ if (PyType_Ready(type) < 0)
268
+ pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
269
+
270
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
271
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
272
+
273
+ return type;
274
+ }
275
+
276
+ /// For multiple inheritance types we need to recursively register/deregister base pointers for any
277
+ /// base classes with pointers that are difference from the instance value pointer so that we can
278
+ /// correctly recognize an offset base class pointer. This calls a function with any offset base ptrs.
279
+ inline void traverse_offset_bases(void *valueptr, const detail::type_info *tinfo, instance *self,
280
+ bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
281
+ for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
282
+ if (auto parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
283
+ for (auto &c : parent_tinfo->implicit_casts) {
284
+ if (c.first == tinfo->cpptype) {
285
+ auto *parentptr = c.second(valueptr);
286
+ if (parentptr != valueptr)
287
+ f(parentptr, self);
288
+ traverse_offset_bases(parentptr, parent_tinfo, self, f);
289
+ break;
290
+ }
291
+ }
292
+ }
293
+ }
294
+ }
295
+
296
+ inline bool register_instance_impl(void *ptr, instance *self) {
297
+ get_internals().registered_instances.emplace(ptr, self);
298
+ return true; // unused, but gives the same signature as the deregister func
299
+ }
300
+ inline bool deregister_instance_impl(void *ptr, instance *self) {
301
+ auto &registered_instances = get_internals().registered_instances;
302
+ auto range = registered_instances.equal_range(ptr);
303
+ for (auto it = range.first; it != range.second; ++it) {
304
+ if (self == it->second) {
305
+ registered_instances.erase(it);
306
+ return true;
307
+ }
308
+ }
309
+ return false;
310
+ }
311
+
312
+ inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
313
+ register_instance_impl(valptr, self);
314
+ if (!tinfo->simple_ancestors)
315
+ traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
316
+ }
317
+
318
+ inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
319
+ bool ret = deregister_instance_impl(valptr, self);
320
+ if (!tinfo->simple_ancestors)
321
+ traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
322
+ return ret;
323
+ }
324
+
325
+ /// Instance creation function for all pybind11 types. It allocates the internal instance layout for
326
+ /// holding C++ objects and holders. Allocation is done lazily (the first time the instance is cast
327
+ /// to a reference or pointer), and initialization is done by an `__init__` function.
328
+ inline PyObject *make_new_instance(PyTypeObject *type) {
329
+ #if defined(PYPY_VERSION)
330
+ // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first inherited
331
+ // object is a plain Python type (i.e. not derived from an extension type). Fix it.
332
+ ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
333
+ if (type->tp_basicsize < instance_size) {
334
+ type->tp_basicsize = instance_size;
335
+ }
336
+ #endif
337
+ PyObject *self = type->tp_alloc(type, 0);
338
+ auto inst = reinterpret_cast<instance *>(self);
339
+ // Allocate the value/holder internals:
340
+ inst->allocate_layout();
341
+
342
+ return self;
343
+ }
344
+
345
+ /// Instance creation function for all pybind11 types. It only allocates space for the
346
+ /// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
347
+ extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
348
+ return make_new_instance(type);
349
+ }
350
+
351
+ /// An `__init__` function constructs the C++ object. Users should provide at least one
352
+ /// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
353
+ /// following default function will be used which simply throws an exception.
354
+ extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
355
+ PyTypeObject *type = Py_TYPE(self);
356
+ std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
357
+ PyErr_SetString(PyExc_TypeError, msg.c_str());
358
+ return -1;
359
+ }
360
+
361
+ inline void add_patient(PyObject *nurse, PyObject *patient) {
362
+ auto &internals = get_internals();
363
+ auto instance = reinterpret_cast<detail::instance *>(nurse);
364
+ instance->has_patients = true;
365
+ Py_INCREF(patient);
366
+ internals.patients[nurse].push_back(patient);
367
+ }
368
+
369
+ inline void clear_patients(PyObject *self) {
370
+ auto instance = reinterpret_cast<detail::instance *>(self);
371
+ auto &internals = get_internals();
372
+ auto pos = internals.patients.find(self);
373
+ assert(pos != internals.patients.end());
374
+ // Clearing the patients can cause more Python code to run, which
375
+ // can invalidate the iterator. Extract the vector of patients
376
+ // from the unordered_map first.
377
+ auto patients = std::move(pos->second);
378
+ internals.patients.erase(pos);
379
+ instance->has_patients = false;
380
+ for (PyObject *&patient : patients)
381
+ Py_CLEAR(patient);
382
+ }
383
+
384
+ /// Clears all internal data from the instance and removes it from registered instances in
385
+ /// preparation for deallocation.
386
+ inline void clear_instance(PyObject *self) {
387
+ auto instance = reinterpret_cast<detail::instance *>(self);
388
+
389
+ // Deallocate any values/holders, if present:
390
+ for (auto &v_h : values_and_holders(instance)) {
391
+ if (v_h) {
392
+
393
+ // We have to deregister before we call dealloc because, for virtual MI types, we still
394
+ // need to be able to get the parent pointers.
395
+ if (v_h.instance_registered() && !deregister_instance(instance, v_h.value_ptr(), v_h.type))
396
+ pybind11_fail("pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
397
+
398
+ if (instance->owned || v_h.holder_constructed())
399
+ v_h.type->dealloc(v_h);
400
+ }
401
+ }
402
+ // Deallocate the value/holder layout internals:
403
+ instance->deallocate_layout();
404
+
405
+ if (instance->weakrefs)
406
+ PyObject_ClearWeakRefs(self);
407
+
408
+ PyObject **dict_ptr = _PyObject_GetDictPtr(self);
409
+ if (dict_ptr)
410
+ Py_CLEAR(*dict_ptr);
411
+
412
+ if (instance->has_patients)
413
+ clear_patients(self);
414
+ }
415
+
416
+ /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
417
+ /// to destroy the C++ object itself, while the rest is Python bookkeeping.
418
+ extern "C" inline void pybind11_object_dealloc(PyObject *self) {
419
+ clear_instance(self);
420
+
421
+ auto type = Py_TYPE(self);
422
+ type->tp_free(self);
423
+
424
+ #if PY_VERSION_HEX < 0x03080000
425
+ // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
426
+ // as part of a derived type's dealloc, in which case we're not allowed to decref
427
+ // the type here. For cross-module compatibility, we shouldn't compare directly
428
+ // with `pybind11_object_dealloc`, but with the common one stashed in internals.
429
+ auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
430
+ if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
431
+ Py_DECREF(type);
432
+ #else
433
+ // This was not needed before Python 3.8 (Python issue 35810)
434
+ // https://github.com/pybind/pybind11/issues/1946
435
+ Py_DECREF(type);
436
+ #endif
437
+ }
438
+
439
+ /** Create the type which can be used as a common base for all classes. This is
440
+ needed in order to satisfy Python's requirements for multiple inheritance.
441
+ Return value: New reference. */
442
+ inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
443
+ constexpr auto *name = "pybind11_object";
444
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
445
+
446
+ /* Danger zone: from now (and until PyType_Ready), make sure to
447
+ issue no Python C API calls which could potentially invoke the
448
+ garbage collector (the GC will call type_traverse(), which will in
449
+ turn find the newly constructed type in an invalid state) */
450
+ auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
451
+ if (!heap_type)
452
+ pybind11_fail("make_object_base_type(): error allocating type!");
453
+
454
+ heap_type->ht_name = name_obj.inc_ref().ptr();
455
+ #ifdef PYBIND11_BUILTIN_QUALNAME
456
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
457
+ #endif
458
+
459
+ auto type = &heap_type->ht_type;
460
+ type->tp_name = name;
461
+ type->tp_base = type_incref(&PyBaseObject_Type);
462
+ type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
463
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
464
+
465
+ type->tp_new = pybind11_object_new;
466
+ type->tp_init = pybind11_object_init;
467
+ type->tp_dealloc = pybind11_object_dealloc;
468
+
469
+ /* Support weak references (needed for the keep_alive feature) */
470
+ type->tp_weaklistoffset = offsetof(instance, weakrefs);
471
+
472
+ if (PyType_Ready(type) < 0)
473
+ pybind11_fail("PyType_Ready failed in make_object_base_type():" + error_string());
474
+
475
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
476
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
477
+
478
+ assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
479
+ return (PyObject *) heap_type;
480
+ }
481
+
482
+ /// dynamic_attr: Support for `d = instance.__dict__`.
483
+ extern "C" inline PyObject *pybind11_get_dict(PyObject *self, void *) {
484
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
485
+ if (!dict)
486
+ dict = PyDict_New();
487
+ Py_XINCREF(dict);
488
+ return dict;
489
+ }
490
+
491
+ /// dynamic_attr: Support for `instance.__dict__ = dict()`.
492
+ extern "C" inline int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *) {
493
+ if (!PyDict_Check(new_dict)) {
494
+ PyErr_Format(PyExc_TypeError, "__dict__ must be set to a dictionary, not a '%.200s'",
495
+ get_fully_qualified_tp_name(Py_TYPE(new_dict)).c_str());
496
+ return -1;
497
+ }
498
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
499
+ Py_INCREF(new_dict);
500
+ Py_CLEAR(dict);
501
+ dict = new_dict;
502
+ return 0;
503
+ }
504
+
505
+ /// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
506
+ extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
507
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
508
+ Py_VISIT(dict);
509
+ return 0;
510
+ }
511
+
512
+ /// dynamic_attr: Allow the GC to clear the dictionary.
513
+ extern "C" inline int pybind11_clear(PyObject *self) {
514
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
515
+ Py_CLEAR(dict);
516
+ return 0;
517
+ }
518
+
519
+ /// Give instances of this type a `__dict__` and opt into garbage collection.
520
+ inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
521
+ auto type = &heap_type->ht_type;
522
+ type->tp_flags |= Py_TPFLAGS_HAVE_GC;
523
+ type->tp_dictoffset = type->tp_basicsize; // place dict at the end
524
+ type->tp_basicsize += (ssize_t)sizeof(PyObject *); // and allocate enough space for it
525
+ type->tp_traverse = pybind11_traverse;
526
+ type->tp_clear = pybind11_clear;
527
+
528
+ static PyGetSetDef getset[] = {
529
+ {const_cast<char*>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
530
+ {nullptr, nullptr, nullptr, nullptr, nullptr}
531
+ };
532
+ type->tp_getset = getset;
533
+ }
534
+
535
+ /// buffer_protocol: Fill in the view as specified by flags.
536
+ extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
537
+ // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
538
+ type_info *tinfo = nullptr;
539
+ for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
540
+ tinfo = get_type_info((PyTypeObject *) type.ptr());
541
+ if (tinfo && tinfo->get_buffer)
542
+ break;
543
+ }
544
+ if (view == nullptr || !tinfo || !tinfo->get_buffer) {
545
+ if (view)
546
+ view->obj = nullptr;
547
+ PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
548
+ return -1;
549
+ }
550
+ std::memset(view, 0, sizeof(Py_buffer));
551
+ buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
552
+ if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
553
+ delete info;
554
+ // view->obj = nullptr; // Was just memset to 0, so not necessary
555
+ PyErr_SetString(PyExc_BufferError, "Writable buffer requested for readonly storage");
556
+ return -1;
557
+ }
558
+ view->obj = obj;
559
+ view->ndim = 1;
560
+ view->internal = info;
561
+ view->buf = info->ptr;
562
+ view->itemsize = info->itemsize;
563
+ view->len = view->itemsize;
564
+ for (auto s : info->shape)
565
+ view->len *= s;
566
+ view->readonly = static_cast<int>(info->readonly);
567
+ if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
568
+ view->format = const_cast<char *>(info->format.c_str());
569
+ if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
570
+ view->ndim = (int) info->ndim;
571
+ view->strides = &info->strides[0];
572
+ view->shape = &info->shape[0];
573
+ }
574
+ Py_INCREF(view->obj);
575
+ return 0;
576
+ }
577
+
578
+ /// buffer_protocol: Release the resources of the buffer.
579
+ extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
580
+ delete (buffer_info *) view->internal;
581
+ }
582
+
583
+ /// Give this type a buffer interface.
584
+ inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
585
+ heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
586
+ #if PY_MAJOR_VERSION < 3
587
+ heap_type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
588
+ #endif
589
+
590
+ heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
591
+ heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
592
+ }
593
+
594
+ /** Create a brand new Python type according to the `type_record` specification.
595
+ Return value: New reference. */
596
+ inline PyObject* make_new_python_type(const type_record &rec) {
597
+ auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
598
+
599
+ auto qualname = name;
600
+ if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
601
+ #if PY_MAJOR_VERSION >= 3
602
+ qualname = reinterpret_steal<object>(
603
+ PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
604
+ #else
605
+ qualname = str(rec.scope.attr("__qualname__").cast<std::string>() + "." + rec.name);
606
+ #endif
607
+ }
608
+
609
+ object module_;
610
+ if (rec.scope) {
611
+ if (hasattr(rec.scope, "__module__"))
612
+ module_ = rec.scope.attr("__module__");
613
+ else if (hasattr(rec.scope, "__name__"))
614
+ module_ = rec.scope.attr("__name__");
615
+ }
616
+
617
+ auto full_name = c_str(
618
+ #if !defined(PYPY_VERSION)
619
+ module_ ? str(module_).cast<std::string>() + "." + rec.name :
620
+ #endif
621
+ rec.name);
622
+
623
+ char *tp_doc = nullptr;
624
+ if (rec.doc && options::show_user_defined_docstrings()) {
625
+ /* Allocate memory for docstring (using PyObject_MALLOC, since
626
+ Python will free this later on) */
627
+ size_t size = strlen(rec.doc) + 1;
628
+ tp_doc = (char *) PyObject_MALLOC(size);
629
+ memcpy((void *) tp_doc, rec.doc, size);
630
+ }
631
+
632
+ auto &internals = get_internals();
633
+ auto bases = tuple(rec.bases);
634
+ auto base = (bases.empty()) ? internals.instance_base
635
+ : bases[0].ptr();
636
+
637
+ /* Danger zone: from now (and until PyType_Ready), make sure to
638
+ issue no Python C API calls which could potentially invoke the
639
+ garbage collector (the GC will call type_traverse(), which will in
640
+ turn find the newly constructed type in an invalid state) */
641
+ auto metaclass = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr()
642
+ : internals.default_metaclass;
643
+
644
+ auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
645
+ if (!heap_type)
646
+ pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
647
+
648
+ heap_type->ht_name = name.release().ptr();
649
+ #ifdef PYBIND11_BUILTIN_QUALNAME
650
+ heap_type->ht_qualname = qualname.inc_ref().ptr();
651
+ #endif
652
+
653
+ auto type = &heap_type->ht_type;
654
+ type->tp_name = full_name;
655
+ type->tp_doc = tp_doc;
656
+ type->tp_base = type_incref((PyTypeObject *)base);
657
+ type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
658
+ if (!bases.empty())
659
+ type->tp_bases = bases.release().ptr();
660
+
661
+ /* Don't inherit base __init__ */
662
+ type->tp_init = pybind11_object_init;
663
+
664
+ /* Supported protocols */
665
+ type->tp_as_number = &heap_type->as_number;
666
+ type->tp_as_sequence = &heap_type->as_sequence;
667
+ type->tp_as_mapping = &heap_type->as_mapping;
668
+ #if PY_VERSION_HEX >= 0x03050000
669
+ type->tp_as_async = &heap_type->as_async;
670
+ #endif
671
+
672
+ /* Flags */
673
+ type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
674
+ #if PY_MAJOR_VERSION < 3
675
+ type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
676
+ #endif
677
+ if (!rec.is_final)
678
+ type->tp_flags |= Py_TPFLAGS_BASETYPE;
679
+
680
+ if (rec.dynamic_attr)
681
+ enable_dynamic_attributes(heap_type);
682
+
683
+ if (rec.buffer_protocol)
684
+ enable_buffer_protocol(heap_type);
685
+
686
+ if (PyType_Ready(type) < 0)
687
+ pybind11_fail(std::string(rec.name) + ": PyType_Ready failed (" + error_string() + ")!");
688
+
689
+ assert(rec.dynamic_attr ? PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC)
690
+ : !PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
691
+
692
+ /* Register type with the parent scope */
693
+ if (rec.scope)
694
+ setattr(rec.scope, rec.name, (PyObject *) type);
695
+ else
696
+ Py_INCREF(type); // Keep it alive forever (reference leak)
697
+
698
+ if (module_) // Needed by pydoc
699
+ setattr((PyObject *) type, "__module__", module_);
700
+
701
+ PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
702
+
703
+ return (PyObject *) type;
704
+ }
705
+
706
+ PYBIND11_NAMESPACE_END(detail)
707
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/detail/common.h ADDED
@@ -0,0 +1,932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 7
14
+ #define PYBIND11_VERSION_PATCH 1
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 0x02070100
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 on
25
+ // 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
+ # endif
40
+ # endif
41
+ #elif defined(_MSC_VER) && __cplusplus == 199711L
42
+ // MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented)
43
+ // Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer
44
+ # if _MSVC_LANG >= 201402L
45
+ # define PYBIND11_CPP14
46
+ # if _MSVC_LANG > 201402L && _MSC_VER >= 1910
47
+ # define PYBIND11_CPP17
48
+ # endif
49
+ # endif
50
+ #endif
51
+
52
+ // Compiler version assertions
53
+ #if defined(__INTEL_COMPILER)
54
+ # if __INTEL_COMPILER < 1800
55
+ # error pybind11 requires Intel C++ compiler v18 or newer
56
+ # elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)
57
+ # error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.
58
+ # endif
59
+ /* The following pragma cannot be pop'ed:
60
+ https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */
61
+ # pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
62
+ #elif defined(__clang__) && !defined(__apple_build_version__)
63
+ # if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
64
+ # error pybind11 requires clang 3.3 or newer
65
+ # endif
66
+ #elif defined(__clang__)
67
+ // Apple changes clang version macros to its Xcode version; the first Xcode release based on
68
+ // (upstream) clang 3.3 was Xcode 5:
69
+ # if __clang_major__ < 5
70
+ # error pybind11 requires Xcode/clang 5.0 or newer
71
+ # endif
72
+ #elif defined(__GNUG__)
73
+ # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
74
+ # error pybind11 requires gcc 4.8 or newer
75
+ # endif
76
+ #elif defined(_MSC_VER)
77
+ // Pybind hits various compiler bugs in 2015u2 and earlier, and also makes use of some stl features
78
+ // (e.g. std::negation) added in 2015u3:
79
+ # if _MSC_FULL_VER < 190024210
80
+ # error pybind11 requires MSVC 2015 update 3 or newer
81
+ # endif
82
+ #endif
83
+
84
+ #if !defined(PYBIND11_EXPORT)
85
+ # if defined(WIN32) || defined(_WIN32)
86
+ # define PYBIND11_EXPORT __declspec(dllexport)
87
+ # else
88
+ # define PYBIND11_EXPORT __attribute__ ((visibility("default")))
89
+ # endif
90
+ #endif
91
+
92
+ #if !defined(PYBIND11_EXPORT_EXCEPTION)
93
+ # ifdef __MINGW32__
94
+ // workaround for:
95
+ // error: 'dllexport' implies default visibility, but xxx has already been declared with a different visibility
96
+ # define PYBIND11_EXPORT_EXCEPTION
97
+ # else
98
+ # define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
99
+ # endif
100
+ #endif
101
+
102
+ #if defined(_MSC_VER)
103
+ # define PYBIND11_NOINLINE __declspec(noinline)
104
+ #else
105
+ # define PYBIND11_NOINLINE __attribute__ ((noinline))
106
+ #endif
107
+
108
+ #if defined(__MINGW32__)
109
+ // For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
110
+ // whether it is used or not
111
+ # define PYBIND11_DEPRECATED(reason)
112
+ #elif defined(PYBIND11_CPP14)
113
+ # define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
114
+ #else
115
+ # define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
116
+ #endif
117
+
118
+ #if defined(PYBIND11_CPP17)
119
+ # define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
120
+ #elif defined(_MSC_VER) && !defined(__clang__)
121
+ # define PYBIND11_MAYBE_UNUSED
122
+ #else
123
+ # define PYBIND11_MAYBE_UNUSED __attribute__ ((__unused__))
124
+ #endif
125
+
126
+ /* Don't let Python.h #define (v)snprintf as macro because they are implemented
127
+ properly in Visual Studio since 2015. */
128
+ #if defined(_MSC_VER) && _MSC_VER >= 1900
129
+ # define HAVE_SNPRINTF 1
130
+ #endif
131
+
132
+ /// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
133
+ #if defined(_MSC_VER)
134
+ # if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 4)
135
+ # define HAVE_ROUND 1
136
+ # endif
137
+ # pragma warning(push)
138
+ // C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
139
+ # pragma warning(disable: 4505)
140
+ # if defined(_DEBUG) && !defined(Py_DEBUG)
141
+ # define PYBIND11_DEBUG_MARKER
142
+ # undef _DEBUG
143
+ # endif
144
+ #endif
145
+
146
+ // https://en.cppreference.com/w/c/chrono/localtime
147
+ #if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
148
+ # define __STDC_WANT_LIB_EXT1__
149
+ #endif
150
+
151
+ #include <Python.h>
152
+ #include <frameobject.h>
153
+ #include <pythread.h>
154
+
155
+ /* Python #defines overrides on all sorts of core functions, which
156
+ tends to weak havok in C++ codebases that expect these to work
157
+ like regular functions (potentially with several overloads) */
158
+ #if defined(isalnum)
159
+ # undef isalnum
160
+ # undef isalpha
161
+ # undef islower
162
+ # undef isspace
163
+ # undef isupper
164
+ # undef tolower
165
+ # undef toupper
166
+ #endif
167
+
168
+ #if defined(copysign)
169
+ # undef copysign
170
+ #endif
171
+
172
+ #if defined(_MSC_VER)
173
+ # if defined(PYBIND11_DEBUG_MARKER)
174
+ # define _DEBUG
175
+ # undef PYBIND11_DEBUG_MARKER
176
+ # endif
177
+ # pragma warning(pop)
178
+ #endif
179
+
180
+ #include <cstddef>
181
+ #include <cstring>
182
+ #include <forward_list>
183
+ #include <vector>
184
+ #include <string>
185
+ #include <stdexcept>
186
+ #include <exception>
187
+ #include <unordered_set>
188
+ #include <unordered_map>
189
+ #include <memory>
190
+ #include <typeindex>
191
+ #include <type_traits>
192
+ #if defined(__has_include)
193
+ # if __has_include(<version>)
194
+ # include <version>
195
+ # endif
196
+ #endif
197
+
198
+ // #define PYBIND11_STR_LEGACY_PERMISSIVE
199
+ // If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
200
+ // (probably surprising and never documented, but this was the
201
+ // legacy behavior until and including v2.6.x). As a side-effect,
202
+ // pybind11::isinstance<str>() is true for both pybind11::str and
203
+ // pybind11::bytes.
204
+ // If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
205
+ // pybind11::isinstance<str>() is true only for pybind11::str.
206
+ // However, for Python 2 only (!), the pybind11::str caster
207
+ // implicitly decodes bytes to PyUnicodeObject. This is to ease
208
+ // the transition from the legacy behavior to the non-permissive
209
+ // behavior.
210
+
211
+ #if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
212
+ #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
213
+ #define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
214
+ #define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
215
+ #define PYBIND11_BYTES_CHECK PyBytes_Check
216
+ #define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
217
+ #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
218
+ #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
219
+ #define PYBIND11_BYTES_AS_STRING PyBytes_AsString
220
+ #define PYBIND11_BYTES_SIZE PyBytes_Size
221
+ #define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
222
+ #define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
223
+ #define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) o)
224
+ #define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) o)
225
+ #define PYBIND11_BYTES_NAME "bytes"
226
+ #define PYBIND11_STRING_NAME "str"
227
+ #define PYBIND11_SLICE_OBJECT PyObject
228
+ #define PYBIND11_FROM_STRING PyUnicode_FromString
229
+ #define PYBIND11_STR_TYPE ::pybind11::str
230
+ #define PYBIND11_BOOL_ATTR "__bool__"
231
+ #define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
232
+ #define PYBIND11_BUILTINS_MODULE "builtins"
233
+ // Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
234
+ // See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
235
+ #define PYBIND11_PLUGIN_IMPL(name) \
236
+ extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name(); \
237
+ extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
238
+
239
+ #else
240
+ #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
241
+ #define PYBIND11_INSTANCE_METHOD_CHECK PyMethod_Check
242
+ #define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyMethod_GET_FUNCTION
243
+ #define PYBIND11_BYTES_CHECK PyString_Check
244
+ #define PYBIND11_BYTES_FROM_STRING PyString_FromString
245
+ #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
246
+ #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
247
+ #define PYBIND11_BYTES_AS_STRING PyString_AsString
248
+ #define PYBIND11_BYTES_SIZE PyString_Size
249
+ #define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
250
+ #define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
251
+ #define PYBIND11_LONG_FROM_SIGNED(o) PyInt_FromSsize_t((ssize_t) o) // Returns long if needed.
252
+ #define PYBIND11_LONG_FROM_UNSIGNED(o) PyInt_FromSize_t((size_t) o) // Returns long if needed.
253
+ #define PYBIND11_BYTES_NAME "str"
254
+ #define PYBIND11_STRING_NAME "unicode"
255
+ #define PYBIND11_SLICE_OBJECT PySliceObject
256
+ #define PYBIND11_FROM_STRING PyString_FromString
257
+ #define PYBIND11_STR_TYPE ::pybind11::bytes
258
+ #define PYBIND11_BOOL_ATTR "__nonzero__"
259
+ #define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_nonzero)
260
+ #define PYBIND11_BUILTINS_MODULE "__builtin__"
261
+ // Providing a separate PyInit decl to make Clang's -Wmissing-prototypes happy.
262
+ // See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
263
+ #define PYBIND11_PLUGIN_IMPL(name) \
264
+ static PyObject *pybind11_init_wrapper(); \
265
+ extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT void init##name(); \
266
+ extern "C" PYBIND11_EXPORT void init##name() { \
267
+ (void)pybind11_init_wrapper(); \
268
+ } \
269
+ PyObject *pybind11_init_wrapper()
270
+ #endif
271
+
272
+ #if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
273
+ extern "C" {
274
+ struct _Py_atomic_address { void *value; };
275
+ PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
276
+ }
277
+ #endif
278
+
279
+ #define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
280
+ #define PYBIND11_STRINGIFY(x) #x
281
+ #define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
282
+ #define PYBIND11_CONCAT(first, second) first##second
283
+ #define PYBIND11_ENSURE_INTERNALS_READY \
284
+ pybind11::detail::get_internals();
285
+
286
+ #define PYBIND11_CHECK_PYTHON_VERSION \
287
+ { \
288
+ const char *compiled_ver = PYBIND11_TOSTRING(PY_MAJOR_VERSION) \
289
+ "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
290
+ const char *runtime_ver = Py_GetVersion(); \
291
+ size_t len = std::strlen(compiled_ver); \
292
+ if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
293
+ || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
294
+ PyErr_Format(PyExc_ImportError, \
295
+ "Python version mismatch: module was compiled for Python %s, " \
296
+ "but the interpreter version is incompatible: %s.", \
297
+ compiled_ver, runtime_ver); \
298
+ return nullptr; \
299
+ } \
300
+ }
301
+
302
+ #define PYBIND11_CATCH_INIT_EXCEPTIONS \
303
+ catch (pybind11::error_already_set &e) { \
304
+ PyErr_SetString(PyExc_ImportError, e.what()); \
305
+ return nullptr; \
306
+ } catch (const std::exception &e) { \
307
+ PyErr_SetString(PyExc_ImportError, e.what()); \
308
+ return nullptr; \
309
+ } \
310
+
311
+ /** \rst
312
+ ***Deprecated in favor of PYBIND11_MODULE***
313
+
314
+ This macro creates the entry point that will be invoked when the Python interpreter
315
+ imports a plugin library. Please create a `module_` in the function body and return
316
+ the pointer to its underlying Python object at the end.
317
+
318
+ .. code-block:: cpp
319
+
320
+ PYBIND11_PLUGIN(example) {
321
+ pybind11::module_ m("example", "pybind11 example plugin");
322
+ /// Set up bindings here
323
+ return m.ptr();
324
+ }
325
+ \endrst */
326
+ #define PYBIND11_PLUGIN(name) \
327
+ PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
328
+ static PyObject *pybind11_init(); \
329
+ PYBIND11_PLUGIN_IMPL(name) { \
330
+ PYBIND11_CHECK_PYTHON_VERSION \
331
+ PYBIND11_ENSURE_INTERNALS_READY \
332
+ try { \
333
+ return pybind11_init(); \
334
+ } PYBIND11_CATCH_INIT_EXCEPTIONS \
335
+ } \
336
+ PyObject *pybind11_init()
337
+
338
+ /** \rst
339
+ This macro creates the entry point that will be invoked when the Python interpreter
340
+ imports an extension module. The module name is given as the fist argument and it
341
+ should not be in quotes. The second macro argument defines a variable of type
342
+ `py::module_` which can be used to initialize the module.
343
+
344
+ The entry point is marked as "maybe unused" to aid dead-code detection analysis:
345
+ since the entry point is typically only looked up at runtime and not referenced
346
+ during translation, it would otherwise appear as unused ("dead") code.
347
+
348
+ .. code-block:: cpp
349
+
350
+ PYBIND11_MODULE(example, m) {
351
+ m.doc() = "pybind11 example module";
352
+
353
+ // Add bindings here
354
+ m.def("foo", []() {
355
+ return "Hello, World!";
356
+ });
357
+ }
358
+ \endrst */
359
+ #define PYBIND11_MODULE(name, variable) \
360
+ static ::pybind11::module_::module_def \
361
+ PYBIND11_CONCAT(pybind11_module_def_, name) PYBIND11_MAYBE_UNUSED; \
362
+ PYBIND11_MAYBE_UNUSED \
363
+ static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
364
+ PYBIND11_PLUGIN_IMPL(name) { \
365
+ PYBIND11_CHECK_PYTHON_VERSION \
366
+ PYBIND11_ENSURE_INTERNALS_READY \
367
+ auto m = ::pybind11::module_::create_extension_module( \
368
+ PYBIND11_TOSTRING(name), nullptr, \
369
+ &PYBIND11_CONCAT(pybind11_module_def_, name)); \
370
+ try { \
371
+ PYBIND11_CONCAT(pybind11_init_, name)(m); \
372
+ return m.ptr(); \
373
+ } PYBIND11_CATCH_INIT_EXCEPTIONS \
374
+ } \
375
+ void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &variable)
376
+
377
+
378
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
379
+
380
+ using ssize_t = Py_ssize_t;
381
+ using size_t = std::size_t;
382
+
383
+ /// Approach used to cast a previously unknown C++ instance into a Python object
384
+ enum class return_value_policy : uint8_t {
385
+ /** This is the default return value policy, which falls back to the policy
386
+ return_value_policy::take_ownership when the return value is a pointer.
387
+ Otherwise, it uses return_value::move or return_value::copy for rvalue
388
+ and lvalue references, respectively. See below for a description of what
389
+ all of these different policies do. */
390
+ automatic = 0,
391
+
392
+ /** As above, but use policy return_value_policy::reference when the return
393
+ value is a pointer. This is the default conversion policy for function
394
+ arguments when calling Python functions manually from C++ code (i.e. via
395
+ handle::operator()). You probably won't need to use this. */
396
+ automatic_reference,
397
+
398
+ /** Reference an existing object (i.e. do not create a new copy) and take
399
+ ownership. Python will call the destructor and delete operator when the
400
+ object’s reference count reaches zero. Undefined behavior ensues when
401
+ the C++ side does the same.. */
402
+ take_ownership,
403
+
404
+ /** Create a new copy of the returned object, which will be owned by
405
+ Python. This policy is comparably safe because the lifetimes of the two
406
+ instances are decoupled. */
407
+ copy,
408
+
409
+ /** Use std::move to move the return value contents into a new instance
410
+ that will be owned by Python. This policy is comparably safe because the
411
+ lifetimes of the two instances (move source and destination) are
412
+ decoupled. */
413
+ move,
414
+
415
+ /** Reference an existing object, but do not take ownership. The C++ side
416
+ is responsible for managing the object’s lifetime and deallocating it
417
+ when it is no longer used. Warning: undefined behavior will ensue when
418
+ the C++ side deletes an object that is still referenced and used by
419
+ Python. */
420
+ reference,
421
+
422
+ /** This policy only applies to methods and properties. It references the
423
+ object without taking ownership similar to the above
424
+ return_value_policy::reference policy. In contrast to that policy, the
425
+ function or property’s implicit this argument (called the parent) is
426
+ considered to be the the owner of the return value (the child).
427
+ pybind11 then couples the lifetime of the parent to the child via a
428
+ reference relationship that ensures that the parent cannot be garbage
429
+ collected while Python is still using the child. More advanced
430
+ variations of this scheme are also possible using combinations of
431
+ return_value_policy::reference and the keep_alive call policy */
432
+ reference_internal
433
+ };
434
+
435
+ PYBIND11_NAMESPACE_BEGIN(detail)
436
+
437
+ inline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
438
+
439
+ // Returns the size as a multiple of sizeof(void *), rounded up.
440
+ inline static constexpr size_t size_in_ptrs(size_t s) { return 1 + ((s - 1) >> log2(sizeof(void *))); }
441
+
442
+ /**
443
+ * The space to allocate for simple layout instance holders (see below) in multiple of the size of
444
+ * a pointer (e.g. 2 means 16 bytes on 64-bit architectures). The default is the minimum required
445
+ * to holder either a std::unique_ptr or std::shared_ptr (which is almost always
446
+ * sizeof(std::shared_ptr<T>)).
447
+ */
448
+ constexpr size_t instance_simple_holder_in_ptrs() {
449
+ static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
450
+ "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
451
+ return size_in_ptrs(sizeof(std::shared_ptr<int>));
452
+ }
453
+
454
+ // Forward declarations
455
+ struct type_info;
456
+ struct value_and_holder;
457
+
458
+ struct nonsimple_values_and_holders {
459
+ void **values_and_holders;
460
+ uint8_t *status;
461
+ };
462
+
463
+ /// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
464
+ struct instance {
465
+ PyObject_HEAD
466
+ /// Storage for pointers and holder; see simple_layout, below, for a description
467
+ union {
468
+ void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
469
+ nonsimple_values_and_holders nonsimple;
470
+ };
471
+ /// Weak references
472
+ PyObject *weakrefs;
473
+ /// If true, the pointer is owned which means we're free to manage it with a holder.
474
+ bool owned : 1;
475
+ /**
476
+ * An instance has two possible value/holder layouts.
477
+ *
478
+ * Simple layout (when this flag is true), means the `simple_value_holder` is set with a pointer
479
+ * and the holder object governing that pointer, i.e. [val1*][holder]. This layout is applied
480
+ * whenever there is no python-side multiple inheritance of bound C++ types *and* the type's
481
+ * holder will fit in the default space (which is large enough to hold either a std::unique_ptr
482
+ * or std::shared_ptr).
483
+ *
484
+ * Non-simple layout applies when using custom holders that require more space than `shared_ptr`
485
+ * (which is typically the size of two pointers), or when multiple inheritance is used on the
486
+ * python side. Non-simple layout allocates the required amount of memory to have multiple
487
+ * bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is set to a
488
+ * pointer to allocated space of the required space to hold a sequence of value pointers and
489
+ * holders followed `status`, a set of bit flags (1 byte each), i.e.
490
+ * [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple of
491
+ * `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the
492
+ * beginning of the [bb...] block (but not independently allocated).
493
+ *
494
+ * Status bits indicate whether the associated holder is constructed (&
495
+ * status_holder_constructed) and whether the value pointer is registered (&
496
+ * status_instance_registered) in `registered_instances`.
497
+ */
498
+ bool simple_layout : 1;
499
+ /// For simple layout, tracks whether the holder has been constructed
500
+ bool simple_holder_constructed : 1;
501
+ /// For simple layout, tracks whether the instance is registered in `registered_instances`
502
+ bool simple_instance_registered : 1;
503
+ /// If true, get_internals().patients has an entry for this object
504
+ bool has_patients : 1;
505
+
506
+ /// Initializes all of the above type/values/holders data (but not the instance values themselves)
507
+ void allocate_layout();
508
+
509
+ /// Destroys/deallocates all of the above
510
+ void deallocate_layout() const;
511
+
512
+ /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
513
+ /// omitted). Returns a default-constructed (with `.inst = nullptr`) object on failure if
514
+ /// `throw_if_missing` is false.
515
+ value_and_holder get_value_and_holder(const type_info *find_type = nullptr, bool throw_if_missing = true);
516
+
517
+ /// Bit values for the non-simple status flags
518
+ static constexpr uint8_t status_holder_constructed = 1;
519
+ static constexpr uint8_t status_instance_registered = 2;
520
+ };
521
+
522
+ static_assert(std::is_standard_layout<instance>::value, "Internal error: `pybind11::detail::instance` is not standard layout!");
523
+
524
+ /// from __cpp_future__ import (convenient aliases from C++14/17)
525
+ #if defined(PYBIND11_CPP14) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
526
+ using std::enable_if_t;
527
+ using std::conditional_t;
528
+ using std::remove_cv_t;
529
+ using std::remove_reference_t;
530
+ #else
531
+ template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
532
+ template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
533
+ template <typename T> using remove_cv_t = typename std::remove_cv<T>::type;
534
+ template <typename T> using remove_reference_t = typename std::remove_reference<T>::type;
535
+ #endif
536
+
537
+ /// Index sequences
538
+ #if defined(PYBIND11_CPP14)
539
+ using std::index_sequence;
540
+ using std::make_index_sequence;
541
+ #else
542
+ template<size_t ...> struct index_sequence { };
543
+ template<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
544
+ template<size_t ...S> struct make_index_sequence_impl <0, S...> { using type = index_sequence<S...>; };
545
+ template<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
546
+ #endif
547
+
548
+ /// Make an index sequence of the indices of true arguments
549
+ template <typename ISeq, size_t, bool...> struct select_indices_impl { using type = ISeq; };
550
+ template <size_t... IPrev, size_t I, bool B, bool... Bs> struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
551
+ : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>, I + 1, Bs...> {};
552
+ template <bool... Bs> using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
553
+
554
+ /// Backports of std::bool_constant and std::negation to accommodate older compilers
555
+ template <bool B> using bool_constant = std::integral_constant<bool, B>;
556
+ template <typename T> struct negation : bool_constant<!T::value> { };
557
+
558
+ // PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
559
+ // using the new one (C++14 defect, so generally works on newer compilers, even
560
+ // if not in C++17 mode)
561
+ #if defined(__PGIC__) || defined(__INTEL_COMPILER)
562
+ template<typename... > using void_t = void;
563
+ #else
564
+ template <typename...> struct void_t_impl { using type = void; };
565
+ template <typename... Ts> using void_t = typename void_t_impl<Ts...>::type;
566
+ #endif
567
+
568
+
569
+ /// Compile-time all/any/none of that check the boolean value of all template types
570
+ #if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
571
+ template <class... Ts> using all_of = bool_constant<(Ts::value && ...)>;
572
+ template <class... Ts> using any_of = bool_constant<(Ts::value || ...)>;
573
+ #elif !defined(_MSC_VER)
574
+ template <bool...> struct bools {};
575
+ template <class... Ts> using all_of = std::is_same<
576
+ bools<Ts::value..., true>,
577
+ bools<true, Ts::value...>>;
578
+ template <class... Ts> using any_of = negation<all_of<negation<Ts>...>>;
579
+ #else
580
+ // MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
581
+ // at a slight loss of compilation efficiency).
582
+ template <class... Ts> using all_of = std::conjunction<Ts...>;
583
+ template <class... Ts> using any_of = std::disjunction<Ts...>;
584
+ #endif
585
+ template <class... Ts> using none_of = negation<any_of<Ts...>>;
586
+
587
+ template <class T, template<class> class... Predicates> using satisfies_all_of = all_of<Predicates<T>...>;
588
+ template <class T, template<class> class... Predicates> using satisfies_any_of = any_of<Predicates<T>...>;
589
+ template <class T, template<class> class... Predicates> using satisfies_none_of = none_of<Predicates<T>...>;
590
+
591
+ /// Strip the class from a method type
592
+ template <typename T> struct remove_class { };
593
+ template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { using type = R (A...); };
594
+ template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { using type = R (A...); };
595
+
596
+ /// Helper template to strip away type modifiers
597
+ template <typename T> struct intrinsic_type { using type = T; };
598
+ template <typename T> struct intrinsic_type<const T> { using type = typename intrinsic_type<T>::type; };
599
+ template <typename T> struct intrinsic_type<T*> { using type = typename intrinsic_type<T>::type; };
600
+ template <typename T> struct intrinsic_type<T&> { using type = typename intrinsic_type<T>::type; };
601
+ template <typename T> struct intrinsic_type<T&&> { using type = typename intrinsic_type<T>::type; };
602
+ template <typename T, size_t N> struct intrinsic_type<const T[N]> { using type = typename intrinsic_type<T>::type; };
603
+ template <typename T, size_t N> struct intrinsic_type<T[N]> { using type = typename intrinsic_type<T>::type; };
604
+ template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
605
+
606
+ /// Helper type to replace 'void' in some expressions
607
+ struct void_type { };
608
+
609
+ /// Helper template which holds a list of types
610
+ template <typename...> struct type_list { };
611
+
612
+ /// Compile-time integer sum
613
+ #ifdef __cpp_fold_expressions
614
+ template <typename... Ts> constexpr size_t constexpr_sum(Ts... ns) { return (0 + ... + size_t{ns}); }
615
+ #else
616
+ constexpr size_t constexpr_sum() { return 0; }
617
+ template <typename T, typename... Ts>
618
+ constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
619
+ #endif
620
+
621
+ PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
622
+ /// Implementation details for constexpr functions
623
+ constexpr int first(int i) { return i; }
624
+ template <typename T, typename... Ts>
625
+ constexpr int first(int i, T v, Ts... vs) { return v ? i : first(i + 1, vs...); }
626
+
627
+ constexpr int last(int /*i*/, int result) { return result; }
628
+ template <typename T, typename... Ts>
629
+ constexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); }
630
+ PYBIND11_NAMESPACE_END(constexpr_impl)
631
+
632
+ /// Return the index of the first type in Ts which satisfies Predicate<T>. Returns sizeof...(Ts) if
633
+ /// none match.
634
+ template <template<typename> class Predicate, typename... Ts>
635
+ constexpr int constexpr_first() { return constexpr_impl::first(0, Predicate<Ts>::value...); }
636
+
637
+ /// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
638
+ template <template<typename> class Predicate, typename... Ts>
639
+ constexpr int constexpr_last() { return constexpr_impl::last(0, -1, Predicate<Ts>::value...); }
640
+
641
+ /// Return the Nth element from the parameter pack
642
+ template <size_t N, typename T, typename... Ts>
643
+ struct pack_element { using type = typename pack_element<N - 1, Ts...>::type; };
644
+ template <typename T, typename... Ts>
645
+ struct pack_element<0, T, Ts...> { using type = T; };
646
+
647
+ /// Return the one and only type which matches the predicate, or Default if none match.
648
+ /// If more than one type matches the predicate, fail at compile-time.
649
+ template <template<typename> class Predicate, typename Default, typename... Ts>
650
+ struct exactly_one {
651
+ static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
652
+ static_assert(found <= 1, "Found more than one type matching the predicate");
653
+
654
+ static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
655
+ using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
656
+ };
657
+ template <template<typename> class P, typename Default>
658
+ struct exactly_one<P, Default> { using type = Default; };
659
+
660
+ template <template<typename> class Predicate, typename Default, typename... Ts>
661
+ using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
662
+
663
+ /// Defer the evaluation of type T until types Us are instantiated
664
+ template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
665
+ template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
666
+
667
+ /// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
668
+ /// unlike `std::is_base_of`)
669
+ template <typename Base, typename Derived> using is_strict_base_of = bool_constant<
670
+ std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
671
+
672
+ /// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived pointer
673
+ /// can be converted to a Base pointer)
674
+ /// For unions, `is_base_of<T, T>::value` is False, so we need to check `is_same` as well.
675
+ template <typename Base, typename Derived> using is_accessible_base_of = bool_constant<
676
+ (std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value) && std::is_convertible<Derived *, Base *>::value>;
677
+
678
+ template <template<typename...> class Base>
679
+ struct is_template_base_of_impl {
680
+ template <typename... Us> static std::true_type check(Base<Us...> *);
681
+ static std::false_type check(...);
682
+ };
683
+
684
+ /// Check if a template is the base of a type. For example:
685
+ /// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
686
+ template <template<typename...> class Base, typename T>
687
+ #if !defined(_MSC_VER)
688
+ using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr));
689
+ #else // MSVC2015 has trouble with decltype in template aliases
690
+ struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr)) { };
691
+ #endif
692
+
693
+ /// Check if T is an instantiation of the template `Class`. For example:
694
+ /// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
695
+ template <template<typename...> class Class, typename T>
696
+ struct is_instantiation : std::false_type { };
697
+ template <template<typename...> class Class, typename... Us>
698
+ struct is_instantiation<Class, Class<Us...>> : std::true_type { };
699
+
700
+ /// Check if T is std::shared_ptr<U> where U can be anything
701
+ template <typename T> using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
702
+
703
+ /// Check if T looks like an input iterator
704
+ template <typename T, typename = void> struct is_input_iterator : std::false_type {};
705
+ template <typename T>
706
+ struct is_input_iterator<T, void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
707
+ : std::true_type {};
708
+
709
+ template <typename T> using is_function_pointer = bool_constant<
710
+ std::is_pointer<T>::value && std::is_function<typename std::remove_pointer<T>::type>::value>;
711
+
712
+ template <typename F> struct strip_function_object {
713
+ // If you are encountering an
714
+ // 'error: name followed by "::" must be a class or namespace name'
715
+ // with the Intel compiler and a noexcept function here,
716
+ // try to use noexcept(true) instead of plain noexcept.
717
+ using type = typename remove_class<decltype(&F::operator())>::type;
718
+ };
719
+
720
+ // Extracts the function signature from a function, function pointer or lambda.
721
+ template <typename Function, typename F = remove_reference_t<Function>>
722
+ using function_signature_t = conditional_t<
723
+ std::is_function<F>::value,
724
+ F,
725
+ typename conditional_t<
726
+ std::is_pointer<F>::value || std::is_member_pointer<F>::value,
727
+ std::remove_pointer<F>,
728
+ strip_function_object<F>
729
+ >::type
730
+ >;
731
+
732
+ /// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
733
+ /// pointer. Note that this can catch all sorts of other things, too; this is intended to be used
734
+ /// in a place where passing a lambda makes sense.
735
+ template <typename T> using is_lambda = satisfies_none_of<remove_reference_t<T>,
736
+ std::is_function, std::is_pointer, std::is_member_pointer>;
737
+
738
+ /// Ignore that a variable is unused in compiler warnings
739
+ inline void ignore_unused(const int *) { }
740
+
741
+ // [workaround(intel)] Internal error on fold expression
742
+ /// Apply a function over each element of a parameter pack
743
+ #if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
744
+ // Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
745
+ #define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
746
+ #else
747
+ using expand_side_effects = bool[];
748
+ #define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (void)pybind11::detail::expand_side_effects{ ((PATTERN), void(), false)..., false }
749
+ #endif
750
+
751
+ PYBIND11_NAMESPACE_END(detail)
752
+
753
+ #if defined(_MSC_VER)
754
+ # pragma warning(push)
755
+ # pragma warning(disable: 4275) // warning C4275: An exported class was derived from a class that wasn't exported. Can be ignored when derived from a STL class.
756
+ #endif
757
+ /// C++ bindings of builtin Python exceptions
758
+ class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
759
+ public:
760
+ using std::runtime_error::runtime_error;
761
+ /// Set the error using the Python C API
762
+ virtual void set_error() const = 0;
763
+ };
764
+ #if defined(_MSC_VER)
765
+ # pragma warning(pop)
766
+ #endif
767
+
768
+ #define PYBIND11_RUNTIME_EXCEPTION(name, type) \
769
+ class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception { public: \
770
+ using builtin_exception::builtin_exception; \
771
+ name() : name("") { } \
772
+ void set_error() const override { PyErr_SetString(type, what()); } \
773
+ };
774
+
775
+ PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
776
+ PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
777
+ PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
778
+ PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
779
+ PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
780
+ PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
781
+ PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
782
+ PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
783
+ PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
784
+
785
+ [[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
786
+ [[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
787
+
788
+ template <typename T, typename SFINAE = void> struct format_descriptor { };
789
+
790
+ PYBIND11_NAMESPACE_BEGIN(detail)
791
+ // Returns the index of the given type in the type char array below, and in the list in numpy.h
792
+ // The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
793
+ // complex float,double,long double. Note that the long double types only participate when long
794
+ // double is actually longer than double (it isn't under MSVC).
795
+ // NB: not only the string below but also complex.h and numpy.h rely on this order.
796
+ template <typename T, typename SFINAE = void> struct is_fmt_numeric { static constexpr bool value = false; };
797
+ template <typename T> struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
798
+ static constexpr bool value = true;
799
+ static constexpr int index = std::is_same<T, bool>::value ? 0 : 1 + (
800
+ std::is_integral<T>::value ? detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value : 8 + (
801
+ std::is_same<T, double>::value ? 1 : std::is_same<T, long double>::value ? 2 : 0));
802
+ };
803
+ PYBIND11_NAMESPACE_END(detail)
804
+
805
+ template <typename T> struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
806
+ static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
807
+ static constexpr const char value[2] = { c, '\0' };
808
+ static std::string format() { return std::string(1, c); }
809
+ };
810
+
811
+ #if !defined(PYBIND11_CPP17)
812
+
813
+ template <typename T> constexpr const char format_descriptor<
814
+ T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
815
+
816
+ #endif
817
+
818
+ /// RAII wrapper that temporarily clears any Python error state
819
+ struct error_scope {
820
+ PyObject *type, *value, *trace;
821
+ error_scope() { PyErr_Fetch(&type, &value, &trace); }
822
+ ~error_scope() { PyErr_Restore(type, value, trace); }
823
+ };
824
+
825
+ /// Dummy destructor wrapper that can be used to expose classes with a private destructor
826
+ struct nodelete { template <typename T> void operator()(T*) { } };
827
+
828
+ PYBIND11_NAMESPACE_BEGIN(detail)
829
+ template <typename... Args>
830
+ struct overload_cast_impl {
831
+ // NOLINTNEXTLINE(modernize-use-equals-default): MSVC 2015 needs this
832
+ constexpr overload_cast_impl() {}
833
+
834
+ template <typename Return>
835
+ constexpr auto operator()(Return (*pf)(Args...)) const noexcept
836
+ -> decltype(pf) { return pf; }
837
+
838
+ template <typename Return, typename Class>
839
+ constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
840
+ -> decltype(pmf) { return pmf; }
841
+
842
+ template <typename Return, typename Class>
843
+ constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
844
+ -> decltype(pmf) { return pmf; }
845
+ };
846
+ PYBIND11_NAMESPACE_END(detail)
847
+
848
+ // overload_cast requires variable templates: C++14
849
+ #if defined(PYBIND11_CPP14)
850
+ #define PYBIND11_OVERLOAD_CAST 1
851
+ /// Syntax sugar for resolving overloaded function pointers:
852
+ /// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
853
+ /// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
854
+ template <typename... Args>
855
+ static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
856
+ // MSVC 2015 only accepts this particular initialization syntax for this variable template.
857
+ #endif
858
+
859
+ /// Const member function selector for overload_cast
860
+ /// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
861
+ /// - sweet: overload_cast<Arg>(&Class::func, const_)
862
+ static constexpr auto const_ = std::true_type{};
863
+
864
+ #if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
865
+ template <typename... Args> struct overload_cast {
866
+ static_assert(detail::deferred_t<std::false_type, Args...>::value,
867
+ "pybind11::overload_cast<...> requires compiling in C++14 mode");
868
+ };
869
+ #endif // overload_cast
870
+
871
+ PYBIND11_NAMESPACE_BEGIN(detail)
872
+
873
+ // Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
874
+ // any standard container (or C-style array) supporting std::begin/std::end, any singleton
875
+ // arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
876
+ template <typename T>
877
+ class any_container {
878
+ std::vector<T> v;
879
+ public:
880
+ any_container() = default;
881
+
882
+ // Can construct from a pair of iterators
883
+ template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
884
+ any_container(It first, It last) : v(first, last) { }
885
+
886
+ // Implicit conversion constructor from any arbitrary container type with values convertible to T
887
+ template <typename Container, typename = enable_if_t<std::is_convertible<decltype(*std::begin(std::declval<const Container &>())), T>::value>>
888
+ any_container(const Container &c) : any_container(std::begin(c), std::end(c)) { }
889
+
890
+ // initializer_list's aren't deducible, so don't get matched by the above template; we need this
891
+ // to explicitly allow implicit conversion from one:
892
+ template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
893
+ any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) { }
894
+
895
+ // Avoid copying if given an rvalue vector of the correct type.
896
+ any_container(std::vector<T> &&v) : v(std::move(v)) { }
897
+
898
+ // Moves the vector out of an rvalue any_container
899
+ operator std::vector<T> &&() && { return std::move(v); }
900
+
901
+ // Dereferencing obtains a reference to the underlying vector
902
+ std::vector<T> &operator*() { return v; }
903
+ const std::vector<T> &operator*() const { return v; }
904
+
905
+ // -> lets you call methods on the underlying vector
906
+ std::vector<T> *operator->() { return &v; }
907
+ const std::vector<T> *operator->() const { return &v; }
908
+ };
909
+
910
+ // Forward-declaration; see detail/class.h
911
+ std::string get_fully_qualified_tp_name(PyTypeObject*);
912
+
913
+ template <typename T>
914
+ inline static std::shared_ptr<T> try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
915
+ // Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
916
+ // Use at your own risk!
917
+ // See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
918
+ // the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
919
+ #if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
920
+ return holder_value_ptr->weak_from_this().lock();
921
+ #else
922
+ try {
923
+ return holder_value_ptr->shared_from_this();
924
+ }
925
+ catch (const std::bad_weak_ptr &) {
926
+ return nullptr;
927
+ }
928
+ #endif
929
+ }
930
+
931
+ PYBIND11_NAMESPACE_END(detail)
932
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/detail/descr.h ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ constexpr descr(char const (&s)[N+1]) : descr(s, make_index_sequence<N>()) { }
30
+
31
+ template <size_t... Is>
32
+ constexpr descr(char const (&s)[N+1], index_sequence<Is...>) : text{s[Is]..., '\0'} { }
33
+
34
+ template <typename... Chars>
35
+ constexpr descr(char c, Chars... cs) : text{c, static_cast<char>(cs)..., '\0'} { }
36
+
37
+ static constexpr std::array<const std::type_info *, sizeof...(Ts) + 1> types() {
38
+ return {{&typeid(Ts)..., nullptr}};
39
+ }
40
+ };
41
+
42
+ template <size_t N1, size_t N2, typename... Ts1, typename... Ts2, size_t... Is1, size_t... Is2>
43
+ constexpr descr<N1 + N2, Ts1..., Ts2...> plus_impl(const descr<N1, Ts1...> &a, const descr<N2, Ts2...> &b,
44
+ index_sequence<Is1...>, index_sequence<Is2...>) {
45
+ return {a.text[Is1]..., b.text[Is2]...};
46
+ }
47
+
48
+ template <size_t N1, size_t N2, typename... Ts1, typename... Ts2>
49
+ constexpr descr<N1 + N2, Ts1..., Ts2...> operator+(const descr<N1, Ts1...> &a, const descr<N2, Ts2...> &b) {
50
+ return plus_impl(a, b, make_index_sequence<N1>(), make_index_sequence<N2>());
51
+ }
52
+
53
+ template <size_t N>
54
+ constexpr descr<N - 1> _(char const(&text)[N]) { return descr<N - 1>(text); }
55
+ constexpr descr<0> _(char const(&)[1]) { return {}; }
56
+
57
+ template <size_t Rem, size_t... Digits> struct int_to_str : int_to_str<Rem/10, Rem%10, Digits...> { };
58
+ template <size_t...Digits> struct int_to_str<0, Digits...> {
59
+ static constexpr auto digits = descr<sizeof...(Digits)>(('0' + Digits)...);
60
+ };
61
+
62
+ // Ternary description (like std::conditional)
63
+ template <bool B, size_t N1, size_t N2>
64
+ constexpr enable_if_t<B, descr<N1 - 1>> _(char const(&text1)[N1], char const(&)[N2]) {
65
+ return _(text1);
66
+ }
67
+ template <bool B, size_t N1, size_t N2>
68
+ constexpr enable_if_t<!B, descr<N2 - 1>> _(char const(&)[N1], char const(&text2)[N2]) {
69
+ return _(text2);
70
+ }
71
+
72
+ template <bool B, typename T1, typename T2>
73
+ constexpr enable_if_t<B, T1> _(const T1 &d, const T2 &) { return d; }
74
+ template <bool B, typename T1, typename T2>
75
+ constexpr enable_if_t<!B, T2> _(const T1 &, const T2 &d) { return d; }
76
+
77
+ template <size_t Size> auto constexpr _() -> decltype(int_to_str<Size / 10, Size % 10>::digits) {
78
+ return int_to_str<Size / 10, Size % 10>::digits;
79
+ }
80
+
81
+ template <typename Type> constexpr descr<1, Type> _() { return {'%'}; }
82
+
83
+ constexpr descr<0> concat() { return {}; }
84
+
85
+ template <size_t N, typename... Ts>
86
+ constexpr descr<N, Ts...> concat(const descr<N, Ts...> &descr) { return descr; }
87
+
88
+ template <size_t N, typename... Ts, typename... Args>
89
+ constexpr auto concat(const descr<N, Ts...> &d, const Args &...args)
90
+ -> decltype(std::declval<descr<N + 2, Ts...>>() + concat(args...)) {
91
+ return d + _(", ") + concat(args...);
92
+ }
93
+
94
+ template <size_t N, typename... Ts>
95
+ constexpr descr<N + 2, Ts...> type_descr(const descr<N, Ts...> &descr) {
96
+ return _("{") + descr + _("}");
97
+ }
98
+
99
+ PYBIND11_NAMESPACE_END(detail)
100
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
third-party/DPVO/Pangolin/components/pango_python/pybind11/include/pybind11/detail/init.h ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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> using cast_op_type = value_and_holder &;
26
+ operator value_and_holder &() { return *value; }
27
+ static constexpr auto name = _<value_and_holder>();
28
+
29
+ private:
30
+ value_and_holder *value = nullptr;
31
+ };
32
+
33
+ PYBIND11_NAMESPACE_BEGIN(initimpl)
34
+
35
+ inline void no_nullptr(void *ptr) {
36
+ if (!ptr) throw type_error("pybind11::init(): factory function returned nullptr");
37
+ }
38
+
39
+ // Implementing functions for all forms of py::init<...> and py::init(...)
40
+ template <typename Class> using Cpp = typename Class::type;
41
+ template <typename Class> using Alias = typename Class::type_alias;
42
+ template <typename Class> using Holder = typename Class::holder_type;
43
+
44
+ template <typename Class> using is_alias_constructible = std::is_constructible<Alias<Class>, Cpp<Class> &&>;
45
+
46
+ // Takes a Cpp pointer and returns true if it actually is a polymorphic Alias instance.
47
+ template <typename Class, enable_if_t<Class::has_alias, int> = 0>
48
+ bool is_alias(Cpp<Class> *ptr) {
49
+ return dynamic_cast<Alias<Class> *>(ptr) != nullptr;
50
+ }
51
+ // Failing fallback version of the above for a no-alias class (always returns false)
52
+ template <typename /*Class*/>
53
+ constexpr bool is_alias(void *) { return false; }
54
+
55
+ // Constructs and returns a new object; if the given arguments don't map to a constructor, we fall
56
+ // back to brace aggregate initiailization so that for aggregate initialization can be used with
57
+ // py::init, e.g. `py::init<int, int>` to initialize a `struct T { int a; int b; }`. For
58
+ // non-aggregate types, we need to use an ordinary T(...) constructor (invoking as `T{...}` usually
59
+ // works, but will not do the expected thing when `T` has an `initializer_list<T>` constructor).
60
+ template <typename Class, typename... Args, detail::enable_if_t<std::is_constructible<Class, Args...>::value, int> = 0>
61
+ inline Class *construct_or_initialize(Args &&...args) { return new Class(std::forward<Args>(args)...); }
62
+ template <typename Class, typename... Args, detail::enable_if_t<!std::is_constructible<Class, Args...>::value, int> = 0>
63
+ inline Class *construct_or_initialize(Args &&...args) { return new Class{std::forward<Args>(args)...}; }
64
+
65
+ // Attempts to constructs an alias using a `Alias(Cpp &&)` constructor. This allows types with
66
+ // an alias to provide only a single Cpp factory function as long as the Alias can be
67
+ // constructed from an rvalue reference of the base Cpp type. This means that Alias classes
68
+ // can, when appropriate, simply define a `Alias(Cpp &&)` constructor rather than needing to
69
+ // inherit all the base class constructors.
70
+ template <typename Class>
71
+ void construct_alias_from_cpp(std::true_type /*is_alias_constructible*/,
72
+ value_and_holder &v_h, Cpp<Class> &&base) {
73
+ v_h.value_ptr() = new Alias<Class>(std::move(base));
74
+ }
75
+ template <typename Class>
76
+ [[noreturn]] void construct_alias_from_cpp(std::false_type /*!is_alias_constructible*/,
77
+ value_and_holder &, Cpp<Class> &&) {
78
+ throw type_error("pybind11::init(): unable to convert returned instance to required "
79
+ "alias class: no `Alias<Class>(Class &&)` constructor available");
80
+ }
81
+
82
+ // Error-generating fallback for factories that don't match one of the below construction
83
+ // mechanisms.
84
+ template <typename Class>
85
+ void construct(...) {
86
+ static_assert(!std::is_same<Class, Class>::value /* always false */,
87
+ "pybind11::init(): init function must return a compatible pointer, "
88
+ "holder, or value");
89
+ }
90
+
91
+ // Pointer return v1: the factory function returns a class pointer for a registered class.
92
+ // If we don't need an alias (because this class doesn't have one, or because the final type is
93
+ // inherited on the Python side) we can simply take over ownership. Otherwise we need to try to
94
+ // construct an Alias from the returned base instance.
95
+ template <typename Class>
96
+ void construct(value_and_holder &v_h, Cpp<Class> *ptr, bool need_alias) {
97
+ no_nullptr(ptr);
98
+ if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
99
+ // We're going to try to construct an alias by moving the cpp type. Whether or not
100
+ // that succeeds, we still need to destroy the original cpp pointer (either the
101
+ // moved away leftover, if the alias construction works, or the value itself if we
102
+ // throw an error), but we can't just call `delete ptr`: it might have a special
103
+ // deleter, or might be shared_from_this. So we construct a holder around it as if
104
+ // it was a normal instance, then steal the holder away into a local variable; thus
105
+ // the holder and destruction happens when we leave the C++ scope, and the holder
106
+ // class gets to handle the destruction however it likes.
107
+ v_h.value_ptr() = ptr;
108
+ v_h.set_instance_registered(true); // To prevent init_instance from registering it
109
+ v_h.type->init_instance(v_h.inst, nullptr); // Set up the holder
110
+ Holder<Class> temp_holder(std::move(v_h.holder<Holder<Class>>())); // Steal the holder
111
+ v_h.type->dealloc(v_h); // Destroys the moved-out holder remains, resets value ptr to null
112
+ v_h.set_instance_registered(false);
113
+
114
+ construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(*ptr));
115
+ } else {
116
+ // Otherwise the type isn't inherited, so we don't need an Alias
117
+ v_h.value_ptr() = ptr;
118
+ }
119
+ }
120
+
121
+ // Pointer return v2: a factory that always returns an alias instance ptr. We simply take over
122
+ // ownership of the pointer.
123
+ template <typename Class, enable_if_t<Class::has_alias, int> = 0>
124
+ void construct(value_and_holder &v_h, Alias<Class> *alias_ptr, bool) {
125
+ no_nullptr(alias_ptr);
126
+ v_h.value_ptr() = static_cast<Cpp<Class> *>(alias_ptr);
127
+ }
128
+
129
+ // Holder return: copy its pointer, and move or copy the returned holder into the new instance's
130
+ // holder. This also handles types like std::shared_ptr<T> and std::unique_ptr<T> where T is a
131
+ // derived type (through those holder's implicit conversion from derived class holder constructors).
132
+ template <typename Class>
133
+ void construct(value_and_holder &v_h, Holder<Class> holder, bool need_alias) {
134
+ auto *ptr = holder_helper<Holder<Class>>::get(holder);
135
+ no_nullptr(ptr);
136
+ // If we need an alias, check that the held pointer is actually an alias instance
137
+ if (Class::has_alias && need_alias && !is_alias<Class>(ptr))
138
+ throw type_error("pybind11::init(): construction failed: returned holder-wrapped instance "
139
+ "is not an alias instance");
140
+
141
+ v_h.value_ptr() = ptr;
142
+ v_h.type->init_instance(v_h.inst, &holder);
143
+ }
144
+
145
+ // return-by-value version 1: returning a cpp class by value. If the class has an alias and an
146
+ // alias is required the alias must have an `Alias(Cpp &&)` constructor so that we can construct
147
+ // the alias from the base when needed (i.e. because of Python-side inheritance). When we don't
148
+ // need it, we simply move-construct the cpp value into a new instance.
149
+ template <typename Class>
150
+ void construct(value_and_holder &v_h, Cpp<Class> &&result, bool need_alias) {
151
+ static_assert(std::is_move_constructible<Cpp<Class>>::value,
152
+ "pybind11::init() return-by-value factory function requires a movable class");
153
+ if (Class::has_alias && need_alias)
154
+ construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(result));
155
+ else
156
+ v_h.value_ptr() = new Cpp<Class>(std::move(result));
157
+ }
158
+
159
+ // return-by-value version 2: returning a value of the alias type itself. We move-construct an
160
+ // Alias instance (even if no the python-side inheritance is involved). The is intended for
161
+ // cases where Alias initialization is always desired.
162
+ template <typename Class>
163
+ void construct(value_and_holder &v_h, Alias<Class> &&result, bool) {
164
+ static_assert(std::is_move_constructible<Alias<Class>>::value,
165
+ "pybind11::init() return-by-alias-value factory function requires a movable alias class");
166
+ v_h.value_ptr() = new Alias<Class>(std::move(result));
167
+ }
168
+
169
+ // Implementing class for py::init<...>()
170
+ template <typename... Args>
171
+ struct constructor {
172
+ template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
173
+ static void execute(Class &cl, const Extra&... extra) {
174
+ cl.def("__init__", [](value_and_holder &v_h, Args... args) {
175
+ v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
176
+ }, is_new_style_constructor(), extra...);
177
+ }
178
+
179
+ template <typename Class, typename... Extra,
180
+ enable_if_t<Class::has_alias &&
181
+ std::is_constructible<Cpp<Class>, Args...>::value, int> = 0>
182
+ static void execute(Class &cl, const Extra&... extra) {
183
+ cl.def("__init__", [](value_and_holder &v_h, Args... args) {
184
+ if (Py_TYPE(v_h.inst) == v_h.type->type)
185
+ v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
186
+ else
187
+ v_h.value_ptr() = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
188
+ }, is_new_style_constructor(), extra...);
189
+ }
190
+
191
+ template <typename Class, typename... Extra,
192
+ enable_if_t<Class::has_alias &&
193
+ !std::is_constructible<Cpp<Class>, Args...>::value, int> = 0>
194
+ static void execute(Class &cl, const Extra&... extra) {
195
+ cl.def("__init__", [](value_and_holder &v_h, Args... args) {
196
+ v_h.value_ptr() = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
197
+ }, is_new_style_constructor(), extra...);
198
+ }
199
+ };
200
+
201
+ // Implementing class for py::init_alias<...>()
202
+ template <typename... Args> struct alias_constructor {
203
+ template <typename Class, typename... Extra,
204
+ enable_if_t<Class::has_alias && std::is_constructible<Alias<Class>, Args...>::value, int> = 0>
205
+ static void execute(Class &cl, const Extra&... extra) {
206
+ cl.def("__init__", [](value_and_holder &v_h, Args... args) {
207
+ v_h.value_ptr() = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
208
+ }, is_new_style_constructor(), extra...);
209
+ }
210
+ };
211
+
212
+ // Implementation class for py::init(Func) and py::init(Func, AliasFunc)
213
+ template <typename CFunc, typename AFunc = void_type (*)(),
214
+ typename = function_signature_t<CFunc>, typename = function_signature_t<AFunc>>
215
+ struct factory;
216
+
217
+ // Specialization for py::init(Func)
218
+ template <typename Func, typename Return, typename... Args>
219
+ struct factory<Func, void_type (*)(), Return(Args...)> {
220
+ remove_reference_t<Func> class_factory;
221
+
222
+ factory(Func &&f) : class_factory(std::forward<Func>(f)) { }
223
+
224
+ // The given class either has no alias or has no separate alias factory;
225
+ // this always constructs the class itself. If the class is registered with an alias
226
+ // type and an alias instance is needed (i.e. because the final type is a Python class
227
+ // inheriting from the C++ type) the returned value needs to either already be an alias
228
+ // instance, or the alias needs to be constructible from a `Class &&` argument.
229
+ template <typename Class, typename... Extra>
230
+ void execute(Class &cl, const Extra &...extra) && {
231
+ #if defined(PYBIND11_CPP14)
232
+ cl.def("__init__", [func = std::move(class_factory)]
233
+ #else
234
+ auto &func = class_factory;
235
+ cl.def("__init__", [func]
236
+ #endif
237
+ (value_and_holder &v_h, Args... args) {
238
+ construct<Class>(v_h, func(std::forward<Args>(args)...),
239
+ Py_TYPE(v_h.inst) != v_h.type->type);
240
+ }, is_new_style_constructor(), extra...);
241
+ }
242
+ };
243
+
244
+ // Specialization for py::init(Func, AliasFunc)
245
+ template <typename CFunc, typename AFunc,
246
+ typename CReturn, typename... CArgs, typename AReturn, typename... AArgs>
247
+ struct factory<CFunc, AFunc, CReturn(CArgs...), AReturn(AArgs...)> {
248
+ static_assert(sizeof...(CArgs) == sizeof...(AArgs),
249
+ "pybind11::init(class_factory, alias_factory): class and alias factories "
250
+ "must have identical argument signatures");
251
+ static_assert(all_of<std::is_same<CArgs, AArgs>...>::value,
252
+ "pybind11::init(class_factory, alias_factory): class and alias factories "
253
+ "must have identical argument signatures");
254
+
255
+ remove_reference_t<CFunc> class_factory;
256
+ remove_reference_t<AFunc> alias_factory;
257
+
258
+ factory(CFunc &&c, AFunc &&a)
259
+ : class_factory(std::forward<CFunc>(c)), alias_factory(std::forward<AFunc>(a)) { }
260
+
261
+ // The class factory is called when the `self` type passed to `__init__` is the direct
262
+ // class (i.e. not inherited), the alias factory when `self` is a Python-side subtype.
263
+ template <typename Class, typename... Extra>
264
+ void execute(Class &cl, const Extra&... extra) && {
265
+ static_assert(Class::has_alias, "The two-argument version of `py::init()` can "
266
+ "only be used if the class has an alias");
267
+ #if defined(PYBIND11_CPP14)
268
+ cl.def("__init__", [class_func = std::move(class_factory), alias_func = std::move(alias_factory)]
269
+ #else
270
+ auto &class_func = class_factory;
271
+ auto &alias_func = alias_factory;
272
+ cl.def("__init__", [class_func, alias_func]
273
+ #endif
274
+ (value_and_holder &v_h, CArgs... args) {
275
+ if (Py_TYPE(v_h.inst) == v_h.type->type)
276
+ // If the instance type equals the registered type we don't have inheritance, so
277
+ // don't need the alias and can construct using the class function:
278
+ construct<Class>(v_h, class_func(std::forward<CArgs>(args)...), false);
279
+ else
280
+ construct<Class>(v_h, alias_func(std::forward<CArgs>(args)...), true);
281
+ }, is_new_style_constructor(), extra...);
282
+ }
283
+ };
284
+
285
+ /// Set just the C++ state. Same as `__init__`.
286
+ template <typename Class, typename T>
287
+ void setstate(value_and_holder &v_h, T &&result, bool need_alias) {
288
+ construct<Class>(v_h, std::forward<T>(result), need_alias);
289
+ }
290
+
291
+ /// Set both the C++ and Python states
292
+ template <typename Class, typename T, typename O,
293
+ enable_if_t<std::is_convertible<O, handle>::value, int> = 0>
294
+ void setstate(value_and_holder &v_h, std::pair<T, O> &&result, bool need_alias) {
295
+ construct<Class>(v_h, std::move(result.first), need_alias);
296
+ auto d = handle(result.second);
297
+ if (PyDict_Check(d.ptr()) && PyDict_Size(d.ptr()) == 0) {
298
+ // Skipping setattr below, to not force use of py::dynamic_attr() for Class unnecessarily.
299
+ // See PR #2972 for details.
300
+ return;
301
+ }
302
+ setattr((PyObject *) v_h.inst, "__dict__", d);
303
+ }
304
+
305
+ /// Implementation for py::pickle(GetState, SetState)
306
+ template <typename Get, typename Set,
307
+ typename = function_signature_t<Get>, typename = function_signature_t<Set>>
308
+ struct pickle_factory;
309
+
310
+ template <typename Get, typename Set,
311
+ typename RetState, typename Self, typename NewInstance, typename ArgState>
312
+ struct pickle_factory<Get, Set, RetState(Self), NewInstance(ArgState)> {
313
+ static_assert(std::is_same<intrinsic_t<RetState>, intrinsic_t<ArgState>>::value,
314
+ "The type returned by `__getstate__` must be the same "
315
+ "as the argument accepted by `__setstate__`");
316
+
317
+ remove_reference_t<Get> get;
318
+ remove_reference_t<Set> set;
319
+
320
+ pickle_factory(Get get, Set set)
321
+ : get(std::forward<Get>(get)), set(std::forward<Set>(set)) { }
322
+
323
+ template <typename Class, typename... Extra>
324
+ void execute(Class &cl, const Extra &...extra) && {
325
+ cl.def("__getstate__", std::move(get));
326
+
327
+ #if defined(PYBIND11_CPP14)
328
+ cl.def("__setstate__", [func = std::move(set)]
329
+ #else
330
+ auto &func = set;
331
+ cl.def("__setstate__", [func]
332
+ #endif
333
+ (value_and_holder &v_h, ArgState state) {
334
+ setstate<Class>(v_h, func(std::forward<ArgState>(state)),
335
+ Py_TYPE(v_h.inst) != v_h.type->type);
336
+ }, is_new_style_constructor(), extra...);
337
+ }
338
+ };
339
+
340
+ PYBIND11_NAMESPACE_END(initimpl)
341
+ PYBIND11_NAMESPACE_END(detail)
342
+ PYBIND11_NAMESPACE_END(pybind11)