blob: dc2b97618f641b294b8a56af0b430dcdd75ee243 [file] [log] [blame]
Wenzel Jakobde623a72016-03-09 21:11:19 +01001Frequently asked questions
2##########################
3
Wenzel Jakobc62360d2016-05-03 14:32:47 +02004"ImportError: dynamic module does not define init function"
5===========================================================
Wenzel Jakob50ed3612016-04-11 17:38:25 +02006
Dean Moldovan443ab592017-04-24 01:51:44 +02007You are likely using an incompatible version of Python (for instance, the
8extension library was compiled against Python 2, while the interpreter is
9running on top of some version of Python 3, or vice versa).
Wenzel Jakobc62360d2016-05-03 14:32:47 +020010
11"Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
12========================================================================
13
Dean Moldovan443ab592017-04-24 01:51:44 +020014See the first answer.
Wenzel Jakobc62360d2016-05-03 14:32:47 +020015
Wenzel Jakob70f5a4d2016-09-05 17:19:18 +090016"SystemError: dynamic module not initialized properly"
17======================================================
18
Dean Moldovan443ab592017-04-24 01:51:44 +020019See the first answer.
Wenzel Jakob70f5a4d2016-09-05 17:19:18 +090020
Wenzel Jakobc62360d2016-05-03 14:32:47 +020021The Python interpreter immediately crashes when importing my module
22===================================================================
23
Dean Moldovan443ab592017-04-24 01:51:44 +020024See the first answer.
Wenzel Jakob50ed3612016-04-11 17:38:25 +020025
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020026CMake doesn't detect the right Python version
27=============================================
Wenzel Jakoba439cca2016-05-17 10:47:52 +020028
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020029The CMake-based build system will try to automatically detect the installed
30version of Python and link against that. When this fails, or when there are
31multiple versions of Python and it finds the wrong one, delete
32``CMakeCache.txt`` and then invoke CMake as follows:
Wenzel Jakoba439cca2016-05-17 10:47:52 +020033
34.. code-block:: bash
35
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020036 cmake -DPYTHON_EXECUTABLE:FILEPATH=<path-to-python-executable> .
Wenzel Jakoba439cca2016-05-17 10:47:52 +020037
Wenzel Jakobde623a72016-03-09 21:11:19 +010038Limitations involving reference arguments
39=========================================
40
41In C++, it's fairly common to pass arguments using mutable references or
42mutable pointers, which allows both read and write access to the value
43supplied by the caller. This is sometimes done for efficiency reasons, or to
44realize functions that have multiple return values. Here are two very basic
45examples:
46
47.. code-block:: cpp
48
49 void increment(int &i) { i++; }
50 void increment_ptr(int *i) { (*i)++; }
51
52In Python, all arguments are passed by reference, so there is no general
53issue in binding such code from Python.
54
55However, certain basic Python types (like ``str``, ``int``, ``bool``,
56``float``, etc.) are **immutable**. This means that the following attempt
57to port the function to Python doesn't have the same effect on the value
58provided by the caller -- in fact, it does nothing at all.
59
60.. code-block:: python
61
62 def increment(i):
63 i += 1 # nope..
64
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010065pybind11 is also affected by such language-level conventions, which means that
66binding ``increment`` or ``increment_ptr`` will also create Python functions
67that don't modify their arguments.
Wenzel Jakobde623a72016-03-09 21:11:19 +010068
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010069Although inconvenient, one workaround is to encapsulate the immutable types in
Wenzel Jakob2e03a582016-04-14 11:27:15 +020070a custom type that does allow modifications.
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010071
72An other alternative involves binding a small wrapper lambda function that
73returns a tuple with all output arguments (see the remainder of the
74documentation for examples on binding lambda functions). An example:
75
76.. code-block:: cpp
77
78 int foo(int &i) { i++; return 123; }
79
80and the binding code
81
82.. code-block:: cpp
83
84 m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
85
Wenzel Jakob2e03a582016-04-14 11:27:15 +020086
Wenzel Jakobc79dbe42016-04-17 21:54:31 +020087How can I reduce the build time?
88================================
89
Jason Rhinelanderfb7c9fd2016-10-22 12:54:33 -040090It's good practice to split binding code over multiple files, as in the
91following example:
92
93:file:`example.cpp`:
Wenzel Jakobc79dbe42016-04-17 21:54:31 +020094
95.. code-block:: cpp
96
97 void init_ex1(py::module &);
98 void init_ex2(py::module &);
99 /* ... */
100
Dean Moldovan443ab592017-04-24 01:51:44 +0200101 PYBIND11_MODULE(example, m) {
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200102 init_ex1(m);
103 init_ex2(m);
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200104 /* ... */
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200105 }
106
Jason Rhinelanderfb7c9fd2016-10-22 12:54:33 -0400107:file:`ex1.cpp`:
108
109.. code-block:: cpp
110
111 void init_ex1(py::module &m) {
112 m.def("add", [](int a, int b) { return a + b; });
113 }
114
115:file:`ex2.cpp`:
116
117.. code-block:: cpp
118
David Caron307ea6b2018-04-24 10:16:18 -0400119 void init_ex2(py::module &m) {
Jason Rhinelanderfb7c9fd2016-10-22 12:54:33 -0400120 m.def("sub", [](int a, int b) { return a - b; });
121 }
122
123:command:`python`:
124
125.. code-block:: pycon
126
127 >>> import example
128 >>> example.add(1, 2)
129 3
130 >>> example.sub(1, 1)
131 0
132
133As shown above, the various ``init_ex`` functions should be contained in
134separate files that can be compiled independently from one another, and then
135linked together into the same final shared object. Following this approach
136will:
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200137
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001381. reduce memory requirements per compilation unit.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200139
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001402. enable parallel builds (if desired).
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200141
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001423. allow for faster incremental builds. For instance, when a single class
Jason Rhinelander20ef6262016-09-21 13:39:02 -0400143 definition is changed, only a subset of the binding code will generally need
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200144 to be recompiled.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200145
Wenzel Jakob2fb5f1d2016-11-16 17:36:54 +0100146"recursive template instantiation exceeded maximum depth of 256"
147================================================================
148
149If you receive an error about excessive recursive template evaluation, try
150specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The
151culprit is generally the generation of function signatures at compile time
152using C++14 template metaprogramming.
153
Jason Rhinelander97aa54f2017-08-10 12:08:42 -0400154.. _`faq:hidden_visibility`:
155
156"‘SomeClass’ declared with greater visibility than the type of its field ‘SomeClass::member’ [-Wattributes]"
157============================================================================================================
158
159This error typically indicates that you are compiling without the required
160``-fvisibility`` flag. pybind11 code internally forces hidden visibility on
161all internal code, but if non-hidden (and thus *exported*) code attempts to
162include a pybind type (for example, ``py::object`` or ``py::list``) you can run
163into this warning.
164
165To avoid it, make sure you are specifying ``-fvisibility=hidden`` when
166compiling pybind code.
167
168As to why ``-fvisibility=hidden`` is necessary, because pybind modules could
169have been compiled under different versions of pybind itself, it is also
170important that the symbols defined in one module do not clash with the
171potentially-incompatible symbols defined in another. While Python extension
172modules are usually loaded with localized symbols (under POSIX systems
173typically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default
174can be changed, but even if it isn't it is not always enough to guarantee
175complete independence of the symbols involved when not using
176``-fvisibility=hidden``.
177
178Additionally, ``-fvisiblity=hidden`` can deliver considerably binary size
179savings. (See the following section for more details).
180
Wenzel Jakob2fb5f1d2016-11-16 17:36:54 +0100181
Lori A. Burns5cafc992016-12-13 10:55:38 -0500182.. _`faq:symhidden`:
183
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200184How can I create smaller binaries?
185==================================
186
187To do its job, pybind11 extensively relies on a programming technique known as
188*template metaprogramming*, which is a way of performing computation at compile
189time using type information. Template metaprogamming usually instantiates code
190involving significant numbers of deeply nested types that are either completely
Jason Rhinelander20ef6262016-09-21 13:39:02 -0400191removed or reduced to just a few instructions during the compiler's optimization
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200192phase. However, due to the nested nature of these types, the resulting symbol
193names in the compiled extension library can be extremely long. For instance,
194the included test suite contains the following symbol:
195
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200196.. only:: html
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200197
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200198 .. code-block:: none
199
Wenzel Jakobfe342412016-09-06 13:02:29 +0900200 _​_​Z​N​8​p​y​b​i​n​d​1​1​1​2​c​p​p​_​f​u​n​c​t​i​o​n​C​1​I​v​8​E​x​a​m​p​l​e​2​J​R​N​S​t​3​_​_​1​6​v​e​c​t​o​r​I​N​S​3​_​1​2​b​a​s​i​c​_​s​t​r​i​n​g​I​w​N​S​3​_​1​1​c​h​a​r​_​t​r​a​i​t​s​I​w​E​E​N​S​3​_​9​a​l​l​o​c​a​t​o​r​I​w​E​E​E​E​N​S​8​_​I​S​A​_​E​E​E​E​E​J​N​S​_​4​n​a​m​e​E​N​S​_​7​s​i​b​l​i​n​g​E​N​S​_​9​i​s​_​m​e​t​h​o​d​E​A​2​8​_​c​E​E​E​M​T​0​_​F​T​_​D​p​T​1​_​E​D​p​R​K​T​2​_
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200201
202.. only:: not html
203
204 .. code-block:: cpp
205
206 __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200207
208which is the mangled form of the following function type:
209
210.. code-block:: cpp
211
212 pybind11::cpp_function::cpp_function<void, Example2, std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28])
213
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200214The memory needed to store just the mangled name of this function (196 bytes)
215is larger than the actual piece of code (111 bytes) it represents! On the other
216hand, it's silly to even give this function a name -- after all, it's just a
217tiny cog in a bigger piece of machinery that is not exposed to the outside
218world. So we'll generally only want to export symbols for those functions which
219are actually called from the outside.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200220
221This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
Jason Rhinelander97aa54f2017-08-10 12:08:42 -0400222and Clang, which sets the default symbol visibility to *hidden*, which has a
223tremendous impact on the final binary size of the resulting extension library.
224(On Visual Studio, symbols are already hidden by default, so nothing needs to
225be done there.)
226
227In addition to decreasing binary size, ``-fvisibility=hidden`` also avoids
228potential serious issues when loading multiple modules and is required for
229proper pybind operation. See the previous FAQ entry for more details.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200230
Marc Schlaichab003db2018-02-06 16:07:27 +0100231Working with ancient Visual Studio 2008 builds on Windows
Wenzel Jakobc62360d2016-05-03 14:32:47 +0200232=========================================================
233
234The official Windows distributions of Python are compiled using truly
235ancient versions of Visual Studio that lack good C++11 support. Some users
236implicitly assume that it would be impossible to load a plugin built with
237Visual Studio 2015 into a Python distribution that was compiled using Visual
Marc Schlaichab003db2018-02-06 16:07:27 +0100238Studio 2008. However, no such issue exists: it's perfectly legitimate to
Wenzel Jakobc62360d2016-05-03 14:32:47 +0200239interface DLLs that are built with different compilers and/or C libraries.
240Common gotchas to watch out for involve not ``free()``-ing memory region
241that that were ``malloc()``-ed in another shared library, using data
242structures with incompatible ABIs, and so on. pybind11 is very careful not
243to make these types of mistakes.
Wenzel Jakobe7d304f2017-11-17 18:44:20 +0100244
245How to cite this project?
246=========================
247
248We suggest the following BibTeX template to cite pybind11 in scientific
249discourse:
250
251.. code-block:: bash
252
253 @misc{pybind11,
254 author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan},
255 year = {2017},
256 note = {https://github.com/pybind/pybind11},
257 title = {pybind11 -- Seamless operability between C++11 and Python}
258 }
259