blob: 6ebc0c34320e5d73aae85dfa1dd438463fe576c9 [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
31 :emphasize-lines: 8,9,33,34
32
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
52 PYBIND11_PLUGIN(example) {
53 py::module m("example", "pybind11 example plugin");
54
55 py::class_<Animal, PyAnimal> animal(m, "Animal");
56 animal
57 .def(py::init<>())
58 .def("go", &Animal::go);
59
60 py::class_<Dog>(m, "Dog", animal)
61 .def(py::init<>());
62
63 m.def("call_go", [](Animal *animal) -> std::string {
64 /* Release GIL before calling into (potentially long-running) C++ code */
65 py::gil_scoped_release release;
66 return call_go(animal);
67 });
68
69 return m.ptr();
70 }
71
Dean Moldovan1ac19032017-03-16 11:22:26 +010072The ``call_go`` wrapper can also be simplified using the `call_guard` policy
73(see :ref:`call_policies`) which yields the same result:
74
75.. code-block:: cpp
76
77 m.def("call_go", &call_go, py::call_guard<py::gil_scoped_release>());
78
Dean Moldovan67b52d82016-10-16 19:12:43 +020079
80Binding sequence data types, iterators, the slicing protocol, etc.
81==================================================================
82
83Please refer to the supplemental example for details.
84
85.. seealso::
86
87 The file :file:`tests/test_sequences_and_iterators.cpp` contains a
88 complete example that shows how to bind a sequence data type, including
89 length queries (``__len__``), iterators (``__iter__``), the slicing
90 protocol and other kinds of useful operations.
91
92
93Partitioning code over multiple extension modules
94=================================================
95
96It's straightforward to split binding code over multiple extension modules,
97while referencing types that are declared elsewhere. Everything "just" works
98without any special precautions. One exception to this rule occurs when
99extending a type declared in another extension module. Recall the basic example
100from Section :ref:`inheritance`.
101
102.. code-block:: cpp
103
104 py::class_<Pet> pet(m, "Pet");
105 pet.def(py::init<const std::string &>())
106 .def_readwrite("name", &Pet::name);
107
108 py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
109 .def(py::init<const std::string &>())
110 .def("bark", &Dog::bark);
111
112Suppose now that ``Pet`` bindings are defined in a module named ``basic``,
113whereas the ``Dog`` bindings are defined somewhere else. The challenge is of
114course that the variable ``pet`` is not available anymore though it is needed
115to indicate the inheritance relationship to the constructor of ``class_<Dog>``.
116However, it can be acquired as follows:
117
118.. code-block:: cpp
119
120 py::object pet = (py::object) py::module::import("basic").attr("Pet");
121
122 py::class_<Dog>(m, "Dog", pet)
123 .def(py::init<const std::string &>())
124 .def("bark", &Dog::bark);
125
126Alternatively, you can specify the base class as a template parameter option to
127``class_``, which performs an automated lookup of the corresponding Python
128type. Like the above code, however, this also requires invoking the ``import``
129function once to ensure that the pybind11 binding code of the module ``basic``
130has been executed:
131
132.. code-block:: cpp
133
134 py::module::import("basic");
135
136 py::class_<Dog, Pet>(m, "Dog")
137 .def(py::init<const std::string &>())
138 .def("bark", &Dog::bark);
139
140Naturally, both methods will fail when there are cyclic dependencies.
141
142Note that compiling code which has its default symbol visibility set to
143*hidden* (e.g. via the command line flag ``-fvisibility=hidden`` on GCC/Clang) can interfere with the
144ability to access types defined in another extension module. Workarounds
145include changing the global symbol visibility (not recommended, because it will
146lead unnecessarily large binaries) or manually exporting types that are
147accessed by multiple extension modules:
148
149.. code-block:: cpp
150
151 #ifdef _WIN32
152 # define EXPORT_TYPE __declspec(dllexport)
153 #else
154 # define EXPORT_TYPE __attribute__ ((visibility("default")))
155 #endif
156
157 class EXPORT_TYPE Dog : public Animal {
158 ...
159 };
160
Ivan Smirnovf95fda02016-10-31 21:40:11 +0000161Note also that it is possible (although would rarely be required) to share arbitrary
162C++ objects between extension modules at runtime. Internal library data is shared
163between modules using capsule machinery [#f6]_ which can be also utilized for
164storing, modifying and accessing user-defined data. Note that an extension module
165will "see" other extensions' data if and only if they were built with the same
166pybind11 version. Consider the following example:
167
168.. code-block:: cpp
169
170 auto data = (MyData *) py::get_shared_data("mydata");
171 if (!data)
172 data = (MyData *) py::set_shared_data("mydata", new MyData(42));
173
174If the above snippet was used in several separately compiled extension modules,
175the first one to be imported would create a ``MyData`` instance and associate
176a ``"mydata"`` key with a pointer to it. Extensions that are imported later
177would be then able to access the data behind the same pointer.
178
179.. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules
Dean Moldovan67b52d82016-10-16 19:12:43 +0200180
Wenzel Jakobb16421e2017-03-22 22:04:00 +0100181Module Destructors
182==================
183
184pybind11 does not provide an explicit mechanism to invoke cleanup code at
185module destruction time. In rare cases where such functionality is required, it
186is possible to emulate it using Python capsules with a destruction callback.
187
188.. code-block:: cpp
189
190 auto cleanup_callback = []() {
191 // perform cleanup here -- this function is called with the GIL held
192 };
193
194 m.add_object("_cleanup", py::capsule(cleanup_callback));
Dean Moldovan67b52d82016-10-16 19:12:43 +0200195
196Generating documentation using Sphinx
197=====================================
198
199Sphinx [#f4]_ has the ability to inspect the signatures and documentation
200strings in pybind11-based extension modules to automatically generate beautiful
201documentation in a variety formats. The python_example repository [#f5]_ contains a
202simple example repository which uses this approach.
203
204There are two potential gotchas when using this approach: first, make sure that
205the resulting strings do not contain any :kbd:`TAB` characters, which break the
206docstring parsing routines. You may want to use C++11 raw string literals,
207which are convenient for multi-line comments. Conveniently, any excess
208indentation will be automatically be removed by Sphinx. However, for this to
209work, it is important that all lines are indented consistently, i.e.:
210
211.. code-block:: cpp
212
213 // ok
214 m.def("foo", &foo, R"mydelimiter(
215 The foo function
216
217 Parameters
218 ----------
219 )mydelimiter");
220
221 // *not ok*
222 m.def("foo", &foo, R"mydelimiter(The foo function
223
224 Parameters
225 ----------
226 )mydelimiter");
227
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100228By default, pybind11 automatically generates and prepends a signature to the docstring of a function
229registered with ``module::def()`` and ``class_::def()``. Sometimes this
230behavior is not desirable, because you want to provide your own signature or remove
231the docstring completely to exclude the function from the Sphinx documentation.
232The class ``options`` allows you to selectively suppress auto-generated signatures:
233
234.. code-block:: cpp
235
236 PYBIND11_PLUGIN(example) {
237 py::module m("example", "pybind11 example plugin");
238
239 py::options options;
240 options.disable_function_signatures();
241
242 m.def("add", [](int a, int b) { return a + b; }, "A function which adds two numbers");
243
244 return m.ptr();
245 }
246
247Note that changes to the settings affect only function bindings created during the
248lifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function,
249the default settings are restored to prevent unwanted side effects.
250
Dean Moldovan67b52d82016-10-16 19:12:43 +0200251.. [#f4] http://www.sphinx-doc.org
252.. [#f5] http://github.com/pybind/python_example