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.

244 lines
9.0 KiB

2 months ago
  1. Miscellaneous
  2. #############
  3. .. _macro_notes:
  4. General notes regarding convenience macros
  5. ==========================================
  6. pybind11 provides a few convenience macros such as
  7. :func:`PYBIND11_MAKE_OPAQUE` and :func:`PYBIND11_DECLARE_HOLDER_TYPE`, and
  8. ``PYBIND11_OVERLOAD_*``. Since these are "just" macros that are evaluated
  9. in the preprocessor (which has no concept of types), they *will* get confused
  10. by commas in a template argument such as ``PYBIND11_OVERLOAD(MyReturnValue<T1,
  11. T2>, myFunc)``. In this case, the preprocessor assumes that the comma indicates
  12. the beginning of the next parameter. Use a ``typedef`` to bind the template to
  13. another name and use it in the macro to avoid this problem.
  14. .. _gil:
  15. Global Interpreter Lock (GIL)
  16. =============================
  17. When calling a C++ function from Python, the GIL is always held.
  18. The classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
  19. used to acquire and release the global interpreter lock in the body of a C++
  20. function call. In this way, long-running C++ code can be parallelized using
  21. multiple Python threads. Taking :ref:`overriding_virtuals` as an example, this
  22. could be realized as follows (important changes highlighted):
  23. .. code-block:: cpp
  24. :emphasize-lines: 8,9,31,32
  25. class PyAnimal : public Animal {
  26. public:
  27. /* Inherit the constructors */
  28. using Animal::Animal;
  29. /* Trampoline (need one for each virtual function) */
  30. std::string go(int n_times) {
  31. /* Acquire GIL before calling Python code */
  32. py::gil_scoped_acquire acquire;
  33. PYBIND11_OVERLOAD_PURE(
  34. std::string, /* Return type */
  35. Animal, /* Parent class */
  36. go, /* Name of function */
  37. n_times /* Argument(s) */
  38. );
  39. }
  40. };
  41. PYBIND11_MODULE(example, m) {
  42. py::class_<Animal, PyAnimal> animal(m, "Animal");
  43. animal
  44. .def(py::init<>())
  45. .def("go", &Animal::go);
  46. py::class_<Dog>(m, "Dog", animal)
  47. .def(py::init<>());
  48. m.def("call_go", [](Animal *animal) -> std::string {
  49. /* Release GIL before calling into (potentially long-running) C++ code */
  50. py::gil_scoped_release release;
  51. return call_go(animal);
  52. });
  53. }
  54. The ``call_go`` wrapper can also be simplified using the `call_guard` policy
  55. (see :ref:`call_policies`) which yields the same result:
  56. .. code-block:: cpp
  57. m.def("call_go", &call_go, py::call_guard<py::gil_scoped_release>());
  58. Binding sequence data types, iterators, the slicing protocol, etc.
  59. ==================================================================
  60. Please refer to the supplemental example for details.
  61. .. seealso::
  62. The file :file:`tests/test_sequences_and_iterators.cpp` contains a
  63. complete example that shows how to bind a sequence data type, including
  64. length queries (``__len__``), iterators (``__iter__``), the slicing
  65. protocol and other kinds of useful operations.
  66. Partitioning code over multiple extension modules
  67. =================================================
  68. It's straightforward to split binding code over multiple extension modules,
  69. while referencing types that are declared elsewhere. Everything "just" works
  70. without any special precautions. One exception to this rule occurs when
  71. extending a type declared in another extension module. Recall the basic example
  72. from Section :ref:`inheritance`.
  73. .. code-block:: cpp
  74. py::class_<Pet> pet(m, "Pet");
  75. pet.def(py::init<const std::string &>())
  76. .def_readwrite("name", &Pet::name);
  77. py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
  78. .def(py::init<const std::string &>())
  79. .def("bark", &Dog::bark);
  80. Suppose now that ``Pet`` bindings are defined in a module named ``basic``,
  81. whereas the ``Dog`` bindings are defined somewhere else. The challenge is of
  82. course that the variable ``pet`` is not available anymore though it is needed
  83. to indicate the inheritance relationship to the constructor of ``class_<Dog>``.
  84. However, it can be acquired as follows:
  85. .. code-block:: cpp
  86. py::object pet = (py::object) py::module::import("basic").attr("Pet");
  87. py::class_<Dog>(m, "Dog", pet)
  88. .def(py::init<const std::string &>())
  89. .def("bark", &Dog::bark);
  90. Alternatively, you can specify the base class as a template parameter option to
  91. ``class_``, which performs an automated lookup of the corresponding Python
  92. type. Like the above code, however, this also requires invoking the ``import``
  93. function once to ensure that the pybind11 binding code of the module ``basic``
  94. has been executed:
  95. .. code-block:: cpp
  96. py::module::import("basic");
  97. py::class_<Dog, Pet>(m, "Dog")
  98. .def(py::init<const std::string &>())
  99. .def("bark", &Dog::bark);
  100. Naturally, both methods will fail when there are cyclic dependencies.
  101. Note that compiling code which has its default symbol visibility set to
  102. *hidden* (e.g. via the command line flag ``-fvisibility=hidden`` on GCC/Clang) can interfere with the
  103. ability to access types defined in another extension module. Workarounds
  104. include changing the global symbol visibility (not recommended, because it will
  105. lead unnecessarily large binaries) or manually exporting types that are
  106. accessed by multiple extension modules:
  107. .. code-block:: cpp
  108. #ifdef _WIN32
  109. # define EXPORT_TYPE __declspec(dllexport)
  110. #else
  111. # define EXPORT_TYPE __attribute__ ((visibility("default")))
  112. #endif
  113. class EXPORT_TYPE Dog : public Animal {
  114. ...
  115. };
  116. Note also that it is possible (although would rarely be required) to share arbitrary
  117. C++ objects between extension modules at runtime. Internal library data is shared
  118. between modules using capsule machinery [#f6]_ which can be also utilized for
  119. storing, modifying and accessing user-defined data. Note that an extension module
  120. will "see" other extensions' data if and only if they were built with the same
  121. pybind11 version. Consider the following example:
  122. .. code-block:: cpp
  123. auto data = (MyData *) py::get_shared_data("mydata");
  124. if (!data)
  125. data = (MyData *) py::set_shared_data("mydata", new MyData(42));
  126. If the above snippet was used in several separately compiled extension modules,
  127. the first one to be imported would create a ``MyData`` instance and associate
  128. a ``"mydata"`` key with a pointer to it. Extensions that are imported later
  129. would be then able to access the data behind the same pointer.
  130. .. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules
  131. Module Destructors
  132. ==================
  133. pybind11 does not provide an explicit mechanism to invoke cleanup code at
  134. module destruction time. In rare cases where such functionality is required, it
  135. is possible to emulate it using Python capsules with a destruction callback.
  136. .. code-block:: cpp
  137. auto cleanup_callback = []() {
  138. // perform cleanup here -- this function is called with the GIL held
  139. };
  140. m.add_object("_cleanup", py::capsule(cleanup_callback));
  141. Generating documentation using Sphinx
  142. =====================================
  143. Sphinx [#f4]_ has the ability to inspect the signatures and documentation
  144. strings in pybind11-based extension modules to automatically generate beautiful
  145. documentation in a variety formats. The python_example repository [#f5]_ contains a
  146. simple example repository which uses this approach.
  147. There are two potential gotchas when using this approach: first, make sure that
  148. the resulting strings do not contain any :kbd:`TAB` characters, which break the
  149. docstring parsing routines. You may want to use C++11 raw string literals,
  150. which are convenient for multi-line comments. Conveniently, any excess
  151. indentation will be automatically be removed by Sphinx. However, for this to
  152. work, it is important that all lines are indented consistently, i.e.:
  153. .. code-block:: cpp
  154. // ok
  155. m.def("foo", &foo, R"mydelimiter(
  156. The foo function
  157. Parameters
  158. ----------
  159. )mydelimiter");
  160. // *not ok*
  161. m.def("foo", &foo, R"mydelimiter(The foo function
  162. Parameters
  163. ----------
  164. )mydelimiter");
  165. By default, pybind11 automatically generates and prepends a signature to the docstring of a function
  166. registered with ``module::def()`` and ``class_::def()``. Sometimes this
  167. behavior is not desirable, because you want to provide your own signature or remove
  168. the docstring completely to exclude the function from the Sphinx documentation.
  169. The class ``options`` allows you to selectively suppress auto-generated signatures:
  170. .. code-block:: cpp
  171. PYBIND11_MODULE(example, m) {
  172. py::options options;
  173. options.disable_function_signatures();
  174. m.def("add", [](int a, int b) { return a + b; }, "A function which adds two numbers");
  175. }
  176. Note that changes to the settings affect only function bindings created during the
  177. lifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function,
  178. the default settings are restored to prevent unwanted side effects.
  179. .. [#f4] http://www.sphinx-doc.org
  180. .. [#f5] http://github.com/pybind/python_example