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.

154 lines
5.2 KiB

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