The source code and dockerfile for the GSW2024 AI Lab.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

201 lines
7.1 KiB

4 weeks ago
  1. STL containers
  2. ##############
  3. Automatic conversion
  4. ====================
  5. When including the additional header file :file:`pybind11/stl.h`, conversions
  6. between ``std::vector<>``/``std::list<>``/``std::array<>``,
  7. ``std::set<>``/``std::unordered_set<>``, and
  8. ``std::map<>``/``std::unordered_map<>`` and the Python ``list``, ``set`` and
  9. ``dict`` data structures are automatically enabled. The types ``std::pair<>``
  10. and ``std::tuple<>`` are already supported out of the box with just the core
  11. :file:`pybind11/pybind11.h` header.
  12. The major downside of these implicit conversions is that containers must be
  13. converted (i.e. copied) on every Python->C++ and C++->Python transition, which
  14. can have implications on the program semantics and performance. Please read the
  15. next sections for more details and alternative approaches that avoid this.
  16. .. note::
  17. Arbitrary nesting of any of these types is possible.
  18. .. seealso::
  19. The file :file:`tests/test_stl.cpp` contains a complete
  20. example that demonstrates how to pass STL data types in more detail.
  21. C++17 library containers
  22. ========================
  23. The :file:`pybind11/stl.h` header also includes support for ``std::optional<>``
  24. and ``std::variant<>``. These require a C++17 compiler and standard library.
  25. In C++14 mode, ``std::experimental::optional<>`` is supported if available.
  26. Various versions of these containers also exist for C++11 (e.g. in Boost).
  27. pybind11 provides an easy way to specialize the ``type_caster`` for such
  28. types:
  29. .. code-block:: cpp
  30. // `boost::optional` as an example -- can be any `std::optional`-like container
  31. namespace pybind11 { namespace detail {
  32. template <typename T>
  33. struct type_caster<boost::optional<T>> : optional_caster<boost::optional<T>> {};
  34. }}
  35. The above should be placed in a header file and included in all translation units
  36. where automatic conversion is needed. Similarly, a specialization can be provided
  37. for custom variant types:
  38. .. code-block:: cpp
  39. // `boost::variant` as an example -- can be any `std::variant`-like container
  40. namespace pybind11 { namespace detail {
  41. template <typename... Ts>
  42. struct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {};
  43. // Specifies the function used to visit the variant -- `apply_visitor` instead of `visit`
  44. template <>
  45. struct visit_helper<boost::variant> {
  46. template <typename... Args>
  47. static auto call(Args &&...args)
  48. -> decltype(boost::apply_visitor(std::forward<Args>(args)...)) {
  49. return boost::apply_visitor(std::forward<Args>(args)...);
  50. }
  51. };
  52. }} // namespace pybind11::detail
  53. The ``visit_helper`` specialization is not required if your ``name::variant`` provides
  54. a ``name::visit()`` function. For any other function name, the specialization must be
  55. included to tell pybind11 how to visit the variant.
  56. .. _opaque:
  57. Making opaque types
  58. ===================
  59. pybind11 heavily relies on a template matching mechanism to convert parameters
  60. and return values that are constructed from STL data types such as vectors,
  61. linked lists, hash tables, etc. This even works in a recursive manner, for
  62. instance to deal with lists of hash maps of pairs of elementary and custom
  63. types, etc.
  64. However, a fundamental limitation of this approach is that internal conversions
  65. between Python and C++ types involve a copy operation that prevents
  66. pass-by-reference semantics. What does this mean?
  67. Suppose we bind the following function
  68. .. code-block:: cpp
  69. void append_1(std::vector<int> &v) {
  70. v.push_back(1);
  71. }
  72. and call it from Python, the following happens:
  73. .. code-block:: pycon
  74. >>> v = [5, 6]
  75. >>> append_1(v)
  76. >>> print(v)
  77. [5, 6]
  78. As you can see, when passing STL data structures by reference, modifications
  79. are not propagated back the Python side. A similar situation arises when
  80. exposing STL data structures using the ``def_readwrite`` or ``def_readonly``
  81. functions:
  82. .. code-block:: cpp
  83. /* ... definition ... */
  84. class MyClass {
  85. std::vector<int> contents;
  86. };
  87. /* ... binding code ... */
  88. py::class_<MyClass>(m, "MyClass")
  89. .def(py::init<>())
  90. .def_readwrite("contents", &MyClass::contents);
  91. In this case, properties can be read and written in their entirety. However, an
  92. ``append`` operation involving such a list type has no effect:
  93. .. code-block:: pycon
  94. >>> m = MyClass()
  95. >>> m.contents = [5, 6]
  96. >>> print(m.contents)
  97. [5, 6]
  98. >>> m.contents.append(7)
  99. >>> print(m.contents)
  100. [5, 6]
  101. Finally, the involved copy operations can be costly when dealing with very
  102. large lists. To deal with all of the above situations, pybind11 provides a
  103. macro named ``PYBIND11_MAKE_OPAQUE(T)`` that disables the template-based
  104. conversion machinery of types, thus rendering them *opaque*. The contents of
  105. opaque objects are never inspected or extracted, hence they *can* be passed by
  106. reference. For instance, to turn ``std::vector<int>`` into an opaque type, add
  107. the declaration
  108. .. code-block:: cpp
  109. PYBIND11_MAKE_OPAQUE(std::vector<int>);
  110. before any binding code (e.g. invocations to ``class_::def()``, etc.). This
  111. macro must be specified at the top level (and outside of any namespaces), since
  112. it instantiates a partial template overload. If your binding code consists of
  113. multiple compilation units, it must be present in every file preceding any
  114. usage of ``std::vector<int>``. Opaque types must also have a corresponding
  115. ``class_`` declaration to associate them with a name in Python, and to define a
  116. set of available operations, e.g.:
  117. .. code-block:: cpp
  118. py::class_<std::vector<int>>(m, "IntVector")
  119. .def(py::init<>())
  120. .def("clear", &std::vector<int>::clear)
  121. .def("pop_back", &std::vector<int>::pop_back)
  122. .def("__len__", [](const std::vector<int> &v) { return v.size(); })
  123. .def("__iter__", [](std::vector<int> &v) {
  124. return py::make_iterator(v.begin(), v.end());
  125. }, py::keep_alive<0, 1>()) /* Keep vector alive while iterator is used */
  126. // ....
  127. The ability to expose STL containers as native Python objects is a fairly
  128. common request, hence pybind11 also provides an optional header file named
  129. :file:`pybind11/stl_bind.h` that does exactly this. The mapped containers try
  130. to match the behavior of their native Python counterparts as much as possible.
  131. The following example showcases usage of :file:`pybind11/stl_bind.h`:
  132. .. code-block:: cpp
  133. // Don't forget this
  134. #include <pybind11/stl_bind.h>
  135. PYBIND11_MAKE_OPAQUE(std::vector<int>);
  136. PYBIND11_MAKE_OPAQUE(std::map<std::string, double>);
  137. // ...
  138. // later in binding code:
  139. py::bind_vector<std::vector<int>>(m, "VectorInt");
  140. py::bind_map<std::map<std::string, double>>(m, "MapStringDouble");
  141. Please take a look at the :ref:`macro_notes` before using the
  142. ``PYBIND11_MAKE_OPAQUE`` macro.
  143. .. seealso::
  144. The file :file:`tests/test_opaque_types.cpp` contains a complete
  145. example that demonstrates how to create and expose opaque types using
  146. pybind11 in more detail.
  147. The file :file:`tests/test_stl_binders.cpp` shows how to use the
  148. convenience STL container wrappers.