blob: 2968f8ac1292770cfd4cf16dbe6f687fb1076b3b [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
18
19Global Interpreter Lock (GIL)
20=============================
21
22The classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
23used to acquire and release the global interpreter lock in the body of a C++
24function call. In this way, long-running C++ code can be parallelized using
25multiple Python threads. Taking :ref:`overriding_virtuals` as an example, this
26could be realized as follows (important changes highlighted):
27
28.. code-block:: cpp
29 :emphasize-lines: 8,9,33,34
30
31 class PyAnimal : public Animal {
32 public:
33 /* Inherit the constructors */
34 using Animal::Animal;
35
36 /* Trampoline (need one for each virtual function) */
37 std::string go(int n_times) {
38 /* Acquire GIL before calling Python code */
39 py::gil_scoped_acquire acquire;
40
41 PYBIND11_OVERLOAD_PURE(
42 std::string, /* Return type */
43 Animal, /* Parent class */
44 go, /* Name of function */
45 n_times /* Argument(s) */
46 );
47 }
48 };
49
50 PYBIND11_PLUGIN(example) {
51 py::module m("example", "pybind11 example plugin");
52
53 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 });
66
67 return m.ptr();
68 }
69
70
71Binding sequence data types, iterators, the slicing protocol, etc.
72==================================================================
73
74Please refer to the supplemental example for details.
75
76.. seealso::
77
78 The file :file:`tests/test_sequences_and_iterators.cpp` contains a
79 complete example that shows how to bind a sequence data type, including
80 length queries (``__len__``), iterators (``__iter__``), the slicing
81 protocol and other kinds of useful operations.
82
83
84Partitioning code over multiple extension modules
85=================================================
86
87It's straightforward to split binding code over multiple extension modules,
88while referencing types that are declared elsewhere. Everything "just" works
89without any special precautions. One exception to this rule occurs when
90extending a type declared in another extension module. Recall the basic example
91from Section :ref:`inheritance`.
92
93.. code-block:: cpp
94
95 py::class_<Pet> pet(m, "Pet");
96 pet.def(py::init<const std::string &>())
97 .def_readwrite("name", &Pet::name);
98
99 py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
100 .def(py::init<const std::string &>())
101 .def("bark", &Dog::bark);
102
103Suppose now that ``Pet`` bindings are defined in a module named ``basic``,
104whereas the ``Dog`` bindings are defined somewhere else. The challenge is of
105course that the variable ``pet`` is not available anymore though it is needed
106to indicate the inheritance relationship to the constructor of ``class_<Dog>``.
107However, it can be acquired as follows:
108
109.. code-block:: cpp
110
111 py::object pet = (py::object) py::module::import("basic").attr("Pet");
112
113 py::class_<Dog>(m, "Dog", pet)
114 .def(py::init<const std::string &>())
115 .def("bark", &Dog::bark);
116
117Alternatively, you can specify the base class as a template parameter option to
118``class_``, which performs an automated lookup of the corresponding Python
119type. Like the above code, however, this also requires invoking the ``import``
120function once to ensure that the pybind11 binding code of the module ``basic``
121has been executed:
122
123.. code-block:: cpp
124
125 py::module::import("basic");
126
127 py::class_<Dog, Pet>(m, "Dog")
128 .def(py::init<const std::string &>())
129 .def("bark", &Dog::bark);
130
131Naturally, both methods will fail when there are cyclic dependencies.
132
133Note that compiling code which has its default symbol visibility set to
134*hidden* (e.g. via the command line flag ``-fvisibility=hidden`` on GCC/Clang) can interfere with the
135ability to access types defined in another extension module. Workarounds
136include changing the global symbol visibility (not recommended, because it will
137lead unnecessarily large binaries) or manually exporting types that are
138accessed by multiple extension modules:
139
140.. code-block:: cpp
141
142 #ifdef _WIN32
143 # define EXPORT_TYPE __declspec(dllexport)
144 #else
145 # define EXPORT_TYPE __attribute__ ((visibility("default")))
146 #endif
147
148 class EXPORT_TYPE Dog : public Animal {
149 ...
150 };
151
152
153
154Generating documentation using Sphinx
155=====================================
156
157Sphinx [#f4]_ has the ability to inspect the signatures and documentation
158strings in pybind11-based extension modules to automatically generate beautiful
159documentation in a variety formats. The python_example repository [#f5]_ contains a
160simple example repository which uses this approach.
161
162There are two potential gotchas when using this approach: first, make sure that
163the resulting strings do not contain any :kbd:`TAB` characters, which break the
164docstring parsing routines. You may want to use C++11 raw string literals,
165which are convenient for multi-line comments. Conveniently, any excess
166indentation will be automatically be removed by Sphinx. However, for this to
167work, it is important that all lines are indented consistently, i.e.:
168
169.. code-block:: cpp
170
171 // ok
172 m.def("foo", &foo, R"mydelimiter(
173 The foo function
174
175 Parameters
176 ----------
177 )mydelimiter");
178
179 // *not ok*
180 m.def("foo", &foo, R"mydelimiter(The foo function
181
182 Parameters
183 ----------
184 )mydelimiter");
185
186.. [#f4] http://www.sphinx-doc.org
187.. [#f5] http://github.com/pybind/python_example