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