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.

229 lines
8.4 KiB

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