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
8.9 KiB

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